【问题标题】:Curious ambiguity in attribute specification (two using directives)属性规范中奇怪的歧义(两个 using 指令)
【发布时间】:2020-01-03 12:34:50
【问题描述】:

背景:在attribute specification 中,有时有两种有效的方式来编写应用的属性。例如,如果属性类的名称为 HorseAttribute,您可以将该属性应用为 [HorseAttribute] 或只是 [Horse]。可以使用@ 解决歧义,例如[@Horse]。

以下是一个有效的程序:

using System;
using Alpha;
using Beta;

namespace N
{
  [Horse]
  class C
  {
  }
}

namespace Alpha
{
  // valid non-abstract attribute type with accessible constructor
  class HorseAttribute : Attribute
  {
  }
}

namespace Beta
{
  // any non-attribute type with that name
  enum Horse
  {
  }
}

当我只写[Horse] 时,C# 编译器能够选择Alpha.HorseAttribute。毕竟,Beta.Horse 类型完全不适合在属性规范中使用。

即使我交换名称,C# 编译器也会知道该怎么做:

using System;
using Alpha;
using Beta;

namespace N
{
  [Horse]
  class C
  {
  }
}

namespace Alpha
{
  // valid non-abstract attribute type with accessible constructor
  class Horse : Attribute
  {
  }
}

namespace Beta
{
  // any non-attribute type with that name
  enum HorseAttribute
  {
  }
}

同样,编译器知道我想要Alpha.Horse。


现在是我要询问的代码。它与上面的相同,只是现在这两种类型具有相同的名称:

using System;
using Alpha;
using Beta;

namespace N
{
  [Horse]
  class C
  {
  }
}

namespace Alpha
{
  // valid non-abstract attribute type with accessible constructor
  class Horse : Attribute
  {
  }
}

namespace Beta
{
  // any non-attribute type with that name
  enum Horse
  {
  }
}

现在,C# 编译器拒绝构建,说:

错误 CS0104:“马”是一个不明确的引用 在“Alpha.Horse”和“Beta.Horse”之间

Try it online!

我的问题是,为什么编译器不能在这种情况下选择正确的,而它在前面的两个示例中做得很好?

这种行为是否符合 C# 语言规范?是不是真的需要C#编译器在这里报错?

(当然我知道我可以通过明确地说 [Alpha.Horse] 来解决它,所以我不要求那个“解决方案”。)

【问题讨论】:

  • 有趣,看看他们的元数据看起来如何。
  • 我认为这是编译器与名称解析有关的特性。作为猜测,第一个有效,因为编译器查找 ___Attribute 并且只找到一个。第二个有效,因为它发现 ___Attribute 作为枚举并丢弃它。第三个失败是因为“让我们查找重复项”代码没有考虑到它必须是一个属性。
  • 您获得 CS0104 是因为您已将两个具有相同名称的类型导入到类中并且您正在使用该类型名称。属性的其余部分是一种干扰。如果枚举和属性类都被称为HorseAttribute,这个问题会更好。 tio.run/…

标签: c# compiler-errors custom-attributes .net-attributes


【解决方案1】:

Attribute 基本上是一个类型,enum 也是如此。这种模棱两可是标准行为。只需将您的思绪从class Horse 继承Attribute 中解放出来。从这个意义上说,将其视为一种类型。解析类型名称是编译器似乎要做的第一件事。之后检查属性(您尝试用作属性的东西)与Attribute 的兼容性。您指定全名的解决方案是唯一正确的。

更新:

看起来您希望 CS 编译器能够区分属性使用语义以及解析类型名称。可以使用这样的自定义代码分析器手动实现它:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public partial class AmbiguityAnalysisAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = "AA0001";

    private static readonly DiagnosticDescriptor Rule =
        new DiagnosticDescriptor(id: DiagnosticId,
                                 title: "Specify the attribute.",
                                 messageFormat: "Possible attribute '{0}' is ambiguous between {1}",
                                 category: "Attribute Usage",
                                 defaultSeverity: DiagnosticSeverity.Error,
                                 isEnabledByDefault: true,
                                 description: "Ambiguous attribute.");

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
        ImmutableArray.Create(Rule);

    public override void Initialize(AnalysisContext context) =>
        context.RegisterSemanticModelAction(SemanticModelAction);

    private void SemanticModelAction(SemanticModelAnalysisContext context)
    {
        var types = GetAllTypes(context.SemanticModel.Compilation).ToArray();
        var attributes = GetAllAttribute(context);
        var ambiguities = GetAmbiguities(types, attributes);
        foreach (var ambiguity in ambiguities)
            context.ReportDiagnostic(ambiguity);
    }
}

有

public partial class AmbiguityAnalysisAnalyzer
{
    private static IEnumerable<INamedTypeSymbol> GetAllTypes(Compilation compilation) =>
        GetAllTypes(compilation.GlobalNamespace);

    private static IEnumerable<INamedTypeSymbol> GetAllTypes(INamespaceSymbol @namespace)
    {
        foreach (var type in @namespace.GetTypeMembers())
            foreach (var nestedType in GetNestedTypes(type))
                yield return nestedType;

        foreach (var nestedNamespace in @namespace.GetNamespaceMembers())
            foreach (var type in GetAllTypes(nestedNamespace))
                yield return type;
    }

    private static IEnumerable<INamedTypeSymbol> GetNestedTypes(INamedTypeSymbol type)
    {
        yield return type;
        foreach (var nestedType in type.GetTypeMembers()
            .SelectMany(nestedType => GetNestedTypes(nestedType)))
            yield return nestedType;
    }

    private static AttributeSyntax[] GetAllAttribute(SemanticModelAnalysisContext context) =>
        context
        .SemanticModel
        .SyntaxTree
        .GetRoot()
        .DescendantNodes()
        .OfType<AttributeSyntax>()
        .ToArray();

    private static IEnumerable<Diagnostic> GetAmbiguities(INamedTypeSymbol[] types, AttributeSyntax[] attributes)
    {
        foreach (var attribute in attributes)
        {
            var usings = GetUsings(attribute.SyntaxTree);
            var ambiguities = GetAmbiguities(usings, types, attribute);

            if (ambiguities.Length < 2)
                continue;

            var suggestedAttributes = GetAttributes(ambiguities);
            var suggestedNonAttributes = GetNonAttributes(ambiguities);
            var parts =
                new[]
                {
                    GetPart("attributes", suggestedAttributes),
                    GetPart("non attributes", suggestedNonAttributes)
                }
                .Where(part => !part.Equals(string.Empty));

            var name = (attribute.Name as IdentifierNameSyntax)?.Identifier.ValueText;
            var suggestions =
                name == null ?
                ImmutableDictionary<string, string>.Empty :
                suggestedAttributes.Select(type => GetFullyQualifiedName(type))
                    .ToImmutableDictionary(type => type, type => name);

            var message = string.Join(" and ", parts);
            yield return Diagnostic.Create(Rule, attribute.GetLocation(), suggestions, attribute.Name, message);
        }
    }
}

和其他辅助方法

public partial class AmbiguityAnalysisAnalyzer
{
    private static string GetFullyQualifiedName(INamedTypeSymbol type)
    {
        var @namespace = GetFullName(type.ContainingNamespace, n => !n.IsGlobalNamespace, n => n.ContainingNamespace);
        var name = GetFullName(type, t => t != null, t => t.ContainingType);

        if (!@namespace.Equals(string.Empty, StringComparison.Ordinal))
            return $"{@namespace}.{name}";

        return name;
    }

    private static string[] GetUsings(SyntaxTree syntaxTree) =>
        syntaxTree
        .GetCompilationUnitRoot()
        .Usings.Select(GetUsingString)
        .Concat(new[] { string.Empty })
        .ToArray();

    private static string GetUsingString(UsingDirectiveSyntax @using) =>
        GetUsingStringFromName(@using.Name);

    private static string GetUsingStringFromName(NameSyntax name)
    {
        if (name is IdentifierNameSyntax identifierName)
            return identifierName.Identifier.ValueText;

        if (name is QualifiedNameSyntax qualifiedName)
            return $"{GetUsingStringFromName(qualifiedName.Left)}.{GetUsingStringFromName(qualifiedName.Right)}";

        throw new ArgumentException($"Argument '{nameof(name)}' was of unexpected type.");
    }

    private static INamedTypeSymbol[] GetAmbiguities(IEnumerable<string> usings, IEnumerable<INamedTypeSymbol> types, AttributeSyntax attribute) =>
        types
        .Where(t => attribute.Name is IdentifierNameSyntax name &&
                    NameMatches(t, name) &&
                    NamespaceInUsings(usings, t))
        .ToArray();

    private static bool NamespaceInUsings(IEnumerable<string> usings, INamedTypeSymbol type) =>
        usings.Contains(GetFullName(type.ContainingNamespace, n => !n.IsGlobalNamespace, n => n.ContainingNamespace));

    private static bool NameMatches(INamedTypeSymbol type, IdentifierNameSyntax nameSyntax)
    {
        var isVerbatim = nameSyntax.Identifier.Text.StartsWith("@");
        var name = nameSyntax.Identifier.ValueText;
        var names = isVerbatim ? new[] { name } : new[] { name, name + "Attribute" };
        var fullName = GetFullName(type, t => t != null, t => t.ContainingType);
        var res = names.Contains(fullName, StringComparer.Ordinal);
        return res;
    }

    private static string GetFullName<TSymbol>(TSymbol symbol, Func<TSymbol, bool> condition, Func<TSymbol, TSymbol> transition) where TSymbol : ISymbol
    {
        var values = new List<string>();
        while (condition(symbol))
        {
            values.Add(symbol.Name);
            symbol = transition(symbol);
        }
        values.Reverse();
        return string.Join(".", values);
    }

    private static IEnumerable<INamedTypeSymbol> GetAttributes(IEnumerable<INamedTypeSymbol> types) =>
        types.Where(type => IsAttribute(type));

    private static IEnumerable<INamedTypeSymbol> GetNonAttributes(IEnumerable<INamedTypeSymbol> types) =>
        types.Where(type => !IsAttribute(type));

    private static bool IsAttribute(INamedTypeSymbol type) =>
        type == null ?
        false :
        type.ContainingNamespace.Name.Equals("System", StringComparison.Ordinal) &&
        type.Name.Equals("Attribute", StringComparison.Ordinal) ||
        IsAttribute(type.BaseType);

    private static string GetPart(string description, IEnumerable<INamedTypeSymbol> types)
    {
        var part = string.Join(", ", types.Select(type => $"'{type}'"));
        if (!part.Equals(string.Empty))
            part = $"{description} {part}";
        return part;
    }
}

代码修复提供者可以是:

[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AmbiguityAnalysisCodeFixProvider)), Shared]
public class AmbiguityAnalysisCodeFixProvider : CodeFixProvider
{
    public sealed override ImmutableArray<string> FixableDiagnosticIds =>
        ImmutableArray.Create(AmbiguityAnalysisAnalyzer.DiagnosticId);

    public sealed override FixAllProvider GetFixAllProvider() =>
        WellKnownFixAllProviders.BatchFixer;

    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        var diagnostic = context.Diagnostics.First();

        var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
        var attribute =
            root
            .FindToken(diagnostic.Location.SourceSpan.Start)
            .Parent
            .AncestorsAndSelf()
            .OfType<AttributeSyntax>()
            .First();

        foreach(var suggestion in diagnostic.Properties)
        {
            var title = $"'{suggestion.Value}' to '{suggestion.Key}'";

            context.RegisterCodeFix(
                CodeAction.Create(
                    title: title,
                    createChangedSolution: c => ReplaceAttributeAsync(context.Document, attribute, suggestion.Key, c),
                    equivalenceKey: title),
                diagnostic);
        }
    }

    private static async Task<Solution> ReplaceAttributeAsync(Document document, AttributeSyntax oldAttribute, string suggestion, CancellationToken cancellationToken)
    {
        var name = SyntaxFactory.ParseName(suggestion);
        var newAttribute = SyntaxFactory.Attribute(name);
        var root = await document.GetSyntaxRootAsync().ConfigureAwait(false);
        root = root.ReplaceNode(oldAttribute, newAttribute);
        return document.Project.Solution.WithDocumentSyntaxRoot(document.Id, root);
    }
}

试试下面的代码来分析一下:

using System;
using Alpha;
using Alpha.Middle;
using Alpha.Middle.Omega;
using Beta;

public class Horse { }

namespace N
{
    [Horse]
    class C { }
}

namespace Alpha
{
    public class Horse : Attribute { }

    namespace Middle
    {
        public class Horse { }

        namespace Omega
        {
            public class Horse : Attribute { }
        }
    }
}

namespace Beta
{
    public enum Horse { }

    public class Foo
    {
        public class Horse : Attribute { }
    }
}

它给出错误:

CS0616 'Horse' 不是属性类

AA0001 可能的属性“Horse”在属性“Alpha.Horse”、“Alpha.Middle.Omega.Horse”和非属性“Horse”、“Alpha.Middle.Horse”、“Beta.Horse”之间不明确

建议的修复方法是:

“马”到“Alpha.Horse”

“马”到“Alpha.Middle.Omega.Horse”

【讨论】:

    【解决方案2】:

    我们这里有两个概念混为一谈。


    1.编译器如何知道哪个类实现了一个属性

    有一个简单的约定,即属性可以由类名或类名减去属性后缀来引用。所以当你像这样将[Horse] 注解添加到someIdentifier 时,

    [Horse]
    someIdentifier
    

    [Horse] 的实现必须是继承 Attribute 的类,该类被称为 HorseAttribute 或 Horse。

    注意:有一个被广泛接受的约定,即所有实现属性的类都应该在类型名称后加上“Attribute”。

    2。编译器如何知道代码所指的类型

    当我们在代码中引用一个类型时,编译器会查找已加载到命名空间中的该类型的定义。如果命名空间中有该类型的多个定义,则编译器不会采取任何措施来解决这种歧义,则由开发人员来改进代码。编译器不能选择所以会引发error CS1040。

    编译器不会进行任何语义或静态分析来判断编码人员的意图。这将难以定义、执行成本高且容易出错。

    此错误不仅仅在查找属性的实现时引发。


    在您的编译示例中,第 2 点没有歧义,因此代码可以编译。

    如果第 1 点的解析导致类型名称不明确,Horse 或 HorseAttribute,则错误将来自第 2 点。

    编译器没有特别考虑,例如我正在执行第 2 点以响应第 1 点,那么,如果我在这种情况下有歧义,是否有针对第 1 点执行的第 2 点的特殊回退位置?

    如果您考虑到特殊规定引入的额外复杂性和时间水平,您可能会接受要求代码作者提供一定程度的严格性会更好。

    在我和其他人看来,要求避免这种歧义的代码会导致代码更容易被他人和未来的自己理解。这使得关于为什么的讨论变得毫无意义,因为我们可以说编译器团队在此处所做的努力会使代码变得“更臭”,更难维护代码。


    注意:进一步回答

    当您考虑 Langauge specification 中的示例所表现出的行为时

    using System;
    
    [AttributeUsage(AttributeTargets.All)]
    public class X: Attribute
    {}
    
    [AttributeUsage(AttributeTargets.All)]
    public class XAttribute: Attribute
    {}
    
    [X]                     // Error: ambiguity
    class Class1 {}
    
    [XAttribute]            // Refers to XAttribute
    class Class2 {}
    
    [@X]                    // Refers to X
    class Class3 {}
    
    [@XAttribute]           // Refers to XAttribute
    class Class4 {}
    

    Try here

    我同意编译器处理来自一个命名空间的定义和从不同命名空间导入的定义的方式存在混淆,实际上是不一致。

    【讨论】:

    • 很好的解释。我想可以创建一个分析器来找出此类语义问题并在roslyn 的帮助下提出适当的修复建议。
    • @Alex,如果有人认为值得付出努力。编写或应用现有的分析器可能会更好,以确保属性实现名称以“属性”为后缀,也许另一个以确保相反。
    • 并让分析器检查class HorseAttribute : Attribute 和enum HorseAttribute 之类的情况,这些情况是可能的(尽管不太可能)。
    • 测试我的理解:如果我拿我的第一个例子,并在底部添加namespace Gamma { /* any non-attribute type with that name */ delegate int Horse(); },并在顶部添加using Gamma;,那么会发生什么?因为这一次将有 两种 类型命名为 Horse 加上一个类型命名为 HorseAttribute。编译器会采取哪些步骤,最终结果是什么?
    • 这里是another example,我觉得很困惑。
    【解决方案3】:

    这是编译器的不一致行为,即使它可能符合规范。恕我直言,第一种情况也应该是模棱两可的错误;编写该代码的人是否知道enum 不能在该上下文中使用并且可能正在尝试完全不同的东西(显然是错误的),这并不完全清楚。允许您省略 Attribute 的语法糖在此类情况下可能会遇到麻烦。

    我不是编译器如何工作的专家,但我认为这里发生的情况是,在编译器对源代码执行的第一次传递中,它必须查找所有省略的属性并将它们替换为类型的全名,woosh,歧义永远消失了。如果没有省略属性名称,则不会发生这种情况,因为名称没有被替换,然后在后面的步骤中会出现歧义错误。

    【讨论】:

    • 您说“恕我直言”的部分即使在第一种情况下也应该是一个模棱两可的错误,它没有回答语言规则是如何以及它们导致这种行为的原因。顺便说一句,我不同意你的观点;如果第一种情况是错误的,那会很烦人。因为同时拥有Xxx 和XxxAttribute 是一种很常见的模式。例如SmtpPermission 和SmtpPermissionAttribute,在命名空间System.Net.Mail 中有不同的类型。 BCL 中还有更多这样的例子。如果 C# 这么严格,你就不能优雅地使用这些属性。
    • 我同意@Jeppe,也不确定这个答案是否给出了意见以外的任何内容。
    猜你喜欢
    • 2016-10-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    相关资源
    最近更新 更多