Joey
Joey

Reputation: 354794

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.)

Upvotes: 10

Views: 834

Answers (2)

Joey
Joey

Reputation: 354794

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.

Upvotes: 2

m0sa
m0sa

Reputation: 10940

nameof expressions are compile-time constant. You can use that fact to distinguish it from normal invocations. You can call SematicModel.GetConstantValue() on the InvocationExpressionSyntax. In case it's a nameof, you get back the string / name inside the Optional<object>.Value (HasValue also returns true).

Upvotes: 7

Related Questions