简体   繁体   中英

Roslyn Declare Local Variable with SyntaxGenerator

I am attempting to write a compiler for a proprietary language based off of C/C++/C#, but with the more complex features hidden. The compiler uses ANTLR to build it's own syntax tree, then uses the Roslyn SyntaxGenerator class to build the code in C#, which is then compiled as usual for C# code. My current issue is handling variables inside of functions: as it's fairly simple to declare a field, local variables don't seem to be discussed or clear to create. How do I create a local variable with the SyntaxGenerator class?

You use SyntaxGenerator.LocalDeclarationStatement .

For example, if you have initialized expression you can use it like this:

SyntaxGenerator generator = ...;
generator.LocalDeclarationStatement(
    "variable",
    generator.LiteralExpression(1));

This will create statement var variable = 1; .

Or if you just want to create variable but assign it later:

SyntaxGenerator generator = ...;     
generator.LocalDeclarationStatement(
    generator.TypeExpression(SpecialType.System_Int32),
    "variable");

This will generate statement int variable; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM