using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
tree = CSharpSyntaxTree.ParseText(@"
public void test2(){ Console.WriteLine(""str""); }
Console.WriteLine(test1());
Console.WriteLine(test1(test2()));
compilation = CSharpCompilation.Create("HelloWorld").AddSyntaxTrees(tree);
model = compilation.GetSemanticModel(tree);
new Finder().Visit(tree.GetRoot());
Console.WriteLine(new Rewriter().Visit(tree.GetRoot()).NormalizeWhitespace().ToFullString());
public static class Globals
public static SyntaxTree tree;
public static CompilationUnitSyntax root;
public static CSharpCompilation compilation;
public static SemanticModel model;
public static Dictionary<IMethodSymbol, string> renames = new();
public sealed class Finder : CSharpSyntaxWalker
public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
base.VisitMethodDeclaration(node);
renames.Add(model.GetDeclaredSymbol(node), "prefix_" + node.Identifier.Value);
public sealed class Rewriter : CSharpSyntaxRewriter
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax mds)
IMethodSymbol symbol = model.GetDeclaredSymbol(mds);
mds = (MethodDeclarationSyntax)base.VisitMethodDeclaration(mds);
if (renames.TryGetValue(symbol, out string newName))
mds = mds.ReplaceToken(mds.Identifier, SyntaxFactory.Identifier(newName));
[return: NotNullIfNotNull("node")]
public override SyntaxNode Visit(SyntaxNode node)
if (node is SimpleNameSyntax sns &&
model.GetSymbolInfo(sns) is { Symbol: IMethodSymbol ms } && renames.TryGetValue(ms, out string newName)
node = sns.ReplaceToken(sns.Identifier, SyntaxFactory.Identifier(newName));