Reputation: 11
I'm taking a look at being able to perform semantic analysis on C# scripts created via the CSharpScript API in Roslyn. However, all of my attempts to use the semantic model API have failed.
Here's my code, containing my methods so far and the stuff I tried (originally my Script declaration had options passed in with imports and references, but those don't seem to change my result here).
Script script = CSharpScript.Create("int x = 2; x += 1;");
script.Compile(); // doesn't seem to matter
Compilation compilation = script.GetCompilation();
SyntaxTree syntaxTree = compilation.SyntaxTrees.Single();
SyntaxNode syntaxTreeRoot = syntaxTree.GetRoot();
SemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree);
var firstVariable = syntaxTreeRoot.DescendantNodes().OfType<VariableDeclarationSyntax>().First();
IEnumerable<SyntaxNode> firstVariableParents = firstVariable.Ancestors();
IEnumerable<Diagnostic> diag = semanticModel.GetSyntaxDiagnostics();
IEnumerable<Diagnostic> declDiag = semanticModel.GetDeclarationDiagnostics();
SymbolInfo variableSymbol = semanticModel.GetSymbolInfo(firstVariable);
ISymbol variableDecl = semanticModel.GetDeclaredSymbol(firstVariable);
int breakpoint = 0;
I've tried getting various different kinds of syntax nodes out of the tree, and nothing is giving me any actual symbol information when I request it from the semantic model. For example, when I stop this code in the VS debugger on the breakpoint declaration, diag and declDiag are of length 0, variableDecl is null, and variableSymbol has zero candidates.
Any advice is appreciated!
Upvotes: 0
Views: 327
Reputation: 11
According to Cyrus Najmabadi on the Roslyn issues tracker:
VariableDeclarationSyntax refers to the entire declaration . i.e.: int i, j, k. So asking what 'declared symbol' you get from that has no meaning in C#. You need to get the individual "VariableDeclarator"s, and ask for GetDeclaredSymbol on those.
Once I used VariableDeclaratorSyntax instead of VariableDeclarationSyntax, I got what I needed.
Upvotes: 1
Reputation: 3513
To get the symbol for the variable declaration, you just need to call GetSymbolInfo
on the variable type like this:
var variableSymbol = semanticModel.GetSymbolInfo(firstVariable.Type);
This returns the symbol for the int
type.
Upvotes: 0