ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c#-查找方法中使用了哪些using指令

2019-11-18 09:18:37  阅读:375  来源: 互联网

标签:roslyn roslyn-code-analysis c


我怎么知道在给定SyntaxNode的后代中使用了哪些using指令.

请参见以下示例:
https://dotnetfiddle.net/mCzNST
在这里,我想知道在Class1中使用了哪些用法,但是忽略了在Class2中使用的用法.

解决方法:

您可以使用语义模型获得与语法节点相关的类型.类型信息知道相关的名称空间,您可以使用该名称空间来标识相关的用途.遍历所有节点时,您会收到方法的返回值以及变量,属性和字段的类型.如果将节点限制为特定类型(例如InvocationExpressionSyntax),则只会获得返回类型,变量类型等.

private static IEnumerable<string> FindUsedUsings(SemanticModel model, SyntaxNode node)
{
    var resultList = new List<string>();
    foreach (var identifier in node.DescendantNodesAndSelf())
    {
        var typeInfo = model.GetTypeInfo(identifier);
        if (typeInfo.Type != null)
        {
            resultList.Add(typeInfo.Type.ContainingNamespace.ToDisplayString());
        }
    }
    return resultList.Distinct().ToList();
}

但是,如果您希望获得使用方法,则必须标识所有声明的类型.我写了一个(不完整的)解决方案来识别三种类型的必需用法:

using System;
using Text = System.String;
using static System.Console;

您可以使用不同的逻辑来识别每种使用类型.

对于第一种使用方式,您应考虑:

> var不需要使用
> PredefinedTypes(字符串,整数)不需要使用
>动态不需要使用
> QualifiedTypeNames不需要使用

对于第二种使用方式,您应考虑:

>尽管可以使用别名来解析类型,但是您也可以使用原始名称.使用上面的示例,您可以编写Statement字符串sample = Text.Empty;.

对于第三个使用类型,您没有该类型的标识符,因此您需要使用Expression语句查找调用.
请注意,在下面的解决方案中,将无法正确解析使用静态MyNamespace.Classname的方法,因为没有为该方法的IdentifierNameSyntax提供TypeSymbol,因此无法解析类型.

这可以解决两个问题:

>如果无法解析类型,则在分析类MyNamespace.Class2时可能会缺少使用静态MyNamespace.Classname的信息
>如果解析了类型,则在分析类MyNamespace.Classname时可能会使用静态MyNamespace.Classname无效(因为在类本身内不需要类型名.

考虑到这一点,这是我想出的解决方案.可能还有其他特殊情况需要考虑,但是我认为这是一个不错的起点:

private static IEnumerable<string> FindUsedUsings(SemanticModel model, 
            SyntaxNode node, SyntaxNode root)
{
    var aliasResolution = new Dictionary<string, string>();
    var usings = root.DescendantNodes().OfType<UsingDirectiveSyntax>();
    foreach (var curr in usings)
    {
        var nameEquals = curr.DescendantNodes().
            OfType<NameEqualsSyntax>().FirstOrDefault();
        if (nameEquals != null)
        {
            var qualifiedName =
                curr.DescendantNodes().OfType<QualifiedNameSyntax>().
                    FirstOrDefault()?.ToFullString();
            if (qualifiedName != null)
            {
                aliasResolution.Add(nameEquals.Name.Identifier.Text, qualifiedName);
            }
        }
    }
    var currentNamespace = node.Ancestors().
        OfType<NamespaceDeclarationSyntax>().FirstOrDefault();
    var namespacename = currentNamespace?.Name.ToString();
    if (namespacename == null)
    {
        // Empty namespace
        namespacename = string.Empty;
    }
    var resultList = new List<string>();
    foreach (var identifier in node.DescendantNodesAndSelf().OfType<TypeSyntax>())
    {
        if (identifier is PredefinedTypeSyntax || identifier.IsVar)
        {
            // No usings required for predefined types or var... 
            // [string, int, char, var, etc. do not need usings]
            continue;
        }
        // If an alias is defined use it prioritized
        if (GetUsingFromAlias(model, identifier, aliasResolution, resultList))
        {
            continue;
        }
        // If a type is provided, try to resolve it
        if (GetUsingFromType(model, identifier, namespacename, resultList))
        {
            continue;
        }
        // If no type is provided check if the expression 
        // corresponds to a static member call
        GetUsingFromStatic(model, identifier, resultList);
    }
    return resultList.Distinct().ToList();
}

private static void GetUsingFromStatic(SemanticModel model, TypeSyntax identifier, 
            List<string> resultList)
{
    var symbol = model.GetSymbolInfo(identifier).Symbol;
    // If the symbol (field, property, method call) can be resolved, 
    // is static and has a containing type
    if (symbol != null && symbol.IsStatic && symbol.ContainingType != null)
    {
        var memberAccess = identifier.Parent as ExpressionSyntax;
        if (memberAccess != null)
        {
            bool hasCallingType = false;
            var children = memberAccess.ChildNodes();
            foreach (var childNode in children)
            {
                // If the Expression has a Type 
                // (that is, if the expression is called from an identifyable source)
                // no using static is required
                var typeInfo = model.GetSymbolInfo(childNode).Symbol as INamedTypeSymbol;
                if (typeInfo != null)
                {
                    hasCallingType = true;
                    break;
                }
            }
            // if the type-Info is missing a static using is required
            if (!hasCallingType)
            {
                // type three using: using static [QualifiedType]
                resultList.Add($"static {symbol.ContainingType}");
            }
        }
    }
}

private static bool GetUsingFromType(SemanticModel model, TypeSyntax identifier, 
            string namespacename, List<string> resultList)
{
    var typeInfo = model.GetSymbolInfo(identifier).Symbol as INamedTypeSymbol;
    // dynamic is not required and not provided as an INamedTypeSymbol
    if (typeInfo != null)
    {
        if (identifier is QualifiedNameSyntax 
            || identifier.Parent is QualifiedNameSyntax)
        {
            // Qualified namespaces can be ignored...
            return true;
        }
        var containingNamespace = typeInfo.ContainingNamespace.ToDisplayString();
        // The current namespace need not be referenced
        if (namespacename == containingNamespace)
        {
            return true;
        }
        // Type one using: using [Namespace];
        resultList.Add(typeInfo.ContainingNamespace.ToDisplayString());
        return true;
    }
    return false;
}

private static bool GetUsingFromAlias(SemanticModel model, TypeSyntax identifier, 
            Dictionary<string, string> aliasResolution, List<string> resultList)
{
    var aliasInfo = model.GetAliasInfo(identifier);
    // If the identifier is an alias
    if (aliasInfo != null)
    {
        // check if it can be resolved
        if (aliasResolution.ContainsKey(aliasInfo.Name))
        {
            // Type two using: using [Alias] = [QualifiedType];
            resultList.Add($"{aliasInfo.Name} = {aliasResolution[aliasInfo.Name]}");
            return true;
        }
    }
    return false;
}

标签:roslyn,roslyn-code-analysis,c
来源: https://codeday.me/bug/20191118/2027117.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有