How do I replace C # keywords with string lists using Roslyn?

I would like to use Roslyn to load C # sources and write them to another file, replacing keywords with placeholders. Example:

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

      

translated into

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

      

What syntax for such an operation might look like?

+3


source to share


3 answers


I don't know how well this will work, but you can replace the token with ForKeyword

another token ForKeyword

, but this time with your custom text. To do this, 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;
    }
}

      

With 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++){}

      

+6


source


You want to look at an instantiation SyntaxWalker

that walks through the entire tree and copies it to the output file, except for items that are key tokens.



+2


source


Just for the record - the following code also worked, but the accepted answer is much more elegant.

foreach (var t in tree.GetCompilationUnitRoot().DescendantTokens())
{

    if (t.HasLeadingTrivia)
    {
        file.Write(t.LeadingTrivia);
    }

    file.Write(t.IsKind(SyntaxKind.ForKeyword)? "foobar" : t.ToString());

    if (t.HasTrailingTrivia)
    {
        file.Write(t.TrailingTrivia);
    }

}

      

+1


source







All Articles