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?
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++){}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With