Parsing C# source code
Asked Answered
S

1

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.

Shepherd answered 29/9, 2014 at 5:51 Comment(7)
I'd suggest you look into using Roslyn instead of CodeDomProvider for this.Herbal
https://mcmap.net/q/50276/-microsoft-roslyn-vs-codedomRorrys
@JonSkeet any particular reasons why you would suggest that?Rorrys
@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#.Herbal
@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.Rorrys
@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.Herbal
@JonSkeet Well they're better reasonsRorrys
F
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.

Frasquito answered 29/9, 2014 at 5:55 Comment(4)
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.Rorrys
@Rorrys 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.Frasquito
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.Rorrys
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!Shepherd

© 2022 - 2024 — McMap. All rights reserved.