Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace C# keywords with string subsitutes using Roslyn?

I'd like to use Roslyn to load C# sources and write it to another file, replacing keywords with substitutes. Sample:

for (int i=0; i<10; i++){}

translated to

foobar (int i=0; i<10; i++){}

What the syntax for such operation could look like?

like image 626
tomash Avatar asked Dec 15 '22 19:12

tomash


1 Answers

I don't know how well is this going to work, but you can replace each ForKeyword token with another ForKeyword token, but this time with your custom text. To do that, you can use CSharpSyntaxRewriter:

class KeywordRewriter : CSharpSyntaxRewriter
{
    public override SyntaxToken VisitToken(SyntaxToken token)
    {
        if (token.Kind() == SyntaxKind.ForKeyword)
        {
            return SyntaxFactory.Token(
                token.LeadingTrivia, SyntaxKind.ForKeyword, "foobar", "foobar",
                token.TrailingTrivia);
        }

        return token;
    }
}

Using this rewriter, you can write code like this:

string code = "for (int i=0; i<10; i++){}";

var statement = SyntaxFactory.ParseStatement(code);

var rewrittenStatement = new KeywordRewriter().Visit(statement);

Console.WriteLine(rewrittenStatement);

Which prints what you wanted:

foobar (int i=0; i<10; i++){}
like image 115
svick Avatar answered Mar 03 '23 15:03

svick