PageRenderTime 30ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 2ms

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

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