Joey Joey - 3 months ago 30
C# Question

Parsing nameof expressions in Roslyn

I'm trying to do something with

nameof
expressions in a
CSharpSyntaxWalker
, however, I noticed that there is no
NameOfExpressionSyntax
in the AST. Instead I get an
InvocationExpressionSyntax
for which
SemanticModel.GetSymbolInfo
returns no matching symbols, and the expression of the invocation is an
IdentifierNameSyntax
containing an identifier token
"nameof"
.

So to recognize
nameof
expressions I would have added a special case to
VisitInvocationExpression
, looking for whether
GetSymbolInfo
returns anything and if not, looking for whether the identifier is
nameof
. However, that sounds a bit iffy to me. Is there a better way maybe which shifts that sort of detection logic to the parser?

(P.S.: I know this is probably parsed like this for backwards compatibility reasons; just wondering whether there is an API for distinguishing
nameof
and normal invocations.)

Answer

I now indeed used the following snippet:

if (symbolInfo.Symbol == null &&
    symbolInfo.CandidateSymbols.IsEmpty &&
    symbolInfo.CandidateReason == CandidateReason.None) {
  var identifier = node.Expression as IdentifierNameSyntax;
  if (identifier != null && identifier.Identifier.Kind() == SyntaxKind.IdentifierToken && identifier.Identifier.Text == "nameof") {
    // We have a nameof expression
  }
}

I opted not to exploit the constant value for detection just in case C# 8 or so adds yet a different operator in that vein, that might also have a constant value, but is not nameof. The detection pretty much detects exactly what the specification says is used for determining an invocation being a nameof expression:

Because nameof is not a reserved keyword, a nameof expression is always syntactically ambiguous with an invocation of the simple name nameof. For compatibility reasons, if a name lookup of the name nameof succeeds, the expression is treated as an invocation_expression – regardless of whether the invocation is legal. Otherwise it is a nameof_expression.