我正在研究如何对通过Roslyn中的CSharpScript应用程序接口创建的C#脚本执行语义分析。然而,我所有使用语义模型API的尝试都失败了。
下面是我的代码,其中包含我到目前为止使用的方法和我尝试过的东西(最初我的脚本声明有通过导入和引用传入的选项,但这些似乎不会改变我的结果)。
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;我尝试过从树中获取各种不同类型的语法节点,但是当我从语义模型请求符号信息时,没有任何东西给我任何实际的符号信息。例如,当我在VS调试器中的断点声明上停止这段代码时,variableDecl和declDiag的长度为0,diag为空,而variableSymbol的候选长度为零。
任何建议都是非常感谢的!
发布于 2018-02-27 06:42:33
根据Roslyn问题跟踪器上的Cyrus Najmabadi的说法:
VariableDeclarationSyntax指的是整个声明。例如: int i,j,k,所以问你从那里得到的‘声明符号’在C#中是没有意义的。您需要获取单独的“VariableDeclarator”,并在这些“GetDeclaredSymbol”上请求for。
一旦我使用VariableDeclaratorSyntax而不是VariableDeclarationSyntax,我就得到了我需要的东西。
发布于 2018-02-27 04:55:56
要获得变量声明的符号,只需对变量类型调用GetSymbolInfo,如下所示:
var variableSymbol = semanticModel.GetSymbolInfo(firstVariable.Type);这将返回int类型的符号。
https://stackoverflow.com/questions/48939754
复制相似问题