SemanticModel Problems -- Syntax node is not within syntax tree

Topics: APIs, General
Feb 4, 2015 at 10:59 PM
I have a problem with SemanticModel while trying to use their GetSymbolInfo() functions. I'm trying to read and analyze several lines below:
private string displayError;
private void dummyMethod()
     foreach (string error in Messages)
          displayError = error;
I'm using MSBuildWorkspace to get the project files and it works fine. Now I want to see the error's data types (inside foreach loop) whether it's a string/int/etc. I'm planning to use the SemanticModel and get its symbol values to extract and give me (in this case) a string. My code looks like this given a Document object:
var tree = CSharpSyntaxTree.ParseFile(documents.FilePath);
var root = (CompilationUnitSyntax)tree.GetRoot();
var semanticModel = documents.GetSemanticModelAsync().Result;

var field = root.DescendantNodes().OfType<FieldDeclarationSyntax>().ToList().FirstOrDefault();
var binx = root.DescendantNodes().OfType<BinaryExpressionSyntax>().ToList().FirstOrDefault();

var name = field.Declaration.Variables.First();
SymbolInfo? info = semanticModel.GetSymbolInfo(name);                  // PASS
var identifier = binx.Right as IdentifierNameSyntax;
SymbolInfo? info1 = semanticModel.GetSymbolInfo(identifier);           // ERROR
It won't give an error for checking field members (displayError). Any idea what might be missing?
Feb 4, 2015 at 11:46 PM
why are you parsing the file directly?
var tree = CSharpSyntaxTree.ParseFile(documents.FilePath);
This will create a new syntax tree that is not a part of any compilation. When you look at the semantic model, it will not be able to tell you anything about the symbols because the tree is not part of the same compilation as the semanticModel. Instead you should get the root node from the document and ask for the declared symbol for nodes that declare new variables (semanticModel.GetDeclaredSymbol) and get symbol info when you want the symbol info for an identifier name (semanticModel.GetSymbolInfo)
var root = document.GetSyntaxRootAsync(cancellationToken).Result;
var semanticModel = document.GetSemanticModelAsync(cancellationToken).Result;

var field = root.DescendantNodes().OfType<FieldDeclarationSyntax>().FirstOrDefault();
var binx = root.DescendantNodes().OfType<BinaryExpressionSyntax>().FirstOrDefault();

var variableDeclarator = field.Declaration.Variables.First();
var variableDeclaratorSymbol = semanticModel.GetDeclaredSymbol(variableDeclarator);
var identifierName = binx.Right as IdentifierNameSyntax;
var identifierNameSymbolInfo = semanticModel.GetSymbolInfo(identifierName);
Feb 5, 2015 at 1:37 PM
Great, it works! So, in what occasion should we parse the file directly?
Feb 5, 2015 at 6:09 PM
ParseFile is there for when you don't need anything other than syntax nodes, or you want to construct your own compilation yourself.