Roslyn完全限定的命名空间元数据错误

时间:2017-08-25 19:59:09

标签: c# location metadata roslyn fully-qualified-naming

我正在尝试创建一个代码分析器来检查完全限定的using语句。这个链接非常有帮助,也是我的解决方案的基础(How can I get the fully qualified namespace from a using directive in Roslyn?),但是当我尝试访问using指令的符号位置时,我遇到了问题。我的代码如下所示:

    private static void AnalyzeModel(SemanticModelAnalysisContext semanticModelAnalysisContext)
    {
        var semanticModel = semanticModelAnalysisContext.SemanticModel;
        var root = semanticModel.SyntaxTree.GetRoot();

        // compare each using statement's name with its fully qualified name
        foreach (var usingDirective in root.DescendantNodes().OfType<UsingDirectiveSyntax>())
        {
            var symbol = semanticModel.GetSymbolInfo(usingDirective.Name).Symbol;
            var fullyQualifiedName = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);

            if (fullyQualifiedName.Contains(GlobalTag))
            {
                fullyQualifiedName = fullyQualifiedName.Substring(GlobalTag.Length);
            }

            if (usingDirective.Name.ToString() != fullyQualifiedName)
            {
                // for each name that is not fully qualified, produce a diagnostic.
                var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name);
                semanticModelAnalysisContext.ReportDiagnostic(diagnostic);
            }
        }
    }

问题是symbol.Locations[0]仅包含元数据中的项目,而不包含源中的项目。这会导致以下错误:

Assert.IsTrue failed. Test base does not currently handle diagnostics in metadata locations.

我的单元测试中的源代码如下:

private const string incorrectSourceCode = @" namespace System { using IO; using Threading; }";

为什么symbol.Locations中没有项目来源?还有其他地方我可以获得这个位置吗?我尝试过使用symbol.ContainingSymbol.Locations[0]symbol.ContainingNamespace.Locations[0],但这些并不是指我感兴趣的使用特定用途。我已经把头发拉了几个小时,有些清晰了非常感谢。

提前致谢!

1 个答案:

答案 0 :(得分:2)

Symbol包含MetadateLocation,因此,如果您希望SourceLocation只是从相应的SyntaxNode检索它:

var diagnostic = Diagnostic.Create(Rule, usingDirective.Name.GetLocation(), symbol.Name)

而不是

var diagnostic = Diagnostic.Create(Rule, symbol.Locations[0], symbol.Name)