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

你离开我真会死。 提交于 2020-05-09 04:50:28

问题


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?


回答1:


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



回答2:


You'll want to look at creating a SyntaxWalker that walks over the entire tree and copies it to your output file, except for elements that are keyword tokens.




回答3:


Just for the record - following code also worked but 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);
    }

}


来源:https://stackoverflow.com/questions/26585869/how-to-replace-c-sharp-keywords-with-string-subsitutes-using-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!