Search code examples
roslynroslyn-code-analysis

How to ask Roslyn to generate an identifier name for me?


As the title says, how do I ask Roslyn to generate an identifier for me, similar to how the pattern matching code fixer or the generate method ones do?

enter image description here


Solution

  • Turns out there is an internal class inside Roslyn that does this, but it does much more than what I need.

    Instead, I simply used the semantic model to get the list of visible symbols at the start of my block's span, named my identifier the same as my type (just starting with a lowercase letter) and started adding numbers at the end of it until I get something that's not otherwise visible:

            var symbols = new HashSet<string>(semanticModel.LookupSymbols(bes.SpanStart).Select(s => s.Name));
    
            var baseIdentifierName = baseType is PredefinedTypeSyntax pts ? pts.Keyword.ValueText : throw new InvalidOperationException();
            if (isArray && !baseIdentifierName.EndsWith("s"))
                baseIdentifierName += "s";
            if (char.IsUpper(baseIdentifierName[0]))
                baseIdentifierName = $"{char.ToLower(baseIdentifierName[0])}{baseIdentifierName.Substring(1)}";
    
            var identifierName = baseIdentifierName;
            var index = 0;
            while (symbols.Contains(identifierName))
                identifierName = baseIdentifierName + ++index;