9

I'm trying to parse a simple.cs source file using the following code:

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
var compileUnit = provider.Parse(File.OpenText(filename));

This gives me a NotImplementedException:

"This CodeDomProvider does not support this method"

Is it true that .NET does not provide an implemenation for parsing C# code? Or am I just using this class the wrong way?

Edit: The reason for doing this is that I want to toy around with some methods for static code analysis. Compiling or executing the code is not required for my research.

Boris
  • 8,551
  • 25
  • 67
  • 120
  • 3
    I'd suggest you look into using Roslyn instead of `CodeDomProvider` for this. – Jon Skeet Sep 29 '14 at 05:54
  • 1
    http://stackoverflow.com/questions/7852926/microsoft-roslyn-vs-codedom – Mick Sep 29 '14 at 06:23
  • @JonSkeet any particular reasons why you would suggest that? – Mick Sep 29 '14 at 07:01
  • 1
    @Mick: Well it's a rather more modern representation which the C# team has been working on for several years - and which can *definitely* parse C#. – Jon Skeet Sep 29 '14 at 07:16
  • @JonSkeet Pretty sure you can parse C# with the CSharpCodeProvider and depending on what Boris is trying to achieve, it could be a lot simpler. – Mick Sep 29 '14 at 23:54
  • 1
    @Mick: While you *may* be able to, the question doesn't make it sound promising - and I don't know what the future of CSharpCodeProvider is in terms of C# 6 etc. I know the team has said that C# 6 will *not* be implemented in the native compiler. The Roslyn representation is likely to be considerably richer than what CSharpCodeProvider gives, too. – Jon Skeet Sep 30 '14 at 05:49
  • @JonSkeet Well they're better reasons – Mick Sep 30 '14 at 07:32

1 Answers1

10

Yes, that's true, the CodeDomProvider is for emitting source code, not reading it. Various companies have their own parsers and recently Microsoft started project Roslyn that provides such features.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 1
    Your answer isn't correct, you can "read" source code and compile it with CodeDom... I think Roslyn, whilst very cool, it might be overkill for what he needs. – Mick Sep 29 '14 at 06:59
  • 1
    @Mick By "read", I meant you cannot generate a parsed syntax tree from code. You may be able to compile code, but you cannot access the `Parse` step of the compilation process alone. It's obviously in there somewhere but inaccessible to the user. – nvoigt Sep 29 '14 at 08:43
  • I think you're making assumptions about what he's trying to achieve, most people just want to spit out an assembly and execute it CSharpCodeProvider is pretty good at doing that and is simple to use. – Mick Sep 29 '14 at 23:57
  • 1
    I really want to get the syntax tree, not compile anything. So Microsoft keeps this part of their implementations locked away? I guess I'll have to wait for Roslyn then. Thanks! – Boris Sep 30 '14 at 05:25