Roslyn: Why `nameof` keyword is parsed to InvocationExpressionSyntax.

Created on 9 May 2019  路  2Comments  路  Source: dotnet/roslyn

image

Unlike sizeof keyword, nameof is always parsed to InvocationExpressionSyntax.

Even this won't be compiled to an __invocation__ because they're not a runtime data.

With the current version of __roslyn__, I have to write something like below:

void OnInvocationExpression(node) {
    if (node.Identifier == "nameof") {
        if (TARGET_CS6_OR_ABOVE) {
            /* nameof must be treated as KEYWORD */ 
        }
        else {
           /* nameof must be treated as FUNCTION NAME */
        }
    }
    else 
         ; // Usual invocation syntax
}

If they're treated as __keyword__, it can be more simpler.

void OnNameofExpression(node) {
    /* always guranteed CS6 or above */
}
Area-Compilers Question Resolution-Answered

Most helpful comment

The problem here is that nameof was a valid identifier before C# 6.0 and so, to avoid breaking changes, it is still a valid identifier in C# 6.0 and above. For a full list of situations where InvocationExpression with nameof is not considered to be the nameof operator, have a look at this compiler source code:

https://github.com/dotnet/roslyn/blob/9d7a2525194447d001ad9a906d57ff7e6da0d0d2/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs#L1506-L1517

This SO question has some suggestions on how to handle this situation in your code (assuming you have access to the SemanticModel).

All 2 comments

The problem here is that nameof was a valid identifier before C# 6.0 and so, to avoid breaking changes, it is still a valid identifier in C# 6.0 and above. For a full list of situations where InvocationExpression with nameof is not considered to be the nameof operator, have a look at this compiler source code:

https://github.com/dotnet/roslyn/blob/9d7a2525194447d001ad9a906d57ff7e6da0d0d2/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs#L1506-L1517

This SO question has some suggestions on how to handle this situation in your code (assuming you have access to the SemanticModel).

@svick Thanks, I didn't noticed that nameof still can be a valid ident after CS6.

Was this page helpful?
0 / 5 - 0 ratings