Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing nameof expressions in Roslyn

Tags:

c#

roslyn

nameof

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

like image 861
Joey Avatar asked Sep 05 '16 07:09

Joey


1 Answers

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

like image 174
m0sa Avatar answered Oct 21 '22 14:10

m0sa