PageRenderTime 117ms CodeModel.GetById 7ms app.highlight 71ms RepoModel.GetById 1ms app.codeStats 3ms

/Src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests.cs

https://github.com/EkardNT/Roslyn
C# | 7205 lines | 6075 code | 628 blank | 502 comment | 13 complexity | e1fd731c9f769cd979fe6505e83e503a MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
   2
   3using System;
   4using System.Collections.Generic;
   5using System.Collections.Immutable;
   6using System.IO;
   7using System.Linq;
   8using System.Reflection;
   9using Microsoft.CodeAnalysis.CSharp.Symbols;
  10using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
  11using Microsoft.CodeAnalysis.CSharp.Syntax;
  12using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
  13using Microsoft.CodeAnalysis.Test.Utilities;
  14using Roslyn.Test.Utilities;
  15using Xunit;
  16
  17namespace Microsoft.CodeAnalysis.CSharp.UnitTests
  18{
  19    public class AttributeTests : CompilingTestBase
  20    {
  21        #region Function Tests
  22
  23        [Fact]
  24        public void TestAssemblyAttributes()
  25        {
  26            var source = CreateCompilationWithMscorlib(@"
  27using System;
  28using System.Runtime.CompilerServices;
  29
  30[assembly: InternalsVisibleTo(""Roslyn.Compilers.UnitTests"")]
  31[assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp"")]
  32[assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.UnitTests"")]
  33[assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.Test.Utilities"")]
  34
  35[assembly: InternalsVisibleTo(""Roslyn.Compilers.VisualBasic"")]
  36class C
  37{
  38    public static void Main() {}
  39}
  40");
  41
  42            Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  43            {
  44                Symbol assembly = m.ContainingSymbol;
  45                var attrs = assembly.GetAttributes();
  46                Assert.Equal(5, attrs.Length);
  47                attrs[0].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.UnitTests");
  48                Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.UnitTests"")", attrs[0].ToString());
  49                attrs[1].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp");
  50                Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp"")", attrs[1].ToString());
  51                attrs[2].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.UnitTests");
  52                Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.UnitTests"")", attrs[2].ToString());
  53                attrs[3].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.Test.Utilities");
  54                Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.Test.Utilities"")", attrs[3].ToString());
  55                attrs[4].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.VisualBasic");
  56                Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.VisualBasic"")", attrs[4].ToString());
  57            };
  58
  59            // Verify attributes from source and then load metadata to see attributes are written correctly.
  60            CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  61        }
  62
  63        [WorkItem(984896)]
  64        [Fact]
  65        public void TestAssemblyAttributesErr()
  66        {
  67            string code = @"
  68using System;
  69using System.Collections.Generic;
  70using System.Linq;
  71using System.Linq.Expressions;
  72using System.Text;
  73using M = System.Math;
  74
  75namespace My
  76{
  77    using A.B;
  78
  79    // TODO: <Insert justification for suppressing TestId>
  80[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""Test"",""TestId"",Justification=""<Pending>"")]
  81public unsafe partial class A : C, I
  82    {
  83
  84    }
  85}
  86";
  87
  88            var source = CreateCompilationWithMscorlibAndSystemCore(code);
  89
  90            // the following should not crash
  91            source.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, source.SyntaxTrees[0], null, true);
  92        }
  93
  94
  95        [Fact, WorkItem(545326, "DevDiv")]
  96        public void TestAssemblyAttributes_Bug13670()
  97        {
  98            var source = @"
  99using System;
 100
 101[assembly: A(Derived.Str)]
 102
 103public class A: Attribute
 104{
 105  public A(string x){}
 106  public static void Main() {}
 107}
 108public class Derived: Base
 109{
 110    internal const string Str = ""temp"";
 111    public override int Foo { get { return 1; } }
 112}
 113public class Base
 114{
 115    public virtual int Foo { get { return 0; } }
 116}
 117";
 118            CompileAndVerify(source);
 119        }
 120
 121        [Fact]
 122        public void TestAssemblyAttributesReflection()
 123        {
 124            var compilation = CreateCompilationWithMscorlib(@"
 125using System.Reflection;
 126using System.Runtime.CompilerServices;
 127using System.Runtime.InteropServices;
 128
 129// These are not pseduo attributes, but encoded as bits in metadata
 130[assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)]
 131[assembly: AssemblyCultureAttribute("""")]
 132[assembly: AssemblyDelaySign(true)]
 133[assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)]
 134[assembly: AssemblyKeyFile(""MyKey.snk"")]
 135[assembly: AssemblyKeyName(""Key Name"")]
 136
 137[assembly: AssemblyVersion(""1.2.*"")]
 138[assembly: AssemblyFileVersionAttribute(""4.3.2.100"")]
 139class C
 140{
 141    public static void Main() {}
 142}
 143");
 144
 145            var attrs = compilation.Assembly.GetAttributes();
 146            Assert.Equal(8, attrs.Length);
 147
 148            foreach (var a in attrs)
 149            {
 150                switch (a.AttributeClass.Name)
 151                {
 152                    case "AssemblyAlgorithmIdAttribute":
 153                        a.VerifyValue(0, TypedConstantKind.Enum, (int)System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5);
 154                        Assert.Equal(@"System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)", a.ToString());
 155                        break;
 156                    case "AssemblyCultureAttribute":
 157                        a.VerifyValue(0, TypedConstantKind.Primitive, "");
 158                        Assert.Equal(@"System.Reflection.AssemblyCultureAttribute("""")", a.ToString());
 159                        break;
 160                    case "AssemblyDelaySignAttribute":
 161                        a.VerifyValue(0, TypedConstantKind.Primitive, true);
 162                        Assert.Equal(@"System.Reflection.AssemblyDelaySignAttribute(true)", a.ToString());
 163                        break;
 164                    case "AssemblyFlagsAttribute":
 165                        a.VerifyValue(0, TypedConstantKind.Enum, (int)AssemblyNameFlags.Retargetable);
 166                        Assert.Equal(@"System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.Retargetable)", a.ToString());
 167                        break;
 168                    case "AssemblyKeyFileAttribute":
 169                        a.VerifyValue(0, TypedConstantKind.Primitive, "MyKey.snk");
 170                        Assert.Equal(@"System.Reflection.AssemblyKeyFileAttribute(""MyKey.snk"")", a.ToString());
 171                        break;
 172                    case "AssemblyKeyNameAttribute":
 173                        a.VerifyValue(0, TypedConstantKind.Primitive, "Key Name");
 174                        Assert.Equal(@"System.Reflection.AssemblyKeyNameAttribute(""Key Name"")", a.ToString());
 175                        break;
 176                    case "AssemblyVersionAttribute":
 177                        a.VerifyValue(0, TypedConstantKind.Primitive, "1.2.*");
 178                        Assert.Equal(@"System.Reflection.AssemblyVersionAttribute(""1.2.*"")", a.ToString());
 179                        break;
 180                    case "AssemblyFileVersionAttribute":
 181                        a.VerifyValue(0, TypedConstantKind.Primitive, "4.3.2.100");
 182                        Assert.Equal(@"System.Reflection.AssemblyFileVersionAttribute(""4.3.2.100"")", a.ToString());
 183                        break;
 184                    default:
 185                        Assert.Equal("Unexpected Attr", a.AttributeClass.Name);
 186                        break;
 187                }
 188            }
 189        }
 190
 191        // Verify that resolving an attribute defined within a class on a class does not cause infinite recursion
 192        [Fact]
 193        public void TestAttributesOnClassDefinedInClass()
 194        {
 195            var compilation = CreateCompilationWithMscorlib(@"
 196using System;
 197using System.Runtime.CompilerServices;
 198
 199[A.X()]
 200public class A
 201{
 202    [AttributeUsage(AttributeTargets.All, allowMultiple = true)]
 203    public class XAttribute : Attribute
 204    {
 205    }
 206}
 207class C
 208{
 209    public static void Main() {}
 210}
 211");
 212            var attrs = compilation.SourceModule.GlobalNamespace.GetMember("A").GetAttributes();
 213            Assert.Equal(1, attrs.Length);
 214            Assert.Equal("A.XAttribute", attrs.First().AttributeClass.ToDisplayString());
 215        }
 216
 217        [Fact]
 218        public void TestAttributesOnClassWithConstantDefinedInClass()
 219        {
 220            var compilation = CreateCompilationWithMscorlib(@"
 221using System;
 222[Attr(Foo.p)]
 223class Foo
 224{
 225    private const object p = null;
 226}
 227internal class AttrAttribute : Attribute
 228{
 229    public AttrAttribute(object p) { }
 230}
 231class C
 232{
 233    public static void Main() { }
 234}
 235");
 236            var attrs = compilation.SourceModule.GlobalNamespace.GetMember("Foo").GetAttributes();
 237            Assert.Equal(1, attrs.Length);
 238            attrs.First().VerifyValue<object>(0, TypedConstantKind.Primitive, null);
 239        }
 240
 241        [Fact]
 242        public void TestAttributeEmit()
 243        {
 244            var compilation = CreateCompilationWithMscorlib(@"
 245using System;
 246public enum e1
 247{
 248    a,
 249    b,
 250    c
 251}
 252
 253[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
 254class XAttribute : Attribute
 255{
 256    public XAttribute(int i)
 257    {
 258    }
 259    public XAttribute(int i, string s)
 260    {
 261    }
 262    public XAttribute(int i, string s, e1 e)
 263    {
 264    }
 265    public XAttribute(object[] o)
 266    {
 267    }
 268    public XAttribute(int[] i)
 269    {
 270    }
 271    public XAttribute(int[] i, string[] s)
 272    {
 273    }
 274    public XAttribute(int[] i, string[] s, e1[] e)
 275    {
 276    }
 277    public int pi { get; set; }
 278    public string ps { get; set; }
 279    public e1 pe { get; set; }
 280}
 281
 282[X(1, ""hello"", e1.a)]
 283[X(new int[] { 1 }, new string[] { ""hello"" }, new e1[] { e1.a, e1.b, e1.c })]
 284[X(new object[] { 1, ""hello"", e1.a })]
 285class C
 286{
 287    public static void Main() {}
 288}
 289");
 290            var verifier = CompileAndVerify(compilation, emitOptions: EmitOptions.RefEmitUnsupported_640494);
 291            verifier.VerifyIL("XAttribute..ctor(int)", @"{
 292  // Code size        7 (0x7)
 293  .maxstack  1
 294  IL_0000:  ldarg.0   
 295  IL_0001:  call       ""System.Attribute..ctor()""
 296  IL_0006:  ret       
 297}");
 298        }
 299
 300        [Fact]
 301        public void TestAttributesOnClassProperty()
 302        {
 303            var compilation = CreateCompilationWithMscorlib(@"
 304using System;
 305public class A
 306{
 307    [CLSCompliant(true)]
 308    public string Prop
 309    {
 310        get { return null; }
 311    }
 312}
 313class C
 314{
 315    public static void Main() {}
 316}
 317");
 318            Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
 319            {
 320                var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A");
 321                var prop = type.GetMember("Prop");
 322                var attrs = prop.GetAttributes();
 323                Assert.Equal(1, attrs.Length);
 324                attrs.First().VerifyValue(0, TypedConstantKind.Primitive, true);
 325                Assert.Equal("System.CLSCompliantAttribute", attrs.First().AttributeClass.ToDisplayString());
 326            };
 327
 328            // Verify attributes from source and then load metadata to see attributes are written correctly.
 329            CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
 330        }
 331
 332        [WorkItem(688268, "DevDiv")]
 333        [Fact]
 334        public void Bug688268()
 335        {
 336            var compilation = CreateCompilationWithMscorlib(@"
 337using System;
 338using System.Runtime.InteropServices;
 339using System.Security;
 340
 341public interface I
 342{
 343    void _VtblGap1_30();
 344    void _VtblGaP1_30();
 345}
 346");
 347            System.Action<ModuleSymbol> metadataValidator =
 348                delegate (ModuleSymbol module)
 349            {
 350                var metadata = ((PEModuleSymbol)module).Module;
 351
 352                var typeI = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMembers("I").Single();
 353
 354                var methods = metadata.GetMethodsOfTypeOrThrow(typeI.Handle);
 355                Assert.Equal(2, methods.Count);
 356
 357                var e = methods.GetEnumerator();
 358                e.MoveNext();
 359                var flags = metadata.GetMethodDefFlagsOrThrow(e.Current);
 360                Assert.Equal(
 361                    MethodAttributes.PrivateScope |
 362                    MethodAttributes.Public |
 363                    MethodAttributes.Virtual |
 364                    MethodAttributes.HideBySig |
 365                    MethodAttributes.VtableLayoutMask |
 366                    MethodAttributes.Abstract |
 367                    MethodAttributes.SpecialName |
 368                    MethodAttributes.RTSpecialName,
 369                    flags);
 370
 371                e.MoveNext();
 372                flags = metadata.GetMethodDefFlagsOrThrow(e.Current);
 373                Assert.Equal(
 374                    MethodAttributes.PrivateScope |
 375                    MethodAttributes.Public |
 376                    MethodAttributes.Virtual |
 377                    MethodAttributes.HideBySig |
 378                    MethodAttributes.VtableLayoutMask |
 379                    MethodAttributes.Abstract,
 380                    flags);
 381            };
 382
 383            CompileAndVerify(
 384                compilation,
 385                sourceSymbolValidator: null,
 386                symbolValidator: metadataValidator);
 387        }
 388
 389        [Fact]
 390        public void TestAttributesOnPropertyAndGetSet()
 391        {
 392            string source = @"
 393using System;
 394[AObject(typeof(object), O = A.obj)]
 395public class A
 396{
 397    internal const object obj = null;
 398    public string RProp
 399    {
 400        [AObject(new object[] { typeof(string) })]
 401        get { return null; }
 402    }
 403
 404    [AObject(new object[] {
 405        1,
 406        ""two"",
 407        typeof(string),
 408        3.1415926
 409    })]
 410    public object WProp
 411    {
 412        [AObject(new object[] { new object[] { typeof(string) } })]
 413
 414        set { }
 415    }
 416}
 417";
 418            var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib.AsImmutableOrNull()) };
 419            CSharpCompilationOptions opt = TestOptions.Dll;
 420
 421            var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
 422
 423            Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
 424            {
 425                var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A");
 426                var attrs = type.GetAttributes();
 427                Assert.Equal("AObjectAttribute(typeof(object), O = null)", attrs.First().ToString());
 428                attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeof(object));
 429                attrs.First().VerifyNamedArgumentValue<object>(0, "O", TypedConstantKind.Primitive, null);
 430
 431                var prop = type.GetMember<PropertySymbol>("RProp");
 432                attrs = prop.GetMethod.GetAttributes();
 433                Assert.Equal("AObjectAttribute({typeof(string)})", attrs.First().ToString());
 434                attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { typeof(string) });
 435
 436                prop = type.GetMember<PropertySymbol>("WProp");
 437                attrs = prop.GetAttributes();
 438                Assert.Equal(@"AObjectAttribute({1, ""two"", typeof(string), 3.1415926})", attrs.First().ToString());
 439                attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { 1, "two", typeof(string), 3.1415926 });
 440                attrs = prop.SetMethod.GetAttributes();
 441                Assert.Equal(@"AObjectAttribute({{typeof(string)}})", attrs.First().ToString());
 442                attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { new object[] { typeof(string) } });
 443            };
 444
 445            // Verify attributes from source and then load metadata to see attributes are written correctly.
 446            CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator);
 447        }
 448
 449        [Fact]
 450        public void TestAttributesOnEvents()
 451        {
 452            string source = @"
 453public class AA : System.Attribute { }
 454public class BB : System.Attribute { }
 455public class CC : System.Attribute { }
 456public class DD : System.Attribute { }
 457public class EE : System.Attribute { }
 458public class FF : System.Attribute { }
 459public class GG : System.Attribute { }
 460public class HH : System.Attribute { }
 461public class II : System.Attribute { }
 462public class JJ : System.Attribute { }
 463
 464public class Test
 465{
 466    [AA] //in event decl
 467    public event System.Action E1;
 468    [event: BB] //in event decl
 469    public event System.Action E2;
 470    [method: CC] //in both accessors
 471    public event System.Action E3;
 472    [field: DD] //on field
 473    public event System.Action E4;
 474
 475    [EE] //in event decl
 476    public event System.Action E5 { add { } remove { } }
 477    [event: FF] //in event decl
 478    public event System.Action E6 { add { } remove { } }
 479
 480    public event System.Action E7 { [GG] add { } remove { } } //in accessor
 481    public event System.Action E8 { [method: HH] add { } remove { } } //in accessor
 482    public event System.Action E9 { [param: II] add { } remove { } } //on parameter (after .param[1])
 483    public event System.Action E10 { [return: JJ] add { } remove { } } //on return (after .param[0])
 484}
 485";
 486
 487            Func<bool, Action<ModuleSymbol>> symbolValidator = isFromSource => moduleSymbol =>
 488            {
 489                var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
 490
 491                var event1 = @class.GetMember<EventSymbol>("E1");
 492                var event2 = @class.GetMember<EventSymbol>("E2");
 493                var event3 = @class.GetMember<EventSymbol>("E3");
 494                var event4 = @class.GetMember<EventSymbol>("E4");
 495                var event5 = @class.GetMember<EventSymbol>("E5");
 496                var event6 = @class.GetMember<EventSymbol>("E6");
 497                var event7 = @class.GetMember<EventSymbol>("E7");
 498                var event8 = @class.GetMember<EventSymbol>("E8");
 499                var event9 = @class.GetMember<EventSymbol>("E9");
 500                var event10 = @class.GetMember<EventSymbol>("E10");
 501
 502                var accessorsExpected = isFromSource ? new string[0] : new[] { "CompilerGeneratedAttribute" };
 503
 504                Assert.Equal("AA", GetSingleAttributeName(event1));
 505                AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.AddMethod.GetAttributes()));
 506                AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.RemoveMethod.GetAttributes()));
 507
 508                if (isFromSource)
 509                {
 510                    AssertNoAttributes(event1.AssociatedField);
 511                    Assert.Equal(0, event1.GetFieldAttributes().Length);
 512                }
 513
 514                Assert.Equal("BB", GetSingleAttributeName(event2));
 515                AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.AddMethod.GetAttributes()));
 516                AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.RemoveMethod.GetAttributes()));
 517                if (isFromSource)
 518                {
 519                    AssertNoAttributes(event2.AssociatedField);
 520                    Assert.Equal(0, event2.GetFieldAttributes().Length);
 521                }
 522
 523                AssertNoAttributes(event3);
 524                AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.AddMethod.GetAttributes()));
 525                AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.RemoveMethod.GetAttributes()));
 526                if (isFromSource)
 527                {
 528                    AssertNoAttributes(event3.AssociatedField);
 529                    Assert.Equal(0, event3.GetFieldAttributes().Length);
 530                }
 531
 532                AssertNoAttributes(event4);
 533                AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.AddMethod.GetAttributes()));
 534                AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.RemoveMethod.GetAttributes()));
 535                if (isFromSource)
 536                {
 537                    Assert.Equal("DD", GetSingleAttributeName(event4.AssociatedField));
 538                    Assert.Equal("DD", event4.GetFieldAttributes().Single().AttributeClass.Name);
 539                }
 540
 541                Assert.Equal("EE", GetSingleAttributeName(event5));
 542                AssertNoAttributes(event5.AddMethod);
 543                AssertNoAttributes(event5.RemoveMethod);
 544
 545                Assert.Equal("FF", GetSingleAttributeName(event6));
 546                AssertNoAttributes(event6.AddMethod);
 547                AssertNoAttributes(event6.RemoveMethod);
 548
 549
 550                AssertNoAttributes(event7);
 551                Assert.Equal("GG", GetSingleAttributeName(event7.AddMethod));
 552                AssertNoAttributes(event7.RemoveMethod);
 553
 554                AssertNoAttributes(event8);
 555                Assert.Equal("HH", GetSingleAttributeName(event8.AddMethod));
 556                AssertNoAttributes(event8.RemoveMethod);
 557
 558                AssertNoAttributes(event9);
 559                AssertNoAttributes(event9.AddMethod);
 560                AssertNoAttributes(event9.RemoveMethod);
 561                Assert.Equal("II", GetSingleAttributeName(event9.AddMethod.Parameters.Single()));
 562
 563                AssertNoAttributes(event10);
 564                AssertNoAttributes(event10.AddMethod);
 565                AssertNoAttributes(event10.RemoveMethod);
 566                Assert.Equal("JJ", event10.AddMethod.GetReturnTypeAttributes().Single().AttributeClass.Name);
 567            };
 568
 569            CompileAndVerify(source, sourceSymbolValidator: symbolValidator(true), symbolValidator: symbolValidator(false));
 570        }
 571
 572        [Fact]
 573        public void TestAttributesOnEvents_NoDuplicateDiagnostics()
 574        {
 575            string source = @"
 576public class AA : System.Attribute { }
 577public class BB : System.Attribute { }
 578public class CC : System.Attribute { }
 579public class DD : System.Attribute { }
 580public class EE : System.Attribute { }
 581public class FF : System.Attribute { }
 582public class GG : System.Attribute { }
 583public class HH : System.Attribute { }
 584public class II : System.Attribute { }
 585public class JJ : System.Attribute { }
 586
 587public class Test
 588{
 589    [AA(0)] //in event decl
 590    public event System.Action E1;
 591    [event: BB(0)] //in event decl
 592    public event System.Action E2;
 593    [method: CC(0)] //in both accessors
 594    public event System.Action E3;
 595    [field: DD(0)] //on field
 596    public event System.Action E4;
 597
 598    [EE(0)] //in event decl
 599    public event System.Action E5 { add { } remove { } }
 600    [event: FF(0)] //in event decl
 601    public event System.Action E6 { add { } remove { } }
 602
 603    public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor
 604    public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor
 605    public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1])
 606    public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0])
 607}
 608";
 609            CreateCompilationWithMscorlib(source).VerifyDiagnostics(
 610                // (15,6): error CS1729: 'AA' does not contain a constructor that takes 1 arguments
 611                //     [AA(0)] //in event decl
 612                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"),
 613                // (17,13): error CS1729: 'BB' does not contain a constructor that takes 1 arguments
 614                //     [event: BB(0)] //in event decl
 615                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"),
 616                // (19,14): error CS1729: 'CC' does not contain a constructor that takes 1 arguments
 617                //     [method: CC(0)] //in both accessors
 618                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"),
 619                // (21,13): error CS1729: 'DD' does not contain a constructor that takes 1 arguments
 620                //     [field: DD(0)] //on field
 621                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"),
 622                // (24,6): error CS1729: 'EE' does not contain a constructor that takes 1 arguments
 623                //     [EE(0)] //in event decl
 624                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1"),
 625                // (26,13): error CS1729: 'FF' does not contain a constructor that takes 1 arguments
 626                //     [event: FF(0)] //in event decl
 627                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "FF(0)").WithArguments("FF", "1"),
 628                // (29,38): error CS1729: 'GG' does not contain a constructor that takes 1 arguments
 629                //     public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor
 630                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "GG(0)").WithArguments("GG", "1"),
 631                // (30,46): error CS1729: 'HH' does not contain a constructor that takes 1 arguments
 632                //     public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor
 633                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "HH(0)").WithArguments("HH", "1"),
 634                // (31,45): error CS1729: 'II' does not contain a constructor that takes 1 arguments
 635                //     public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1])
 636                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "II(0)").WithArguments("II", "1"),
 637                // (32,47): error CS1729: 'JJ' does not contain a constructor that takes 1 arguments
 638                //     public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0])
 639                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "JJ(0)").WithArguments("JJ", "1"),
 640                // (22,32): warning CS0067: The event 'Test.E4' is never used
 641                //     public event System.Action E4;
 642                Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("Test.E4"),
 643                // (18,32): warning CS0067: The event 'Test.E2' is never used
 644                //     public event System.Action E2;
 645                Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("Test.E2"),
 646                // (20,32): warning CS0067: The event 'Test.E3' is never used
 647                //     public event System.Action E3;
 648                Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("Test.E3"),
 649                // (16,32): warning CS0067: The event 'Test.E1' is never used
 650                //     public event System.Action E1;
 651                Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("Test.E1"));
 652        }
 653
 654        [Fact]
 655        public void TestAttributesOnIndexer_NoDuplicateDiagnostics()
 656        {
 657            string source = @"
 658public class AA : System.Attribute { }
 659public class BB : System.Attribute { }
 660public class CC : System.Attribute { }
 661public class DD : System.Attribute { }
 662public class EE : System.Attribute { }
 663
 664public class Test
 665{
 666    public int this[[AA(0)]int x]
 667    {
 668        [return: BB(0)]
 669        [CC(0)]
 670        get { return x; }
 671
 672        [param: DD(0)]
 673        [EE(0)]
 674        set { }
 675    }
 676}
 677";
 678            CreateCompilationWithMscorlib(source).VerifyDiagnostics(
 679                // (10,22): error CS1729: 'AA' does not contain a constructor that takes 1 arguments
 680                //     public int this[[AA(0)]int x]
 681                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"),
 682                // (13,10): error CS1729: 'CC' does not contain a constructor that takes 1 arguments
 683                //         [CC(0)]
 684                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"),
 685                // (12,18): error CS1729: 'BB' does not contain a constructor that takes 1 arguments
 686                //         [return: BB(0)]
 687                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"),
 688                // (16,17): error CS1729: 'DD' does not contain a constructor that takes 1 arguments
 689                //         [param: DD(0)]
 690                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"),
 691                // (17,10): error CS1729: 'EE' does not contain a constructor that takes 1 arguments
 692                //         [EE(0)]
 693                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1"));
 694        }
 695
 696        private static string GetSingleAttributeName(Symbol symbol)
 697        {
 698            return symbol.GetAttributes().Single().AttributeClass.Name;
 699        }
 700
 701        private static void AssertNoAttributes(Symbol symbol)
 702        {
 703            Assert.Equal(0, symbol.GetAttributes().Length);
 704        }
 705
 706        [Fact]
 707        public void TestAttributesOnDelegates()
 708        {
 709            string source = @"
 710using System;
 711
 712public class TypeAttribute : System.Attribute { }
 713public class ParamAttribute : System.Attribute { }
 714public class ReturnTypeAttribute : System.Attribute { }
 715public class TypeParamAttribute : System.Attribute { }
 716
 717class C
 718{
 719    [TypeAttribute]
 720    [return: ReturnTypeAttribute]
 721    public delegate T Delegate<[TypeParamAttribute]T> ([ParamAttribute]T p1, [param: ParamAttribute]ref T p2, [ParamAttribute]out T p3);
 722    
 723    public delegate int Delegate2 ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2);
 724
 725    static void Main()
 726    {
 727        typeof(Delegate<int>).GetCustomAttributes(false);
 728    }
 729}";
 730
 731            Action<ModuleSymbol> symbolValidator = moduleSymbol =>
 732            {
 733                var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
 734                var typeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeAttribute");
 735                var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute");
 736                var returnTypeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ReturnTypeAttribute");
 737                var typeParamAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeParamAttribute");
 738
 739                // Verify delegate type attribute
 740                var delegateType = type.GetTypeMember("Delegate");
 741                Assert.Equal(1, delegateType.GetAttributes(typeAttrType).Count());
 742
 743                // Verify type parameter attribute
 744                var typeParameters = delegateType.TypeParameters;
 745                Assert.Equal(1, typeParameters.Length);
 746                Assert.Equal(1, typeParameters[0].GetAttributes(typeParamAttrType).Count());
 747
 748                // Verify delegate methods (return type/parameters) attributes
 749
 750                // Invoke method
 751                // 1) Has return type attributes from delegate declaration syntax
 752                // 2) Has parameter attributes from delegate declaration syntax
 753                var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke");
 754                Assert.Equal(1, invokeMethod.GetReturnTypeAttributes().Where(a => a.AttributeClass == returnTypeAttrType).Count());
 755                Assert.Equal(typeParameters[0], invokeMethod.ReturnType);
 756                var parameters = invokeMethod.GetParameters();
 757                Assert.Equal(3, parameters.Length);
 758                Assert.Equal("p1", parameters[0].Name);
 759                Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count());
 760                Assert.Equal("p2", parameters[1].Name);
 761                Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count());
 762                Assert.Equal("p3", parameters[2].Name);
 763                Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count());
 764
 765                // Delegate Constructor:
 766                // 1) Doesn't have any return type attributes
 767                // 2) Doesn't have any parameter attributes
 768                var ctor = (MethodSymbol)delegateType.GetMember(".ctor");
 769                Assert.Equal(0, ctor.GetReturnTypeAttributes().Length);
 770                parameters = ctor.GetParameters();
 771                Assert.Equal(2, parameters.Length);
 772                Assert.Equal(0, parameters[0].GetAttributes().Length);
 773                Assert.Equal(0, parameters[1].GetAttributes().Length);
 774
 775                // BeginInvoke method:
 776                // 1) Doesn't have any return type attributes
 777                // 2) Has parameter attributes from delegate declaration parameters syntax
 778                var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke");
 779                Assert.Equal(0, beginInvokeMethod.GetReturnTypeAttributes().Length);
 780                parameters = beginInvokeMethod.GetParameters();
 781                Assert.Equal(5, parameters.Length);
 782                Assert.Equal("p1", parameters[0].Name);
 783                Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count());
 784                Assert.Equal("p2", parameters[1].Name);
 785                Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count());
 786                Assert.Equal("p3", parameters[2].Name);
 787                Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count());
 788                Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count());
 789                Assert.Equal(0, parameters[4].GetAttributes(paramAttrType).Count());
 790
 791                // EndInvoke method:
 792                // 1) Has return type attributes from delegate declaration syntax
 793                // 2) Has parameter attributes from delegate declaration syntax
 794                //    only for ref/out parameters.
 795                var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke");
 796                Assert.Equal(1, endInvokeMethod.GetReturnTypeAttributes().Where(a => a.AttributeClass == returnTypeAttrType).Count());
 797                parameters = endInvokeMethod.GetParameters();
 798                Assert.Equal(3, parameters.Length);
 799                Assert.Equal("p2", parameters[0].Name);
 800                Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count());
 801                Assert.Equal("p3", parameters[1].Name);
 802                Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count());
 803                Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count());
 804            };
 805
 806            CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator);
 807        }
 808
 809        [Fact]
 810        public void TestAttributesOnDelegates_NoDuplicateDiagnostics()
 811        {
 812            string source = @"
 813public class TypeAttribute : System.Attribute { }
 814public class ParamAttribute1 : System.Attribute { }
 815public class ParamAttribute2 : System.Attribute { }
 816public class ParamAttribute3 : System.Attribute { }
 817public class ParamAttribute4 : System.Attribute { }
 818public class ParamAttribute5 : System.Attribute { }
 819public class ReturnTypeAttribute : System.Attribute { }
 820public class TypeParamAttribute : System.Attribute { }
 821
 822class C
 823{
 824    [TypeAttribute(0)]
 825    [return: ReturnTypeAttribute(0)]
 826    public delegate T Delegate<[TypeParamAttribute(0)]T> ([ParamAttribute1(0)]T p1, [param: ParamAttribute2(0)]ref T p2, [ParamAttribute3(0)]out T p3);
 827
 828    public delegate int Delegate2 ([ParamAttribute4(0)]int p1 = 0, [param: ParamAttribute5(0)]params int[] p2);
 829}";
 830            CreateCompilationWithMscorlib(source).VerifyDiagnostics(
 831                // (13,6): error CS1729: 'TypeAttribute' does not contain a constructor that takes 1 arguments
 832                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeAttribute(0)").WithArguments("TypeAttribute", "1"),
 833                // (15,33): error CS1729: 'TypeParamAttribute' does not contain a constructor that takes 1 arguments
 834                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeParamAttribute(0)").WithArguments("TypeParamAttribute", "1"),
 835                // (15,60): error CS1729: 'ParamAttribute1' does not contain a constructor that takes 1 arguments
 836                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute1(0)").WithArguments("ParamAttribute1", "1"),
 837                // (15,93): error CS1729: 'ParamAttribute2' does not contain a constructor that takes 1 arguments
 838                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute2(0)").WithArguments("ParamAttribute2", "1"),
 839                // (15,123): error CS1729: 'ParamAttribute3' does not contain a constructor that takes 1 arguments
 840                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute3(0)").WithArguments("ParamAttribute3", "1"),
 841                // (14,14): error CS1729: 'ReturnTypeAttribute' does not contain a constructor that takes 1 arguments
 842                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ReturnTypeAttribute(0)").WithArguments("ReturnTypeAttribute", "1"),
 843                // (17,37): error CS1729: 'ParamAttribute4' does not contain a constructor that takes 1 arguments
 844                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute4(0)").WithArguments("ParamAttribute4", "1"),
 845                // (17,76): error CS1729: 'ParamAttribute5' does not contain a constructor that takes 1 arguments
 846                Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute5(0)").WithArguments("ParamAttribute5", "1"));
 847        }
 848
 849        [Fact]
 850        public void TestAttributesOnDelegateWithOptionalAndParams()
 851        {
 852            string source = @"
 853using System;
 854
 855public class ParamAttribute : System.Attribute { }
 856
 857class C
 858{
 859    public delegate int Delegate ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2);
 860
 861    static void Main()
 862    {
 863        typeof(Delegate).GetCustomAttributes(false);
 864    }
 865}";
 866
 867            Func<bool, Action<ModuleSymbol>> symbolValidator = isFromSource => moduleSymbol =>
 868            {
 869                var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
 870                var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute");
 871
 872                // Verify delegate type attribute
 873                var delegateType = type.GetTypeMember("Delegate");
 874
 875                // Verify delegate methods (return type/parameters) attributes
 876
 877                // Invoke method has parameter attributes from delegate declaration syntax
 878                var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke");
 879                var parameters = invokeMethod.GetParameters();
 880                Assert.Equal(2, parameters.Length);
 881                Assert.Equal("p1", parameters[0].Name);
 882                Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count());
 883                Assert.Equal("p2", parameters[1].Name);
 884                Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count());
 885
 886                // verify ParamArrayAttribute on p2
 887                if (isFromSource)
 888                {
 889                    WellKnownAttributesTestBase.VerifyParamArrayAttribute(parameters[1], (SourceModuleSymbol)moduleSymbol);
 890                }
 891
 892                // Delegate Constructor: Doesn't have any parameter attributes
 893                var ctor = (MethodSymbol)delegateType.GetMember(".ctor");
 894                parameters = ctor.GetParameters();
 895                Assert.Equal(2, parameters.Length);
 896                Assert.Equal(0, parameters[0].GetAttributes().Length);
 897                Assert.Equal(0, parameters[1].GetAttributes().Length);
 898                Assert.Equal(0, parameters[0].GetSynthesizedAttributes().Length);
 899                Assert.Equal(0, parameters[1].GetSynthesizedAttributes().Length);
 900
 901                // BeginInvoke method: Has parameter attributes from delegate declaration parameters syntax
 902                var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke");
 903                parameters = beginInvokeMethod.GetParameters();
 904                Assert.Equal(4, parameters.Length);
 905                Assert.Equal("p1", parameters[0].Name);
 906                Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count());
 907                Assert.Equal("p2", parameters[1].Name);
 908                Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count());
 909                Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count());
 910                Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count());
 911
 912                // verify no ParamArrayAttribute on p2
 913                if (isFromSource)
 914                {
 915                    WellKnownAttributesTestBase.VerifyParamArrayAttribute(parameters[1], (SourceModuleSymbol)moduleSymbol, expected: false);
 916                }
 917            };
 918
 919            CompileAndVerify(source, sourceSymbolValidator: symbolValidator(true), symbolValidator: symbolValidator(false));
 920        }
 921
 922        [Fact]
 923        public void TestAttributesOnEnumField()
 924        {
 925            string source = @"
 926using System;
 927using System.Collections.Generic;
 928using System.Reflection;
 929using CustomAttribute;
 930using AN = CustomAttribute.AttrName;
 931
 932// Use AttrName without Attribute suffix
 933[assembly: AN(UShortField = 4321)]
 934[assembly: AN(UShortField = 1234)]
 935
 936// TODO: below attribute seems to be an ambiguous attribute specification
 937// TODO: modify the test assembly to remove ambiguity
 938// [module: AttrName(TypeField = typeof(System.IO.FileStream))]
 939namespace AttributeTest
 940{
 941    class Foo
 942    {
 943        public class NestedClass
 944        {
 945            // enum as object
 946            [AllInheritMultiple(System.IO.FileMode.Open, BindingFlags.DeclaredOnly | BindingFlags.Public, UIntField = 123 * Field)]
 947            internal const uint Field = 10;
 948        }
 949        [AllInheritMultiple(new char[] { 'q', 'c' }, """")]
 950        [AllInheritMultiple()]
 951        enum NestedEnum
 952        {
 953            zero,
 954            one = 1,
 955            [AllInheritMultiple(null, 256, 0f, -1, AryField = new ulong[] { 0, 1, 12345657 })]
 956            [AllInheritMultipleAttribute(typeof(Dictionary<string, int>), 255 + NestedClass.Field, -0.0001f, 3 - (short)NestedEnum.oneagain)]
 957            three = 3,
 958            oneagain = one
 959        }
 960    }
 961}
 962";
 963
 964            var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
 965            CSharpCompilationOptions opt = TestOptions.Dll;
 966
 967            var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
 968
 969            Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
 970            {
 971                var attrs = m.GetAttributes();
 972                // Assert.Equal(1, attrs.Count);
 973                // Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString());
 974                // attrs[0].VerifyValue<Type>(0, "TypeField", TypedConstantKind.Type, typeof(System.IO.FileStream));
 975
 976                var assembly = m.ContainingSymbol;
 977                attrs = assembly.GetAttributes();
 978                Assert.Equal(2, attrs.Length);
 979                Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString());
 980                attrs[1].VerifyNamedArgumentValue<ushort>(0, "UShortField", TypedConstantKind.Primitive, 1234);
 981
 982                var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
 983                var top = (NamedTypeSymbol)ns.GetMember("Foo");
 984                var type = top.GetMember<NamedTypeSymbol>("NestedClass");
 985
 986                var field = type.GetMember<FieldSymbol>("Field");
 987                attrs = field.GetAttributes();
 988                Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attrs[0].AttributeClass.ToDisplayString());
 989                attrs[0].VerifyValue(0, TypedConstantKind.Enum, (int)FileMode.Open);
 990                attrs[0].VerifyValue(1, TypedConstantKind.Enum, (int)(BindingFlags.DeclaredOnly | BindingFlags.Public));
 991                attrs[0].VerifyNamedArgumentValue<uint>(0, "UIntField", TypedConstantKind.Primitive, 1230);
 992
 993                var nenum = top.GetMember<TypeSymbol>("NestedEnum");
 994                attrs = nenum.GetAttributes();
 995                Assert.Equal(2, attrs.Length);
 996                attrs[0].VerifyValue(0, TypedConstantKind.Array, new char[] { 'q', 'c' });
 997                Assert.Equal(SyntaxKind.Attribute, attrs[0].ApplicationSyntaxReference.GetSyntax().CSharpKind());
 998                var syntax = (AttributeSyntax)attrs[0].ApplicationSyntaxReference.GetSyntax();
 999                Assert.Equal(2, syntax.ArgumentList.Arguments.Count());
1000                syntax = (AttributeSyntax)attrs[1].ApplicationSyntaxReference.GetSyntax();
1001                Assert.Equal(0, syntax.ArgumentList.Arguments.Count());
1002
1003                attrs = nenum.GetMember("three").GetAttributes();
1004                Assert.Equal(2, attrs.Length);
1005                attrs[0].VerifyValue<object>(0, TypedConstantKind.Primitive, null);
1006                attrs[0].VerifyValue<long>(1, TypedConstantKind.Primitive, 256);
1007                attrs[0].VerifyValue<float>(2, TypedConstantKind.Primitive, 0);
1008                attrs[0].VerifyValue<short>(3, TypedConstantKind.Primitive, -1);
1009                attrs[0].VerifyNamedArgumentValue<ulong[]>(0, "AryField", TypedConstantKind.Array, new ulong[] { 0, 1, 12345657 });
1010
1011                attrs[1].VerifyValue<object>(0, TypedConstantKind.Type, typeof(Dictionary<string, int>));
1012                attrs[1].VerifyValue<long>(1, TypedConstantKind.Primitive, 265);
1013                attrs[1].VerifyValue<float>(2, TypedConstantKind.Primitive, -0.0001f);
1014                attrs[1].VerifyValue<short>(3, TypedConstantKind.Primitive, 2);
1015            };
1016
1017            // Verify attributes from source and then load metadata to see attributes are written correctly.
1018            CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
1019        }
1020
1021        [Fact]
1022        public void TestAttributesOnDelegate()
1023        {
1024            string source = @"
1025using System;
1026using System.Collections.Generic;
1027using CustomAttribute;
1028
1029namespace AttributeTest
1030{
1031    public class Foo
1032    {
1033        [AllInheritMultiple(new object[] { 0, """", null }, 255, -127 - 1, AryProp = new object[] { new object[] { """", typeof(IList<string>) } })]
1034        public delegate void NestedSubDele([AllInheritMultiple()]string p1, [Derived(typeof(string[, ,]))]string p2);
1035    }
1036}
1037";
1038
1039            var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
1040            CSharpCompilationOptions opt = TestOptions.Dll;
1041
1042            var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
1043
1044            Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
1045            {
1046                var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
1047                var type = (NamedTypeSymbol)ns.GetMember("Foo");
1048
1049                var dele = (NamedTypeSymbol)type.GetTypeMember("NestedSubDele");
1050                var attrs = dele.GetAttributes();
1051                attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 0, "", null });
1052                attrs.First().VerifyValue<byte>(1, TypedConstantKind.Primitive, 255);
1053                attrs.First().VerifyValue<sbyte>(2, TypedConstantKind.Primitive, -128);
1054                attrs.First().VerifyNamedArgumentValue<object[]>(0, "AryProp", TypedConstantKind.Array, new object[] { new object[] { "", typeof(IList<string>) } });
1055                var mem = dele.GetMember<MethodSymbol>("Invoke");
1056                attrs = mem.Parameters[0].GetAttributes();
1057                Assert.Equal(1, attrs.Length);
1058                attrs = mem.Parameters[1].GetAttributes();
1059                Assert.Equal(1, attrs.Length);
1060                attrs[0].VerifyValue<object>(0, TypedConstantKind.Type, typeof(string[,,]));
1061            };
1062
1063            // Verify attributes from source and then load metadata to see attributes are written correctly.
1064            CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator);
1065        }
1066
1067        [Fact]
1068        public void TestAttributesUseBaseAttributeField()
1069        {
1070            string source = @"
1071using System;
1072namespace AttributeTest
1073{
1074    public interface IFoo
1075    {
1076        [CustomAttribute.Derived(new object[] { 1, null, ""Hi"" }, ObjectField = 2)]
1077        int F(int p);
1078    }
1079}
1080";
1081            var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
1082            CSharpCompilationOptions opt = TestOptions.Dll;
1083
1084            var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
1085
1086            Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
1087            {
1088                var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
1089                var type = (NamedTypeSymbol)ns.GetMember("IFoo");
1090                var attrs = type.GetMember<MethodSymbol>("F").GetAttributes();
1091
1092                Assert.Equal(@"CustomAttribute.DerivedAttribute({1, null, ""Hi""}, ObjectField = 2)", attrs.First().ToString());
1093                attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 1, null, "Hi" });
1094                attrs.First().VerifyNamedArgumentValue<object>(0, "ObjectField", TypedConstantKind.Primitive, 2);
1095            };
1096
1097            // Verify attributes from source and then load metadata to see attributes are written correctly.
1098            CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
1099        }
1100
1101        [WorkItem(688007, "DevDiv")]
1102        [Fact]
1103        public void Bug688007a()
1104        {
1105            string source = @"
1106using System;
1107using X;
1108using Z;
1109
1110namespace X
1111{
1112    public class At

Large files files are truncated, but you can click here to view the full file