Newbee
Newbee

Reputation: 1032

Using Roslyn to replace identifiers in C#

I'm new in Roslyn and need the right direction from where to start.

My task is to write a tool to auto change identifiers of variables/functions/classes/etc in the SyntaxTree in order to meet our common naming standard.

For example:

public class t_user {
  public string m_name;
  public int m_age;
}
t_user[] inactive_users;

need to be changed to:

public class CUser {
  public string Name;
  public int Age;
}
CUser[] inactiveUsers;

So task looks like: get all declarations, generate new unique identifiers for each, change all occurrences in the tree.

Found some docs about Syntax Transformation with SyntaxRewriters but it looks too complex to start. I would be grateful for help in indicating the direction.

Thanks!

P.S. I need something like this:

SyntaxTree tree = CSharpSyntaxTree.ParseText ( File.ReadAllText(path) ); 
/* ...rename symbols... */ 
File.WriteAllText ( tree.ToString(), path );

with renamer function something like (just to start)

    static string renamer ( string id ){
        if( id.StartsWith("m_") ){
            return id.Substring(2,1).ToUpper()+id.Substring(3); // m_abc -> Abc
        }
        if( id.StartsWith("t_") ){
            return "C"+id.Substring(2,1).ToUpper()+id.Substring(3); // t_abc -> CAbc
        }
        return  id;
    }

Upvotes: 4

Views: 1070

Answers (1)

Dudi Keleti
Dudi Keleti

Reputation: 2984

You can't implement renamer just with strings manipulation. You must use symbols to understand the code and the symbolic meaning of each syntax node to know if it required renaming or not.

There is a renamer class that does it for you.

if you want to do it yourself as an exercise, you need to go over nodes, then get the symbol, check if it indeed node that you want to change (i.e field name for example and not a part of a using statement...), then find all locations\references\interface implementations and change it.

Upvotes: 1

Related Questions