I am writing a solution which requires an AST to be generated and then this AST should be parsed in order to generate a valid compilation unit with semantics available.
- The AST is generated by means of
SyntaxFactory
class. - Then I will need to get a
Compilation
somehow. - Then I will get a reference to
SemanticModel
from the compilation unit.
Creating the AST
The code I run for generating the AST is something like:
var classNode = SyntaxFactory.ClassDeclaration("MyCLass");
classNode = classNode.AddMembers(
SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("string"), "DoIt")
.WithBody(...));
...
Missing parts
The first part is ok as you can see. I can get my AST. But now I need to convert it into code? How to invoke the compiler on the AST?:
Compiler Compilation.GetSemanticModel(AST)
| |
+-----+ v +-----------------+ v +---------------+
+----> AST +-----> CompilationUnit +-----> SemanticModel |
^ +-----+ +-----------------+ +---------------+
| ^ ^
| |-----------------|
Factories ???
Note that the part relative to getting the SemanticModel
is covered as I simly need to use the Compilation
object and call GetSemanticModel
on that by passing the CSharpSyntaxTree
.
If you are wondering why this, it is because of a testing tool I am writing. Regardless of the use, this scenario should be possible. How?