PageRenderTime 83ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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 AttrAttribute : Attribute
  982. {
  983. }
  984. }
  985. namespace Z
  986. {
  987. public class Attr
  988. {
  989. }
  990. }
  991. [Attr()]
  992. partial class CDoc
  993. {
  994. static void Main(string[] args)
  995. {
  996. }
  997. }
  998. ";
  999. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Dll);
  1000. var globalNs = compilation.GlobalNamespace;
  1001. var cDoc = globalNs.GetTypeMember("CDoc");
  1002. Assert.NotNull(cDoc);
  1003. var attrs = cDoc.GetAttributes();
  1004. Assert.Equal(1, attrs.Length);
  1005. Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString());
  1006. CompileAndVerify(compilation).VerifyDiagnostics();
  1007. }
  1008. [WorkItem(688007, "DevDiv")]
  1009. [Fact]
  1010. public void Bug688007b()
  1011. {
  1012. string source = @"
  1013. using System;
  1014. using X;
  1015. using Z;
  1016. namespace X
  1017. {
  1018. public class AttrAttribute : Attribute
  1019. {
  1020. }
  1021. public class Attr : Attribute
  1022. {
  1023. }
  1024. }
  1025. namespace Z
  1026. {
  1027. public class Attr : Attribute
  1028. {
  1029. }
  1030. }
  1031. [Attr()]
  1032. partial class CDoc
  1033. {
  1034. static void Main(string[] args)
  1035. {
  1036. }
  1037. }
  1038. ";
  1039. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Dll);
  1040. var globalNs = compilation.GlobalNamespace;
  1041. var cDoc = globalNs.GetTypeMember("CDoc");
  1042. Assert.NotNull(cDoc);
  1043. var attrs = cDoc.GetAttributes();
  1044. Assert.Equal(1, attrs.Length);
  1045. Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString());
  1046. CompileAndVerify(compilation).VerifyDiagnostics();
  1047. }
  1048. [WorkItem(688007, "DevDiv")]
  1049. [Fact]
  1050. public void Bug688007c()
  1051. {
  1052. string source = @"
  1053. using System;
  1054. using X;
  1055. using Y;
  1056. using Z;
  1057. namespace X
  1058. {
  1059. public class AttrAttribute /*: Attribute*/
  1060. {
  1061. }
  1062. }
  1063. namespace Y
  1064. {
  1065. public class AttrAttribute /*: Attribute*/
  1066. {
  1067. }
  1068. }
  1069. namespace Z
  1070. {
  1071. public class Attr : Attribute
  1072. {
  1073. }
  1074. }
  1075. [Attr()]
  1076. partial class CDoc
  1077. {
  1078. static void Main(string[] args)
  1079. {
  1080. }
  1081. }
  1082. ";
  1083. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Dll);
  1084. var globalNs = compilation.GlobalNamespace;
  1085. var cDoc = globalNs.GetTypeMember("CDoc");
  1086. Assert.NotNull(cDoc);
  1087. var attrs = cDoc.GetAttributes();
  1088. Assert.Equal(1, attrs.Length);
  1089. Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString());
  1090. CompileAndVerify(compilation).VerifyDiagnostics();
  1091. }
  1092. [WorkItem(688007, "DevDiv")]
  1093. [Fact]
  1094. public void Bug688007d()
  1095. {
  1096. string source = @"
  1097. using System;
  1098. using X;
  1099. using Y;
  1100. using Z;
  1101. namespace X
  1102. {
  1103. public class AttrAttribute : Attribute
  1104. {
  1105. }
  1106. }
  1107. namespace Y
  1108. {
  1109. public class AttrAttribute : Attribute
  1110. {
  1111. }
  1112. }
  1113. namespace Z
  1114. {
  1115. public class Attr : Attribute
  1116. {
  1117. }
  1118. }
  1119. [Attr()]
  1120. partial class CDoc
  1121. {
  1122. static void Main(string[] args)
  1123. {
  1124. }
  1125. }
  1126. ";
  1127. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Dll);
  1128. var globalNs = compilation.GlobalNamespace;
  1129. var cDoc = globalNs.GetTypeMember("CDoc");
  1130. Assert.NotNull(cDoc);
  1131. var attrs = cDoc.GetAttributes();
  1132. Assert.Equal(1, attrs.Length);
  1133. Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString());
  1134. var syntax = attrs.Single().ApplicationSyntaxReference.GetSyntax();
  1135. Assert.NotNull(syntax);
  1136. Assert.IsType<AttributeSyntax>(syntax);
  1137. CompileAndVerify(compilation).VerifyDiagnostics();
  1138. }
  1139. [Fact]
  1140. public void TestAttributesWithParamArrayInCtor01()
  1141. {
  1142. string source = @"
  1143. using System;
  1144. using CustomAttribute;
  1145. namespace AttributeTest
  1146. {
  1147. [AllInheritMultiple(new char[] { ' '}, """")]
  1148. public interface IFoo
  1149. {
  1150. }
  1151. }
  1152. ";
  1153. var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
  1154. CSharpCompilationOptions opt = TestOptions.Dll;
  1155. var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
  1156. Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) =>
  1157. {
  1158. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1159. var type = (NamedTypeSymbol)ns.GetMember("IFoo");
  1160. var attrs = type.GetAttributes();
  1161. attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' });
  1162. attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" });
  1163. Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams);
  1164. };
  1165. Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) =>
  1166. {
  1167. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1168. var type = (NamedTypeSymbol)ns.GetMember("IFoo");
  1169. var attrs = type.GetAttributes();
  1170. attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' });
  1171. attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" });
  1172. };
  1173. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1174. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator);
  1175. }
  1176. [Fact]
  1177. public void TestAttributesWithParamArrayInCtor02()
  1178. {
  1179. string source = @"
  1180. using System;
  1181. namespace AttributeTest
  1182. {
  1183. class ExampleAttribute : Attribute
  1184. {
  1185. public int[] Numbers;
  1186. public ExampleAttribute(string message, params int[] numbers)
  1187. {
  1188. Numbers = numbers;
  1189. }
  1190. }
  1191. class Program
  1192. {
  1193. [Example(""MultipleArgumentsToParamsParameter"", 4, 5, 6)]
  1194. public void MultipleArgumentsToParamsParameter() { }
  1195. [Example(""NoArgumentsToParamsParameter"")]
  1196. public void NoArgumentsToParamsParameter() { }
  1197. [Example(""NullArgumentToParamsParameter"", null)]
  1198. public void NullArgumentToParamsParameter() { }
  1199. static void Main()
  1200. {
  1201. ExampleAttribute att = null;
  1202. try
  1203. {
  1204. var programType = typeof(Program);
  1205. var method = programType.GetMember(""MultipleArgumentsToParamsParameter"")[0];
  1206. att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0];
  1207. method = programType.GetMember(""NoArgumentsToParamsParameter"")[0];
  1208. att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0];
  1209. method = programType.GetMember(""NullArgumentToParamsParameter"")[0];
  1210. att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0];
  1211. }
  1212. catch (Exception e)
  1213. {
  1214. Console.WriteLine(e.Message);
  1215. return;
  1216. }
  1217. Console.WriteLine(true);
  1218. }
  1219. }
  1220. }
  1221. ";
  1222. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1223. {
  1224. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1225. var type = (NamedTypeSymbol)ns.GetMember("Program");
  1226. var attributeClass = (NamedTypeSymbol)ns.GetMember("ExampleAttribute");
  1227. var method = (MethodSymbol)type.GetMember("MultipleArgumentsToParamsParameter");
  1228. var attrs = method.GetAttributes(attributeClass);
  1229. var attr = attrs.Single();
  1230. Assert.Equal(2, attr.CommonConstructorArguments.Length);
  1231. attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "MultipleArgumentsToParamsParameter");
  1232. attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { 4, 5, 6 });
  1233. method = (MethodSymbol)type.GetMember("NoArgumentsToParamsParameter");
  1234. attrs = method.GetAttributes(attributeClass);
  1235. attr = attrs.Single();
  1236. Assert.Equal(2, attr.CommonConstructorArguments.Length);
  1237. attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NoArgumentsToParamsParameter");
  1238. attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { });
  1239. method = (MethodSymbol)type.GetMember("NullArgumentToParamsParameter");
  1240. attrs = method.GetAttributes(attributeClass);
  1241. attr = attrs.Single();
  1242. Assert.Equal(2, attr.CommonConstructorArguments.Length);
  1243. attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NullArgumentToParamsParameter");
  1244. attr.VerifyValue<int[]>(1, TypedConstantKind.Array, null);
  1245. };
  1246. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1247. var compVerifier = CompileAndVerify(
  1248. source,
  1249. emitOptions: EmitOptions.CCI,
  1250. sourceSymbolValidator: attributeValidator,
  1251. symbolValidator: attributeValidator,
  1252. expectedOutput: "True\r\n",
  1253. expectedSignatures: new[]
  1254. {
  1255. Signature("AttributeTest.Program", "MultipleArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"MultipleArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void MultipleArgumentsToParamsParameter() cil managed"),
  1256. Signature("AttributeTest.Program", "NoArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NoArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void NoArgumentsToParamsParameter() cil managed"),
  1257. Signature("AttributeTest.Program", "NullArgumentToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NullArgumentToParamsParameter\", )] public hidebysig instance System.Void NullArgumentToParamsParameter() cil managed"),
  1258. });
  1259. }
  1260. [Fact, WorkItem(531385, "DevDiv")]
  1261. public void TestAttributesWithParamArrayInCtor3()
  1262. {
  1263. string source = @"
  1264. using System;
  1265. using CustomAttribute;
  1266. namespace AttributeTest
  1267. {
  1268. [AllInheritMultiple(new char[] { ' ' }, new string[] { ""whatever"" })]
  1269. public interface IFoo
  1270. {
  1271. }
  1272. }
  1273. ";
  1274. var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
  1275. CSharpCompilationOptions opt = TestOptions.Dll;
  1276. var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
  1277. Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) =>
  1278. {
  1279. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1280. var type = (NamedTypeSymbol)ns.GetMember("IFoo");
  1281. var attrs = type.GetAttributes();
  1282. attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' });
  1283. attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" });
  1284. Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams);
  1285. };
  1286. Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) =>
  1287. {
  1288. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1289. var type = (NamedTypeSymbol)ns.GetMember("IFoo");
  1290. var attrs = type.GetAttributes();
  1291. attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' });
  1292. attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" });
  1293. };
  1294. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1295. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator);
  1296. }
  1297. [Fact]
  1298. public void TestAttributeSpecifiedOnItself()
  1299. {
  1300. string source = @"
  1301. using System;
  1302. namespace AttributeTest
  1303. {
  1304. [MyAttribute(typeof(object))]
  1305. public class MyAttribute : Attribute
  1306. {
  1307. public MyAttribute(Type t)
  1308. {
  1309. }
  1310. public static void Main()
  1311. {
  1312. }
  1313. }
  1314. }
  1315. ";
  1316. var compilation = CreateCompilationWithMscorlib(source);
  1317. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1318. {
  1319. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1320. var type = (NamedTypeSymbol)ns.GetMember("MyAttribute");
  1321. var attrs = type.GetAttributes();
  1322. Assert.Equal(1, attrs.Length);
  1323. attrs.First().VerifyValue(0, TypedConstantKind.Type, typeof(Object));
  1324. };
  1325. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1326. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator);
  1327. }
  1328. [Fact]
  1329. public void TestAttributesWithEnumArrayInCtor()
  1330. {
  1331. string source = @"
  1332. using System;
  1333. namespace AttributeTest
  1334. {
  1335. public enum X
  1336. {
  1337. a,
  1338. b
  1339. };
  1340. public class Y : Attribute
  1341. {
  1342. public int f;
  1343. public Y(X[] x) { }
  1344. }
  1345. [Y(A.x)]
  1346. public class A
  1347. {
  1348. public const X[] x = null;
  1349. public static void Main() { }
  1350. }
  1351. }
  1352. ";
  1353. var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
  1354. CSharpCompilationOptions opt = TestOptions.Dll;
  1355. var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
  1356. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1357. {
  1358. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1359. var type = (NamedTypeSymbol)ns.GetMember("A");
  1360. var attrs = type.GetAttributes();
  1361. attrs.First().VerifyValue(0, TypedConstantKind.Array, (object[])null);
  1362. };
  1363. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1364. CompileAndVerify(compilation, emitOptions: EmitOptions.RefEmitUnsupported_640494, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  1365. }
  1366. [WorkItem(541058, "DevDiv")]
  1367. [Fact]
  1368. public void TestAttributesWithtypeof()
  1369. {
  1370. string source = @"
  1371. using System;
  1372. [MyAttribute(typeof(object))]
  1373. public class MyAttribute : Attribute
  1374. {
  1375. public MyAttribute(Type t)
  1376. {
  1377. }
  1378. public static void Main()
  1379. {
  1380. }
  1381. }
  1382. ";
  1383. CompileAndVerify(source);
  1384. }
  1385. [WorkItem(541071, "DevDiv")]
  1386. [Fact]
  1387. public void TestAttributesWithParams()
  1388. {
  1389. string source = @"
  1390. using System;
  1391. class ExampleAttribute : Attribute
  1392. {
  1393. public int[] Numbers;
  1394. public ExampleAttribute(string message, params int[] numbers)
  1395. {
  1396. Numbers = numbers;
  1397. }
  1398. }
  1399. [Example(""wibble"", 4, 5, 6)]
  1400. class Program
  1401. {
  1402. static void Main()
  1403. {
  1404. ExampleAttribute att = null;
  1405. try
  1406. {
  1407. att = (ExampleAttribute)typeof(Program).GetCustomAttributes(typeof(ExampleAttribute), false)[0];
  1408. }
  1409. catch (Exception e)
  1410. {
  1411. Console.WriteLine(e.Message);
  1412. return;
  1413. }
  1414. Console.WriteLine(true);
  1415. }
  1416. }
  1417. ";
  1418. var expectedOutput = @"True";
  1419. CompileAndVerify(source, expectedOutput: expectedOutput);
  1420. }
  1421. [Fact]
  1422. public void TestAttributesOnReturnType()
  1423. {
  1424. string source = @"
  1425. using System;
  1426. using CustomAttribute;
  1427. namespace AttributeTest
  1428. {
  1429. public class Foo
  1430. {
  1431. int p;
  1432. public int Property
  1433. {
  1434. [return: AllInheritMultipleAttribute()]
  1435. [AllInheritMultipleAttribute()]
  1436. get { return p; }
  1437. [return: AllInheritMultipleAttribute()]
  1438. [AllInheritMultipleAttribute()]
  1439. set { p = value; }
  1440. }
  1441. [return: AllInheritMultipleAttribute()]
  1442. [return: AllInheritMultipleAttribute()]
  1443. public int Method() { return p; }
  1444. [return: AllInheritMultipleAttribute()]
  1445. public delegate void Delegate();
  1446. public static void Main() {}
  1447. }
  1448. }
  1449. ";
  1450. var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
  1451. CSharpCompilationOptions opt = TestOptions.Dll;
  1452. var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
  1453. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1454. {
  1455. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1456. var type = (NamedTypeSymbol)ns.GetMember("Foo");
  1457. var property = (PropertySymbol)type.GetMember("Property");
  1458. var getter = property.GetMethod;
  1459. var attrs = getter.GetReturnTypeAttributes();
  1460. Assert.Equal(1, attrs.Length);
  1461. var attr = attrs.First();
  1462. Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString());
  1463. var setter = property.SetMethod;
  1464. attrs = setter.GetReturnTypeAttributes();
  1465. Assert.Equal(1, attrs.Length);
  1466. attr = attrs.First();
  1467. Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString());
  1468. var method = (MethodSymbol)type.GetMember("Method");
  1469. attrs = method.GetReturnTypeAttributes();
  1470. Assert.Equal(2, attrs.Length);
  1471. attr = attrs.First();
  1472. Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString());
  1473. attr = attrs.Last();
  1474. Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString());
  1475. var delegateType = type.GetTypeMember("Delegate");
  1476. var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke");
  1477. attrs = invokeMethod.GetReturnTypeAttributes();
  1478. Assert.Equal(1, attrs.Length);
  1479. attr = attrs.First();
  1480. Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString());
  1481. var ctor = (MethodSymbol)delegateType.GetMember(".ctor");
  1482. attrs = ctor.GetReturnTypeAttributes();
  1483. Assert.Equal(0, attrs.Length);
  1484. var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke");
  1485. attrs = beginInvokeMethod.GetReturnTypeAttributes();
  1486. Assert.Equal(0, attrs.Length);
  1487. var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke");
  1488. attrs = endInvokeMethod.GetReturnTypeAttributes();
  1489. Assert.Equal(1, attrs.Length);
  1490. attr = attrs.First();
  1491. Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString());
  1492. };
  1493. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1494. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  1495. }
  1496. [WorkItem(541397, "DevDiv")]
  1497. [Fact]
  1498. public void TestAttributeWithSameNameAsTypeParameter()
  1499. {
  1500. string source = @"
  1501. using System;
  1502. namespace AttributeTest
  1503. {
  1504. public class TAttribute : Attribute { }
  1505. public class RAttribute : TAttribute { }
  1506. public class GClass<T>
  1507. {
  1508. [T]
  1509. public enum E { }
  1510. [R]
  1511. internal R M<R>() { return default(R); }
  1512. }
  1513. }
  1514. ";
  1515. var compilation = CreateCompilationWithMscorlib(source);
  1516. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1517. {
  1518. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1519. var type = (NamedTypeSymbol)ns.GetMember("GClass");
  1520. var enumType = (NamedTypeSymbol)type.GetTypeMember("E");
  1521. var attributeType = (NamedTypeSymbol)ns.GetMember("TAttribute");
  1522. var attributeType2 = (NamedTypeSymbol)ns.GetMember("RAttribute");
  1523. var genMethod = (MethodSymbol)type.GetMember("M");
  1524. var attrs = enumType.GetAttributes(attributeType);
  1525. Assert.Equal(1, attrs.Count());
  1526. attrs = genMethod.GetAttributes(attributeType2);
  1527. Assert.Equal(1, attrs.Count());
  1528. };
  1529. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1530. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  1531. }
  1532. [WorkItem(541615, "DevDiv")]
  1533. [Fact]
  1534. public void TestAttributeWithVarIdentifierName()
  1535. {
  1536. string source = @"
  1537. using System;
  1538. namespace AttributeTest
  1539. {
  1540. public class var: Attribute { }
  1541. [var]
  1542. class Program
  1543. {
  1544. public static void Main() {}
  1545. }
  1546. }
  1547. ";
  1548. var compilation = CreateCompilationWithMscorlib(source);
  1549. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1550. {
  1551. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1552. var type = (NamedTypeSymbol)ns.GetMember("Program");
  1553. var attributeType = (NamedTypeSymbol)ns.GetMember("var");
  1554. var attrs = type.GetAttributes(attributeType);
  1555. Assert.Equal(1, attrs.Count());
  1556. var attr = attrs.First();
  1557. Assert.Equal("AttributeTest.var", attr.ToString());
  1558. };
  1559. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1560. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  1561. }
  1562. [WorkItem(541505, "DevDiv")]
  1563. [Fact]
  1564. public void AttributeArgumentBind_PropertyWithSameName()
  1565. {
  1566. var source =
  1567. @"using System;
  1568. namespace AttributeTest
  1569. {
  1570. class TestAttribute : Attribute
  1571. {
  1572. public TestAttribute(ProtectionLevel p){}
  1573. }
  1574. enum ProtectionLevel
  1575. {
  1576. Privacy = 0
  1577. }
  1578. class TestClass
  1579. {
  1580. ProtectionLevel ProtectionLevel { get { return ProtectionLevel.Privacy; } }
  1581. [TestAttribute(ProtectionLevel.Privacy)]
  1582. public int testField;
  1583. }
  1584. }
  1585. ";
  1586. var compilation = CreateCompilationWithMscorlib(source);
  1587. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1588. {
  1589. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1590. var type = (NamedTypeSymbol)ns.GetMember("TestClass");
  1591. var attributeType = (NamedTypeSymbol)ns.GetMember("TestAttribute");
  1592. var field = (FieldSymbol)type.GetMember("testField");
  1593. var attrs = field.GetAttributes(attributeType);
  1594. Assert.Equal(1, attrs.Count());
  1595. };
  1596. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1597. CompileAndVerify(compilation, emitOptions: EmitOptions.RefEmitUnsupported_640494, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  1598. }
  1599. [WorkItem(541709, "DevDiv")]
  1600. [Fact]
  1601. public void AttributeOnSynthesizedParameterSymbol()
  1602. {
  1603. var source =
  1604. @"using System;
  1605. namespace AttributeTest
  1606. {
  1607. public class TestAttributeForMethod : System.Attribute { }
  1608. public class TestAttributeForParam : System.Attribute { }
  1609. public class TestAttributeForReturn : System.Attribute { }
  1610. class TestClass
  1611. {
  1612. int P1
  1613. {
  1614. [TestAttributeForMethod]
  1615. [param: TestAttributeForParam]
  1616. [return: TestAttributeForReturn]
  1617. set { }
  1618. }
  1619. int P2
  1620. {
  1621. [TestAttributeForMethod]
  1622. [return: TestAttributeForReturn]
  1623. get { return 0; }
  1624. }
  1625. public static void Main() {}
  1626. }
  1627. }
  1628. ";
  1629. var compilation = CreateCompilationWithMscorlib(source);
  1630. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1631. {
  1632. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1633. var type = (NamedTypeSymbol)ns.GetMember("TestClass");
  1634. var attributeTypeForMethod = (NamedTypeSymbol)ns.GetMember("TestAttributeForMethod");
  1635. var attributeTypeForParam = (NamedTypeSymbol)ns.GetMember("TestAttributeForParam");
  1636. var attributeTypeForReturn = (NamedTypeSymbol)ns.GetMember("TestAttributeForReturn");
  1637. var property = (PropertySymbol)type.GetMember("P1");
  1638. var setter = property.SetMethod;
  1639. var attrs = setter.GetAttributes(attributeTypeForMethod);
  1640. Assert.Equal(1, attrs.Count());
  1641. var attr = attrs.First();
  1642. Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString());
  1643. Assert.Equal(1, setter.ParameterCount);
  1644. attrs = setter.Parameters[0].GetAttributes(attributeTypeForParam);
  1645. Assert.Equal(1, attrs.Count());
  1646. attr = attrs.First();
  1647. Assert.Equal("AttributeTest.TestAttributeForParam", attr.AttributeClass.ToDisplayString());
  1648. attrs = setter.GetReturnTypeAttributes().Where(a => a.AttributeClass == attributeTypeForReturn);
  1649. Assert.Equal(1, attrs.Count());
  1650. attr = attrs.First();
  1651. Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString());
  1652. property = (PropertySymbol)type.GetMember("P2");
  1653. var getter = property.GetMethod;
  1654. attrs = getter.GetAttributes(attributeTypeForMethod);
  1655. Assert.Equal(1, attrs.Count());
  1656. attr = attrs.First();
  1657. Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString());
  1658. attrs = getter.GetReturnTypeAttributes().Where(a => a.AttributeClass == attributeTypeForReturn);
  1659. Assert.Equal(1, attrs.Count());
  1660. attr = attrs.First();
  1661. Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString());
  1662. };
  1663. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1664. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  1665. }
  1666. [Fact]
  1667. public void TestAttributeStringForEnumTypedConstant()
  1668. {
  1669. var source = CreateCompilationWithMscorlib(@"
  1670. using System;
  1671. namespace AttributeTest
  1672. {
  1673. enum X
  1674. {
  1675. One = 1,
  1676. Two = 2,
  1677. Three = 3
  1678. };
  1679. [AttributeUsage(AttributeTargets.Field | AttributeTargets.Event, Inherited = false, AllowMultiple = true)]
  1680. class A : System.Attribute
  1681. {
  1682. public A(X x) { }
  1683. public static void Main() { }
  1684. // AttributeData.ToString() should display 'X.Three' not 'X.One | X.Two'
  1685. [A(X.Three)]
  1686. int field;
  1687. // AttributeData.ToString() should display '5'
  1688. [A((X)5)]
  1689. int field2;
  1690. }
  1691. }
  1692. ");
  1693. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1694. {
  1695. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1696. var type = (NamedTypeSymbol)ns.GetMember("A");
  1697. var attrs = type.GetAttributes();
  1698. Assert.Equal(1, attrs.Length);
  1699. var attr = attrs.First();
  1700. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  1701. attr.VerifyValue(0, TypedConstantKind.Enum, (int)(AttributeTargets.Field | AttributeTargets.Event));
  1702. Assert.Equal(2, attr.CommonNamedArguments.Length);
  1703. attr.VerifyNamedArgumentValue(0, "Inherited", TypedConstantKind.Primitive, false);
  1704. attr.VerifyNamedArgumentValue(1, "AllowMultiple", TypedConstantKind.Primitive, true);
  1705. Assert.Equal(@"System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Event, Inherited = false, AllowMultiple = true)", attr.ToString());
  1706. var fieldSymbol = (FieldSymbol)type.GetMember("field");
  1707. attrs = fieldSymbol.GetAttributes();
  1708. Assert.Equal(1, attrs.Length);
  1709. Assert.Equal(@"AttributeTest.A(AttributeTest.X.Three)", attrs.First().ToString());
  1710. fieldSymbol = (FieldSymbol)type.GetMember("field2");
  1711. attrs = fieldSymbol.GetAttributes();
  1712. Assert.Equal(1, attrs.Length);
  1713. Assert.Equal(@"AttributeTest.A(5)", attrs.First().ToString());
  1714. };
  1715. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1716. CompileAndVerify(source, emitOptions: EmitOptions.RefEmitUnsupported_640494, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  1717. }
  1718. [Fact]
  1719. public void TestAttributesWithNamedConstructorArguments_01()
  1720. {
  1721. string source = @"
  1722. using System;
  1723. namespace AttributeTest
  1724. {
  1725. [A(y:4, z:5, X = 6)]
  1726. public class A : Attribute
  1727. {
  1728. public int X;
  1729. public A(int y, int z) { Console.WriteLine(y); Console.WriteLine(z); }
  1730. static void Main()
  1731. {
  1732. typeof(A).GetCustomAttributes(false);
  1733. }
  1734. }
  1735. }
  1736. ";
  1737. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  1738. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1739. {
  1740. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1741. var type = (NamedTypeSymbol)ns.GetMember("A");
  1742. var attrs = type.GetAttributes();
  1743. attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 4);
  1744. attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 5);
  1745. attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6);
  1746. };
  1747. string expectedOutput = @"4
  1748. 5
  1749. ";
  1750. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1751. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  1752. }
  1753. [Fact]
  1754. public void TestAttributesWithNamedConstructorArguments_02()
  1755. {
  1756. string source = @"
  1757. using System;
  1758. namespace AttributeTest
  1759. {
  1760. [A(3, z:5, y:4, X = 6)]
  1761. public class A : Attribute
  1762. {
  1763. public int X;
  1764. public A(int x, int y, int z) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); }
  1765. static void Main()
  1766. {
  1767. typeof(A).GetCustomAttributes(false);
  1768. }
  1769. }
  1770. }
  1771. ";
  1772. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  1773. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1774. {
  1775. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1776. var type = (NamedTypeSymbol)ns.GetMember("A");
  1777. var attrs = type.GetAttributes();
  1778. attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3);
  1779. attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4);
  1780. attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5);
  1781. attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6);
  1782. };
  1783. string expectedOutput = @"3
  1784. 4
  1785. 5
  1786. ";
  1787. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1788. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  1789. }
  1790. [WorkItem(541864, "DevDiv")]
  1791. [Fact]
  1792. public void Bug_8769_TestAttributesWithNamedConstructorArguments()
  1793. {
  1794. string source = @"
  1795. using System;
  1796. namespace AttributeTest
  1797. {
  1798. [A(y: 1, x: 2)]
  1799. public class A : Attribute
  1800. {
  1801. public A(int x, int y) { Console.WriteLine(x); Console.WriteLine(y); }
  1802. static void Main()
  1803. {
  1804. typeof(A).GetCustomAttributes(false);
  1805. }
  1806. }
  1807. }
  1808. ";
  1809. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  1810. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1811. {
  1812. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1813. var type = (NamedTypeSymbol)ns.GetMember("A");
  1814. var attrs = type.GetAttributes();
  1815. Assert.Equal(2, attrs.First().CommonConstructorArguments.Length);
  1816. attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2);
  1817. attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 1);
  1818. Assert.Equal(0, attrs.First().CommonNamedArguments.Length);
  1819. };
  1820. string expectedOutput = @"2
  1821. 1
  1822. ";
  1823. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1824. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  1825. }
  1826. [Fact]
  1827. public void TestAttributesWithOptionalConstructorArguments_01()
  1828. {
  1829. string source = @"
  1830. using System;
  1831. namespace AttributeTest
  1832. {
  1833. [A(3, z:5, X = 6)]
  1834. public class A : Attribute
  1835. {
  1836. public int X;
  1837. public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); }
  1838. static void Main()
  1839. {
  1840. typeof(A).GetCustomAttributes(false);
  1841. }
  1842. }
  1843. }
  1844. ";
  1845. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  1846. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1847. {
  1848. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1849. var type = (NamedTypeSymbol)ns.GetMember("A");
  1850. var attrs = type.GetAttributes();
  1851. attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3);
  1852. attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4);
  1853. attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5);
  1854. attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6);
  1855. };
  1856. string expectedOutput = @"3
  1857. 4
  1858. 5
  1859. ";
  1860. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1861. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  1862. }
  1863. [WorkItem(541861, "DevDiv")]
  1864. [Fact]
  1865. public void Bug_8768_TestAttributesWithOptionalConstructorArguments()
  1866. {
  1867. string source = @"
  1868. using System;
  1869. namespace AttributeTest
  1870. {
  1871. [A]
  1872. public class A : Attribute
  1873. {
  1874. public A(int x = 2) { Console.Write(x); }
  1875. static void Main()
  1876. {
  1877. typeof(A).GetCustomAttributes(false);
  1878. }
  1879. }
  1880. }
  1881. ";
  1882. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  1883. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  1884. {
  1885. var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest");
  1886. var type = (NamedTypeSymbol)ns.GetMember("A");
  1887. var attrs = type.GetAttributes();
  1888. var attr = attrs.First();
  1889. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  1890. attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 2);
  1891. Assert.Equal(0, attrs.First().CommonNamedArguments.Length);
  1892. };
  1893. string expectedOutput = @"2";
  1894. // Verify attributes from source and then load metadata to see attributes are written correctly.
  1895. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  1896. }
  1897. [WorkItem(541854, "DevDiv")]
  1898. [Fact]
  1899. public void Bug8761_StringArrayArgument()
  1900. {
  1901. var source =
  1902. @"using System;
  1903. [A(X = new string[] { """" })]
  1904. public class A : Attribute
  1905. {
  1906. public object[] X;
  1907. static void Main()
  1908. {
  1909. typeof(A).GetCustomAttributes(false);
  1910. }
  1911. }
  1912. ";
  1913. CompileAndVerify(source, expectedOutput: "");
  1914. }
  1915. [WorkItem(541856, "DevDiv")]
  1916. [Fact]
  1917. public void Bug8763_NullInArrayInitializer()
  1918. {
  1919. var source =
  1920. @"using System;
  1921. [A(X = new object[] { null })]
  1922. public class A : Attribute
  1923. {
  1924. public object[] X;
  1925. static void Main()
  1926. {
  1927. typeof(A).GetCustomAttributes(false);
  1928. typeof(B).GetCustomAttributes(false);
  1929. }
  1930. }
  1931. [A(X = new object[] { typeof(int), typeof(System.Type), 1, null, ""hi"" })]
  1932. public class B
  1933. {
  1934. public object[] X;
  1935. }
  1936. ";
  1937. CompileAndVerify(source, expectedOutput: "");
  1938. }
  1939. [WorkItem(541856, "DevDiv")]
  1940. [Fact]
  1941. public void AttributeArrayTypeArgument()
  1942. {
  1943. var source =
  1944. @"using System;
  1945. [A(objArray = new string[] { ""a"", null })]
  1946. public class A : Attribute
  1947. {
  1948. public object[] objArray;
  1949. public object obj;
  1950. static void Main()
  1951. {
  1952. typeof(A).GetCustomAttributes(false);
  1953. typeof(B).GetCustomAttributes(false);
  1954. typeof(C).GetCustomAttributes(false);
  1955. typeof(D).GetCustomAttributes(false);
  1956. typeof(E).GetCustomAttributes(false);
  1957. typeof(F).GetCustomAttributes(false);
  1958. typeof(G).GetCustomAttributes(false);
  1959. typeof(H).GetCustomAttributes(false);
  1960. typeof(I).GetCustomAttributes(false);
  1961. }
  1962. }
  1963. [A(objArray = new object[] { ""a"", null, 3 })]
  1964. public class B
  1965. {
  1966. }
  1967. /*
  1968. CS0029: Cannot implicitly convert type 'int[]' to 'object[]'
  1969. [A(objArray = new int[] { 3 })]
  1970. public class Error
  1971. {
  1972. }
  1973. */
  1974. [A(objArray = null)]
  1975. public class C
  1976. {
  1977. }
  1978. [A(obj = new string[] { ""a"" })]
  1979. public class D
  1980. {
  1981. }
  1982. [A(obj = new object[] { ""a"", null, 3 })]
  1983. public class E
  1984. {
  1985. }
  1986. [A(obj = new int[] { 1 })]
  1987. public class F
  1988. {
  1989. }
  1990. [A(obj = 1)]
  1991. public class G
  1992. {
  1993. }
  1994. [A(obj = ""a"")]
  1995. public class H
  1996. {
  1997. }
  1998. [A(obj = null)]
  1999. public class I
  2000. {
  2001. }
  2002. ";
  2003. CompileAndVerify(source, expectedOutput: "");
  2004. }
  2005. [WorkItem(541859, "DevDiv")]
  2006. [Fact]
  2007. public void Bug8766_AttributeCtorOverloadResolution()
  2008. {
  2009. var source =
  2010. @"using System;
  2011. [A(C)]
  2012. public class A : Attribute
  2013. {
  2014. const int C = 1;
  2015. A(int x) { Console.Write(""int""); }
  2016. public A(long x) { Console.Write(""long""); }
  2017. static void Main()
  2018. {
  2019. typeof(A).GetCustomAttributes(false);
  2020. }
  2021. }
  2022. ";
  2023. CompileAndVerify(source, emitOptions: EmitOptions.RefEmitUnsupported_646007, expectedOutput: "int");
  2024. }
  2025. [WorkItem(541876, "DevDiv")]
  2026. [Fact]
  2027. public void Bug8771_AttributeArgumentNameBinding()
  2028. {
  2029. var source =
  2030. @"using System;
  2031. public class A : Attribute
  2032. {
  2033. public A(int x) { Console.WriteLine(x); }
  2034. }
  2035. class B
  2036. {
  2037. const int X = 1;
  2038. [A(X)]
  2039. class C<[A(X)] T>
  2040. {
  2041. const int X = 2;
  2042. }
  2043. static void Main()
  2044. {
  2045. typeof(C<>).GetCustomAttributes(false);
  2046. typeof(C<>).GetGenericArguments()[0].GetCustomAttributes(false);
  2047. }
  2048. }";
  2049. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  2050. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2051. {
  2052. NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B");
  2053. NamedTypeSymbol cClass = bClass.GetTypeMember("C");
  2054. NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A");
  2055. var attrs = cClass.GetAttributes(attributeType);
  2056. Assert.Equal(1, attrs.Count());
  2057. attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2);
  2058. var typeParameters = cClass.TypeParameters;
  2059. Assert.Equal(1, typeParameters.Length);
  2060. attrs = typeParameters[0].GetAttributes(attributeType);
  2061. Assert.Equal(1, attrs.Count());
  2062. attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2);
  2063. };
  2064. string expectedOutput = @"2
  2065. 2
  2066. ";
  2067. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2068. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  2069. }
  2070. [WorkItem(546380, "DevDiv")]
  2071. [Fact]
  2072. public void AttributeWithNestedUnboundGenericType()
  2073. {
  2074. var source =
  2075. @"using System;
  2076. using System.Collections.Generic;
  2077. public class A : Attribute
  2078. {
  2079. public A(object o) { }
  2080. }
  2081. [A(typeof(B<>.C))]
  2082. public class B<T>
  2083. {
  2084. public class C
  2085. {
  2086. }
  2087. }
  2088. public class Program
  2089. {
  2090. static void Main(string[] args)
  2091. {
  2092. }
  2093. }";
  2094. var compilation = CreateCompilationWithMscorlib(source);
  2095. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2096. {
  2097. NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B");
  2098. NamedTypeSymbol cClass = bClass.GetTypeMember("C");
  2099. NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A");
  2100. var attrs = bClass.GetAttributes(attributeType);
  2101. Assert.Equal(1, attrs.Count());
  2102. attrs.First().VerifyValue(0, TypedConstantKind.Type, cClass.AsUnboundGenericType());
  2103. };
  2104. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2105. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator);
  2106. }
  2107. [WorkItem(546380, "DevDiv")]
  2108. [Fact]
  2109. public void AttributeWithUnboundGenericType()
  2110. {
  2111. var source =
  2112. @"using System;
  2113. using System.Collections.Generic;
  2114. public class A : Attribute
  2115. {
  2116. public A(object o) { }
  2117. }
  2118. [A(typeof(B<>))]
  2119. public class B<T>
  2120. {
  2121. }
  2122. class Program
  2123. {
  2124. static void Main(string[] args)
  2125. {
  2126. }
  2127. }";
  2128. var compilation = CreateCompilationWithMscorlib(source);
  2129. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2130. {
  2131. NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B");
  2132. NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A");
  2133. var attrs = bClass.GetAttributes(attributeType);
  2134. Assert.Equal(1, attrs.Count());
  2135. attrs.First().VerifyValue(0, TypedConstantKind.Type, bClass.AsUnboundGenericType());
  2136. };
  2137. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2138. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator);
  2139. }
  2140. [WorkItem(542223, "DevDiv")]
  2141. [Fact]
  2142. public void AttributeArgumentAsEnumFromMetadata()
  2143. {
  2144. var metadata1 = CSharpCompilation.Create("bar.dll",
  2145. references: new[] { MscorlibRef },
  2146. syntaxTrees: new[] { Parse("public enum Bar { Baz }") }).EmitToStream(metadataOnly: true);
  2147. var ref1 = new MetadataImageReference(metadata1);
  2148. var metadata2 = CSharpCompilation.Create("foo.dll", references: new[] { MscorlibRef, ref1 },
  2149. syntaxTrees: new[] {
  2150. SyntaxFactory.ParseSyntaxTree(
  2151. "public class Ca : System.Attribute { public Ca(object o) { } } " +
  2152. "[Ca(Bar.Baz)]" +
  2153. "public class Foo { }") }).EmitToStream(metadataOnly: true);
  2154. var ref2 = new MetadataImageReference(metadata2);
  2155. var compilation = CSharpCompilation.Create("moo.dll", references: new[] { MscorlibRef, ref1, ref2 });
  2156. var foo = compilation.GetTypeByMetadataName("Foo");
  2157. var ca = foo.GetAttributes().First().CommonConstructorArguments.First();
  2158. Assert.Equal("Bar", ca.Type.Name);
  2159. }
  2160. [WorkItem(542318, "DevDiv")]
  2161. [Fact]
  2162. public void AttributeWithDaysOfWeekArgument()
  2163. {
  2164. // DELIBERATE SPEC VIOLATION:
  2165. //
  2166. // Object creation expressions like "new int()" are not considered constant expressions
  2167. // by the specification but they are by the native compiler; we maintain compatibility
  2168. // with this bug.
  2169. //
  2170. // Additionaly, it also treats "new X()", where X is an enum type, as a
  2171. // constant expression with default value 0, we maintaing compatibility with it.
  2172. var source =
  2173. @"using System;
  2174. [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  2175. [A(X = new DayOfWeek())]
  2176. [A(X = new bool())]
  2177. [A(X = new sbyte())]
  2178. [A(X = new byte())]
  2179. [A(X = new short())]
  2180. [A(X = new ushort())]
  2181. [A(X = new int())]
  2182. [A(X = new uint())]
  2183. [A(X = new char())]
  2184. [A(X = new float())]
  2185. [A(X = new Single())]
  2186. [A(X = new double())]
  2187. public class A : Attribute
  2188. {
  2189. public object X;
  2190. const DayOfWeek dayofweek = new DayOfWeek();
  2191. const bool b = new bool();
  2192. const sbyte sb = new sbyte();
  2193. const byte by = new byte();
  2194. const short s = new short();
  2195. const ushort us = new ushort();
  2196. const int i = new int();
  2197. const uint ui = new uint();
  2198. const char c = new char();
  2199. const float f = new float();
  2200. const Single si = new Single();
  2201. const double d = new double();
  2202. public static void Main()
  2203. {
  2204. typeof(A).GetCustomAttributes(false);
  2205. }
  2206. }";
  2207. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  2208. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2209. {
  2210. NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A");
  2211. var attrs = attributeType.GetAttributes(attributeType);
  2212. Assert.Equal(12, attrs.Count());
  2213. var enumerator = attrs.GetEnumerator();
  2214. enumerator.MoveNext();
  2215. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Enum, (int)new DayOfWeek());
  2216. enumerator.MoveNext();
  2217. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new bool());
  2218. enumerator.MoveNext();
  2219. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new sbyte());
  2220. enumerator.MoveNext();
  2221. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new byte());
  2222. enumerator.MoveNext();
  2223. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new short());
  2224. enumerator.MoveNext();
  2225. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new ushort());
  2226. enumerator.MoveNext();
  2227. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new int());
  2228. enumerator.MoveNext();
  2229. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new uint());
  2230. enumerator.MoveNext();
  2231. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new char());
  2232. enumerator.MoveNext();
  2233. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new float());
  2234. enumerator.MoveNext();
  2235. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new Single());
  2236. enumerator.MoveNext();
  2237. enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new double());
  2238. };
  2239. string expectedOutput = "";
  2240. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2241. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  2242. }
  2243. [WorkItem(542534, "DevDiv")]
  2244. [Fact]
  2245. public void AttributeOnDefiningPartialMethodDeclaration()
  2246. {
  2247. var source =
  2248. @"
  2249. using System;
  2250. class A : Attribute { }
  2251. partial class Program
  2252. {
  2253. [A]
  2254. static partial void Foo();
  2255. static partial void Foo() { }
  2256. static void Main()
  2257. {
  2258. Console.WriteLine(((Action) Foo).Method.GetCustomAttributesData().Count);
  2259. }
  2260. }
  2261. ";
  2262. CompileAndVerify(source, expectedOutput: "1");
  2263. }
  2264. [WorkItem(542534, "DevDiv")]
  2265. [Fact]
  2266. public void AttributeOnDefiningPartialMethodDeclaration_02()
  2267. {
  2268. var source1 = @"
  2269. using System;
  2270. class A1 : Attribute {}
  2271. class B1 : Attribute {}
  2272. class C1 : Attribute {}
  2273. class D1 : Attribute {}
  2274. class E1 : Attribute {}
  2275. partial class Program
  2276. {
  2277. [A1]
  2278. [return: B1]
  2279. static partial void Foo<[C1] T, [D1] U>([E1]int x);
  2280. }
  2281. ";
  2282. var source2 =
  2283. @"
  2284. using System;
  2285. class A2 : Attribute {}
  2286. class B2 : Attribute {}
  2287. class C2 : Attribute {}
  2288. class D2 : Attribute {}
  2289. class E2 : Attribute {}
  2290. partial class Program
  2291. {
  2292. [A2]
  2293. [return: B2]
  2294. static partial void Foo<[C2] U, [D2] T>([E2]int y) { }
  2295. static void Main()
  2296. {}
  2297. }
  2298. ";
  2299. var compilation = CreateCompilationWithMscorlib(new[] { source1, source2 }, compOptions: TestOptions.Exe);
  2300. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2301. {
  2302. var programClass = m.GlobalNamespace.GetTypeMember("Program");
  2303. var fooMethod = (MethodSymbol)programClass.GetMember("Foo");
  2304. TestAttributeOnPartialMethodHelper(m, fooMethod);
  2305. };
  2306. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2307. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: "");
  2308. }
  2309. private void TestAttributeOnPartialMethodHelper(ModuleSymbol m, MethodSymbol fooMethod)
  2310. {
  2311. var a1Class = m.GlobalNamespace.GetTypeMember("A1");
  2312. var a2Class = m.GlobalNamespace.GetTypeMember("A2");
  2313. var b1Class = m.GlobalNamespace.GetTypeMember("B1");
  2314. var b2Class = m.GlobalNamespace.GetTypeMember("B2");
  2315. var c1Class = m.GlobalNamespace.GetTypeMember("C1");
  2316. var c2Class = m.GlobalNamespace.GetTypeMember("C2");
  2317. var d1Class = m.GlobalNamespace.GetTypeMember("D1");
  2318. var d2Class = m.GlobalNamespace.GetTypeMember("D2");
  2319. var e1Class = m.GlobalNamespace.GetTypeMember("E1");
  2320. var e2Class = m.GlobalNamespace.GetTypeMember("E2");
  2321. Assert.Equal(1, fooMethod.GetAttributes(a1Class).Count());
  2322. Assert.Equal(1, fooMethod.GetAttributes(a2Class).Count());
  2323. Assert.Equal(1, fooMethod.GetReturnTypeAttributes().Where(a => a.AttributeClass == b1Class).Count());
  2324. Assert.Equal(1, fooMethod.GetReturnTypeAttributes().Where(a => a.AttributeClass == b2Class).Count());
  2325. var typeParam1 = fooMethod.TypeParameters[0];
  2326. Assert.Equal(1, typeParam1.GetAttributes(c1Class).Count());
  2327. Assert.Equal(1, typeParam1.GetAttributes(c2Class).Count());
  2328. var typeParam2 = fooMethod.TypeParameters[1];
  2329. Assert.Equal(1, typeParam2.GetAttributes(d1Class).Count());
  2330. Assert.Equal(1, typeParam2.GetAttributes(d2Class).Count());
  2331. var param = fooMethod.Parameters[0];
  2332. Assert.Equal(1, param.GetAttributes(e1Class).Count());
  2333. Assert.Equal(1, param.GetAttributes(e2Class).Count());
  2334. }
  2335. [WorkItem(542533, "DevDiv")]
  2336. [Fact]
  2337. public void AttributesInMultipleParialDeclarations_Type()
  2338. {
  2339. var source1 = @"
  2340. using System;
  2341. class A : Attribute {}
  2342. [A]
  2343. partial class X {}";
  2344. var source2 = @"
  2345. using System;
  2346. class B : Attribute {}
  2347. [B]
  2348. partial class X {}
  2349. class C
  2350. {
  2351. public static void Main()
  2352. {
  2353. typeof(X).GetCustomAttributes(false);
  2354. }
  2355. }";
  2356. var compilation = CreateCompilationWithMscorlib(new[] { source1, source2 }, compOptions: TestOptions.Exe);
  2357. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2358. {
  2359. var aClass = m.GlobalNamespace.GetTypeMember("A");
  2360. var bClass = m.GlobalNamespace.GetTypeMember("B");
  2361. var type = m.GlobalNamespace.GetTypeMember("X");
  2362. Assert.Equal(2, type.GetAttributes().Length);
  2363. Assert.Equal(1, type.GetAttributes(aClass).Count());
  2364. Assert.Equal(1, type.GetAttributes(bClass).Count());
  2365. };
  2366. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2367. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: "");
  2368. }
  2369. [WorkItem(542533, "DevDiv")]
  2370. [Fact]
  2371. public void AttributesInMultipleParialDeclarations_TypeParam()
  2372. {
  2373. var source1 = @"
  2374. using System;
  2375. class A : Attribute {}
  2376. partial class Gen<[A] T> {}";
  2377. var source2 = @"
  2378. using System;
  2379. class B : Attribute {}
  2380. partial class Gen<[B] T> {}
  2381. class C
  2382. {
  2383. public static void Main() {}
  2384. }";
  2385. var compilation = CreateCompilationWithMscorlib(new[] { source1, source2 }, compOptions: TestOptions.Exe);
  2386. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2387. {
  2388. var aClass = m.GlobalNamespace.GetTypeMember("A");
  2389. var bClass = m.GlobalNamespace.GetTypeMember("B");
  2390. var type = m.GlobalNamespace.GetTypeMember("Gen");
  2391. var typeParameter = type.TypeParameters.First();
  2392. Assert.Equal(2, typeParameter.GetAttributes().Length);
  2393. Assert.Equal(1, typeParameter.GetAttributes(aClass).Count());
  2394. Assert.Equal(1, typeParameter.GetAttributes(bClass).Count());
  2395. };
  2396. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2397. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: "");
  2398. }
  2399. [WorkItem(542550, "DevDiv")]
  2400. [Fact]
  2401. public void Bug9824()
  2402. {
  2403. var source =
  2404. @"
  2405. using System;
  2406. public class TAttribute : Attribute { public static void Main () {} }
  2407. [T]
  2408. public class GClass<T> where T : Attribute
  2409. {
  2410. [T]
  2411. public enum E { }
  2412. }
  2413. ";
  2414. var compilation = CreateCompilationWithMscorlib(source);
  2415. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2416. {
  2417. NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("TAttribute");
  2418. NamedTypeSymbol GClass = m.GlobalNamespace.GetTypeMember("GClass").AsUnboundGenericType();
  2419. Assert.Equal(1, GClass.GetAttributes(attributeType).Count());
  2420. NamedTypeSymbol enumE = GClass.GetTypeMember("E");
  2421. Assert.Equal(1, enumE.GetAttributes(attributeType).Count());
  2422. };
  2423. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2424. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null);
  2425. }
  2426. [WorkItem(543135, "DevDiv")]
  2427. [Fact]
  2428. public void AttributeAndDefaultValueArguments_01()
  2429. {
  2430. var source = @"
  2431. using System;
  2432. [A]
  2433. public class A : Attribute
  2434. {
  2435. public A(object a = default(A)) { }
  2436. }
  2437. [A(1)]
  2438. class C
  2439. {
  2440. public static void Main()
  2441. {
  2442. typeof(C).GetCustomAttributes(false);
  2443. }
  2444. }";
  2445. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  2446. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2447. {
  2448. NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A");
  2449. NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C");
  2450. var attrs = attributeType.GetAttributes(attributeType);
  2451. Assert.Equal(1, attrs.Count());
  2452. var attr = attrs.First();
  2453. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  2454. attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null);
  2455. attrs = cClass.GetAttributes(attributeType);
  2456. Assert.Equal(1, attrs.Count());
  2457. attr = attrs.First();
  2458. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  2459. attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 1);
  2460. };
  2461. string expectedOutput = "";
  2462. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2463. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  2464. }
  2465. [WorkItem(543135, "DevDiv")]
  2466. [Fact]
  2467. public void AttributeAndDefaultValueArguments_02()
  2468. {
  2469. var source = @"
  2470. using System;
  2471. [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
  2472. public class A : System.Attribute
  2473. {
  2474. public A(object o = null) { }
  2475. }
  2476. [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
  2477. public class B : System.Attribute
  2478. {
  2479. public B(object o = default(B)) { }
  2480. }
  2481. [A]
  2482. [A(null)]
  2483. [B]
  2484. [B(default(B))]
  2485. class C
  2486. {
  2487. public static void Main()
  2488. {
  2489. typeof(C).GetCustomAttributes(false);
  2490. }
  2491. }
  2492. ";
  2493. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  2494. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2495. {
  2496. NamedTypeSymbol attributeTypeA = m.GlobalNamespace.GetTypeMember("A");
  2497. NamedTypeSymbol attributeTypeB = m.GlobalNamespace.GetTypeMember("B");
  2498. NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C");
  2499. // Verify A attributes
  2500. var attrs = cClass.GetAttributes(attributeTypeA);
  2501. Assert.Equal(2, attrs.Count());
  2502. var attr = attrs.First();
  2503. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  2504. attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null);
  2505. attr = attrs.ElementAt(1);
  2506. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  2507. attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null);
  2508. // Verify B attributes
  2509. attrs = cClass.GetAttributes(attributeTypeB);
  2510. Assert.Equal(2, attrs.Count());
  2511. attr = attrs.First();
  2512. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  2513. attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null);
  2514. attr = attrs.ElementAt(1);
  2515. Assert.Equal(1, attr.CommonConstructorArguments.Length);
  2516. attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null);
  2517. };
  2518. string expectedOutput = "";
  2519. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2520. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput);
  2521. }
  2522. [WorkItem(529044, "DevDiv")]
  2523. [Fact]
  2524. public void AttributeNameLookup()
  2525. {
  2526. var source = @"
  2527. using System;
  2528. public class MyClass<T>
  2529. {
  2530. }
  2531. public class MyClassAttribute : Attribute
  2532. {
  2533. }
  2534. [MyClass]
  2535. public class Test
  2536. {
  2537. public static void Main()
  2538. {
  2539. typeof(Test).GetCustomAttributes(false);
  2540. }
  2541. }
  2542. ";
  2543. var compilation = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Exe);
  2544. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2545. {
  2546. NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("MyClassAttribute");
  2547. NamedTypeSymbol testClass = m.GlobalNamespace.GetTypeMember("Test");
  2548. // Verify attributes
  2549. var attrs = testClass.GetAttributes(attributeType);
  2550. Assert.Equal(1, attrs.Count());
  2551. };
  2552. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2553. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: "");
  2554. }
  2555. [WorkItem(542003, "DevDiv")]
  2556. [Fact]
  2557. public void Bug8956_NullArgumentToSystemTypeParam()
  2558. {
  2559. string source = @"
  2560. using System;
  2561. class A : Attribute
  2562. {
  2563. public A(System.Type t) {}
  2564. }
  2565. [A(null)]
  2566. class Test
  2567. {
  2568. static void Main(string[] args)
  2569. {
  2570. typeof(Test).GetCustomAttributes(false);
  2571. }
  2572. }
  2573. ";
  2574. CompileAndVerify(source);
  2575. }
  2576. [Fact]
  2577. public void SpecialNameAttributeFromSource()
  2578. {
  2579. string source = @"
  2580. using System;
  2581. using System.Runtime.CompilerServices;
  2582. [SpecialName()]
  2583. public struct S
  2584. {
  2585. [SpecialName]
  2586. byte this[byte x] { get { return x; } }
  2587. [SpecialName]
  2588. public event Action<string> E;
  2589. }
  2590. ";
  2591. var comp = CreateCompilationWithMscorlib(source);
  2592. var global = comp.SourceModule.GlobalNamespace;
  2593. var typesym = global.GetMember("S") as NamedTypeSymbol;
  2594. Assert.NotNull(typesym);
  2595. Assert.True(typesym.HasSpecialName);
  2596. var idxsym = typesym.GetMember(WellKnownMemberNames.Indexer) as PropertySymbol;
  2597. Assert.NotNull(idxsym);
  2598. Assert.True(idxsym.HasSpecialName);
  2599. var etsym = typesym.GetMember("E") as EventSymbol;
  2600. Assert.NotNull(etsym);
  2601. Assert.True(etsym.HasSpecialName);
  2602. }
  2603. [WorkItem(546277, "DevDiv")]
  2604. [Fact]
  2605. public void TestArrayTypeInAttributeArgument()
  2606. {
  2607. var source =
  2608. @"using System;
  2609. public class W {}
  2610. public class Y<T>
  2611. {
  2612. public class F {}
  2613. public class Z<U> {}
  2614. }
  2615. public class X : Attribute
  2616. {
  2617. public X(Type y) { }
  2618. }
  2619. [X(typeof(W[]))]
  2620. public class C1 {}
  2621. [X(typeof(W[,]))]
  2622. public class C2 {}
  2623. [X(typeof(W[,][]))]
  2624. public class C3 {}
  2625. [X(typeof(Y<W>[][,]))]
  2626. public class C4 {}
  2627. [X(typeof(Y<int>.F[,][][,,]))]
  2628. public class C5 {}
  2629. [X(typeof(Y<int>.Z<W>[,][]))]
  2630. public class C6 {}
  2631. ";
  2632. var compilation = CreateCompilationWithMscorlib(source);
  2633. Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) =>
  2634. {
  2635. NamedTypeSymbol classW = m.GlobalNamespace.GetTypeMember("W");
  2636. NamedTypeSymbol classY = m.GlobalNamespace.GetTypeMember("Y");
  2637. NamedTypeSymbol classF = classY.GetTypeMember("F");
  2638. NamedTypeSymbol classZ = classY.GetTypeMember("Z");
  2639. NamedTypeSymbol classX = m.GlobalNamespace.GetTypeMember("X");
  2640. NamedTypeSymbol classC1 = m.GlobalNamespace.GetTypeMember("C1");
  2641. NamedTypeSymbol classC2 = m.GlobalNamespace.GetTypeMember("C2");
  2642. NamedTypeSymbol classC3 = m.GlobalNamespace.GetTypeMember("C3");
  2643. NamedTypeSymbol classC4 = m.GlobalNamespace.GetTypeMember("C4");
  2644. NamedTypeSymbol classC5 = m.GlobalNamespace.GetTypeMember("C5");
  2645. NamedTypeSymbol classC6 = m.GlobalNamespace.GetTypeMember("C6");
  2646. var attrs = classC1.GetAttributes();
  2647. Assert.Equal(1, attrs.Length);
  2648. var typeArg = new ArrayTypeSymbol(m.ContainingAssembly, classW, default(ImmutableArray<CustomModifier>));
  2649. attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg);
  2650. attrs = classC2.GetAttributes();
  2651. Assert.Equal(1, attrs.Length);
  2652. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, classW, default(ImmutableArray<CustomModifier>), rank: 2);
  2653. attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg);
  2654. attrs = classC3.GetAttributes();
  2655. Assert.Equal(1, attrs.Length);
  2656. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, classW, default(ImmutableArray<CustomModifier>));
  2657. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, typeArg, default(ImmutableArray<CustomModifier>), rank: 2);
  2658. attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg);
  2659. attrs = classC4.GetAttributes();
  2660. Assert.Equal(1, attrs.Length);
  2661. NamedTypeSymbol classYOfW = classY.ConstructIfGeneric(ImmutableArray.Create<TypeSymbol>(classW));
  2662. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, classYOfW, default(ImmutableArray<CustomModifier>), rank: 2);
  2663. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, typeArg, default(ImmutableArray<CustomModifier>));
  2664. attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg);
  2665. attrs = classC5.GetAttributes();
  2666. Assert.Equal(1, attrs.Length);
  2667. NamedTypeSymbol classYOfInt = classY.ConstructIfGeneric(ImmutableArray.Create<TypeSymbol>(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)));
  2668. NamedTypeSymbol substNestedF = classYOfInt.GetTypeMember("F");
  2669. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, substNestedF, default(ImmutableArray<CustomModifier>), rank: 3);
  2670. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, typeArg, default(ImmutableArray<CustomModifier>));
  2671. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, typeArg, default(ImmutableArray<CustomModifier>), rank: 2);
  2672. attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg);
  2673. attrs = classC6.GetAttributes();
  2674. Assert.Equal(1, attrs.Length);
  2675. NamedTypeSymbol substNestedZ = classYOfInt.GetTypeMember("Z").ConstructIfGeneric(ImmutableArray.Create<TypeSymbol>(classW));
  2676. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, substNestedZ, default(ImmutableArray<CustomModifier>));
  2677. typeArg = new ArrayTypeSymbol(m.ContainingAssembly, typeArg, default(ImmutableArray<CustomModifier>), rank: 2);
  2678. attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg);
  2679. };
  2680. // Verify attributes from source and then load metadata to see attributes are written correctly.
  2681. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator);
  2682. }
  2683. [WorkItem(546621, "DevDiv")]
  2684. [Fact]
  2685. public void TestUnicodeAttributeArgument_Bug16353()
  2686. {
  2687. var source =
  2688. @"using System;
  2689. [Obsolete(UnicodeHighSurrogate)]
  2690. class C
  2691. {
  2692. public const string UnicodeHighSurrogate = ""\uD800"";
  2693. public const string UnicodeReplacementCharacter = ""\uFFFD"";
  2694. static void Main()
  2695. {
  2696. string message = ((ObsoleteAttribute)typeof(C).GetCustomAttributes(false)[0]).Message;
  2697. Console.WriteLine(message == UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2698. }
  2699. }";
  2700. CompileAndVerify(source, emitOptions: EmitOptions.RefEmitBug, expectedOutput: "True");
  2701. }
  2702. [WorkItem(546621, "DevDiv")]
  2703. [Fact]
  2704. public void TestUnicodeAttributeArgumentsStrings()
  2705. {
  2706. string HighSurrogateCharacter = "\uD800";
  2707. string LowSurrogateCharacter = "\uDC00";
  2708. string UnicodeReplacementCharacter = "\uFFFD";
  2709. string UnicodeLT0080 = "\u007F";
  2710. string UnicodeLT0800 = "\u07FF";
  2711. string UnicodeLT10000 = "\uFFFF";
  2712. string source = @"
  2713. using System;
  2714. public class C
  2715. {
  2716. public const string UnicodeSurrogate1 = ""\uD800"";
  2717. public const string UnicodeSurrogate2 = ""\uD800\uD800"";
  2718. public const string UnicodeSurrogate3 = ""\uD800\uDC00"";
  2719. public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800"";
  2720. public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00"";
  2721. public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00"";
  2722. public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00"";
  2723. public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00"";
  2724. public const string UnicodeSurrogate9 = ""\uDC00\uDC00"";
  2725. [Obsolete(UnicodeSurrogate1)]
  2726. public int x1;
  2727. [Obsolete(UnicodeSurrogate2)]
  2728. public int x2;
  2729. [Obsolete(UnicodeSurrogate3)]
  2730. public int x3;
  2731. [Obsolete(UnicodeSurrogate4)]
  2732. public int x4;
  2733. [Obsolete(UnicodeSurrogate5)]
  2734. public int x5;
  2735. [Obsolete(UnicodeSurrogate6)]
  2736. public int x6;
  2737. [Obsolete(UnicodeSurrogate7)]
  2738. public int x7;
  2739. [Obsolete(UnicodeSurrogate8)]
  2740. public int x8;
  2741. [Obsolete(UnicodeSurrogate9)]
  2742. public int x9;
  2743. }
  2744. ";
  2745. Action<FieldSymbol, string> VerifyAttributes = (field, value) =>
  2746. {
  2747. var attributes = field.GetAttributes();
  2748. Assert.Equal(1, attributes.Length);
  2749. attributes[0].VerifyValue(0, TypedConstantKind.Primitive, value);
  2750. };
  2751. Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol module) =>
  2752. {
  2753. var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
  2754. var x1 = type.GetMember<FieldSymbol>("x1");
  2755. var x2 = type.GetMember<FieldSymbol>("x2");
  2756. var x3 = type.GetMember<FieldSymbol>("x3");
  2757. var x4 = type.GetMember<FieldSymbol>("x4");
  2758. var x5 = type.GetMember<FieldSymbol>("x5");
  2759. var x6 = type.GetMember<FieldSymbol>("x6");
  2760. var x7 = type.GetMember<FieldSymbol>("x7");
  2761. var x8 = type.GetMember<FieldSymbol>("x8");
  2762. var x9 = type.GetMember<FieldSymbol>("x9");
  2763. // public const string UnicodeSurrogate1 = ""\uD800"";
  2764. VerifyAttributes(x1, isFromSource ?
  2765. HighSurrogateCharacter :
  2766. UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2767. // public const string UnicodeSurrogate2 = ""\uD800\uD800"";
  2768. VerifyAttributes(x2, isFromSource ?
  2769. HighSurrogateCharacter + HighSurrogateCharacter :
  2770. UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2771. // public const string UnicodeSurrogate3 = ""\uD800\uDC00"";
  2772. VerifyAttributes(x3, HighSurrogateCharacter + LowSurrogateCharacter);
  2773. // public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800"";
  2774. VerifyAttributes(x4, isFromSource ?
  2775. HighSurrogateCharacter + UnicodeLT0800 + HighSurrogateCharacter :
  2776. UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2777. // public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00"";
  2778. VerifyAttributes(x5, isFromSource ?
  2779. HighSurrogateCharacter + UnicodeLT0080 + LowSurrogateCharacter :
  2780. UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0080 + UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2781. // public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00"";
  2782. VerifyAttributes(x6, isFromSource ?
  2783. HighSurrogateCharacter + UnicodeLT0800 + LowSurrogateCharacter :
  2784. UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2785. // public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00"";
  2786. VerifyAttributes(x7, isFromSource ?
  2787. HighSurrogateCharacter + UnicodeLT10000 + LowSurrogateCharacter :
  2788. UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT10000 + UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2789. // public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00"";
  2790. VerifyAttributes(x8, isFromSource ?
  2791. HighSurrogateCharacter + HighSurrogateCharacter + LowSurrogateCharacter :
  2792. UnicodeReplacementCharacter + UnicodeReplacementCharacter + HighSurrogateCharacter + LowSurrogateCharacter);
  2793. // public const string UnicodeSurrogate9 = ""\uDC00\uDC00"";
  2794. VerifyAttributes(x9, isFromSource ?
  2795. LowSurrogateCharacter + LowSurrogateCharacter :
  2796. UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter);
  2797. };
  2798. CompileAndVerify(source, emitOptions: EmitOptions.CCI, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
  2799. }
  2800. [Fact]
  2801. [WorkItem(546896, "DevDiv")]
  2802. public void MissingTypeInSignature()
  2803. {
  2804. string lib1 = @"
  2805. public enum E { A, B, C }
  2806. ";
  2807. string lib2 = @"
  2808. public class A : System.Attribute
  2809. {
  2810. public A(E e) { }
  2811. }
  2812. public class C
  2813. {
  2814. [A(E.A)]
  2815. public void M() { }
  2816. }
  2817. ";
  2818. string main = @"
  2819. class D : C
  2820. {
  2821. void N() { M(); }
  2822. }
  2823. ";
  2824. var c1 = CreateCompilationWithMscorlib(lib1);
  2825. var r1 = c1.EmitToImageReference();
  2826. var c2 = CreateCompilationWithMscorlib(lib2, references: new[] { r1 });
  2827. var r2 = c2.EmitToImageReference();
  2828. var cm = CreateCompilationWithMscorlib(main, new[] { r2 });
  2829. cm.VerifyDiagnostics();
  2830. var model = cm.GetSemanticModel(cm.SyntaxTrees[0]);
  2831. int index = main.IndexOf("M()");
  2832. var m = (ExpressionSyntax)cm.SyntaxTrees[0].GetCompilationUnitRoot().FindToken(index).Parent.Parent;
  2833. var info = model.GetSymbolInfo(m);
  2834. var args = info.Symbol.GetAttributes()[0].CommonConstructorArguments;
  2835. // unresolved type - parameter ignored
  2836. Assert.Equal(0, args.Length);
  2837. }
  2838. [Fact]
  2839. [WorkItem(569089, "DevDiv")]
  2840. public void NullArrays()
  2841. {
  2842. var source = @"
  2843. using System;
  2844. public class A : Attribute
  2845. {
  2846. public A(object[] a, int[] b)
  2847. {
  2848. }
  2849. public object[] P { get; set; }
  2850. public int[] F;
  2851. }
  2852. [A(null, null, P = null, F = null)]
  2853. class C
  2854. {
  2855. }
  2856. ";
  2857. CompileAndVerify(source, symbolValidator: (m) =>
  2858. {
  2859. var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
  2860. var attr = c.GetAttributes().Single();
  2861. var args = attr.ConstructorArguments.ToArray();
  2862. Assert.True(args[0].IsNull);
  2863. Assert.Equal("object[]", args[0].Type.ToDisplayString());
  2864. Assert.Throws<InvalidOperationException>(() => args[0].Value);
  2865. Assert.True(args[1].IsNull);
  2866. Assert.Equal("int[]", args[1].Type.ToDisplayString());
  2867. Assert.Throws<InvalidOperationException>(() => args[1].Value);
  2868. var named = attr.NamedArguments.ToDictionary(e => e.Key, e => e.Value);
  2869. Assert.True(named["P"].IsNull);
  2870. Assert.Equal("object[]", named["P"].Type.ToDisplayString());
  2871. Assert.Throws<InvalidOperationException>(() => named["P"].Value);
  2872. Assert.True(named["F"].IsNull);
  2873. Assert.Equal("int[]", named["F"].Type.ToDisplayString());
  2874. Assert.Throws<InvalidOperationException>(() => named["F"].Value);
  2875. });
  2876. }
  2877. [Fact]
  2878. public void NullTypeAndString()
  2879. {
  2880. var source = @"
  2881. using System;
  2882. public class A : Attribute
  2883. {
  2884. public A(Type t, string s)
  2885. {
  2886. }
  2887. }
  2888. [A(null, null)]
  2889. class C
  2890. {
  2891. }
  2892. ";
  2893. CompileAndVerify(source, symbolValidator: (m) =>
  2894. {
  2895. var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
  2896. var attr = c.GetAttributes().Single();
  2897. var args = attr.ConstructorArguments.ToArray();
  2898. Assert.Null(args[0].Value);
  2899. Assert.Equal("Type", args[0].Type.Name);
  2900. Assert.Throws<InvalidOperationException>(() => args[0].Values);
  2901. Assert.Null(args[1].Value);
  2902. Assert.Equal("String", args[1].Type.Name);
  2903. Assert.Throws<InvalidOperationException>(() => args[1].Values);
  2904. });
  2905. }
  2906. [WorkItem(121)]
  2907. [Fact(Skip = "121")]
  2908. public void Bug_AttributeOnWrongGenericParameter()
  2909. {
  2910. var source = @"
  2911. using System;
  2912. class XAttribute : Attribute { }
  2913. class C<T>
  2914. {
  2915. public void M<[X]U>() { }
  2916. }
  2917. ";
  2918. CompileAndVerify(source, symbolValidator: module =>
  2919. {
  2920. var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
  2921. var classTypeParameter = @class.TypeParameters.Single();
  2922. var method = @class.GetMember<MethodSymbol>("M");
  2923. var methodTypeParameter = method.TypeParameters.Single();
  2924. Assert.Empty(classTypeParameter.GetAttributes());
  2925. var attribute = methodTypeParameter.GetAttributes().Single();
  2926. Assert.Equal("XAttribute", attribute.AttributeClass.Name);
  2927. });
  2928. }
  2929. #endregion
  2930. #region Error Tests
  2931. [Fact]
  2932. public void AttributeConstructorErrors1()
  2933. {
  2934. var compilation = CreateCompilationWithMscorlibAndSystemCore(@"
  2935. using System;
  2936. static class m
  2937. {
  2938. public static int NotAConstant()
  2939. {
  2940. return 9;
  2941. }
  2942. }
  2943. public enum e1
  2944. {
  2945. a
  2946. }
  2947. [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  2948. class XAttribute : Attribute
  2949. {
  2950. public XAttribute()
  2951. {
  2952. }
  2953. public XAttribute(decimal d)
  2954. {
  2955. }
  2956. public XAttribute(ref int i)
  2957. {
  2958. }
  2959. public XAttribute(e1 e)
  2960. {
  2961. }
  2962. }
  2963. [XDoesNotExist()]
  2964. [X(1m)]
  2965. [X(1)]
  2966. [X(e1.a)]
  2967. [X(A.dyn)]
  2968. [X(m.NotAConstant() + 2)]
  2969. class A
  2970. {
  2971. public const dynamic dyn = null;
  2972. }
  2973. ", compOptions: TestOptions.Dll);
  2974. // Note that the dev11 compiler produces errors that XDoesNotExist *and* XDoesNotExistAttribute could not be found.
  2975. // It does not go on to produce the other errors.
  2976. compilation.VerifyDiagnostics(
  2977. // (33,2): error CS0246: The type or namespace name 'XDoesNotExist' could not be found (are you missing a using directive or an assembly reference?)
  2978. // [XDoesNotExist()]
  2979. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExist").WithLocation(33, 2),
  2980. // (34,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type
  2981. // [X(1m)]
  2982. Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(34, 2),
  2983. // (35,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type
  2984. // [X(1)]
  2985. Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(35, 2),
  2986. // (37,2): error CS0121: The call is ambiguous between the following methods or properties: 'XAttribute.XAttribute(decimal)' and 'XAttribute.XAttribute(ref int)'
  2987. // [X(A.dyn)]
  2988. Diagnostic(ErrorCode.ERR_AmbigCall, "X(A.dyn)").WithArguments("XAttribute.XAttribute(decimal)", "XAttribute.XAttribute(ref int)").WithLocation(37, 2),
  2989. // (38,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type
  2990. // [X(m.NotAConstant() + 2)]
  2991. Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(38, 2));
  2992. }
  2993. [Fact]
  2994. public void AttributeNamedArgumentErrors1()
  2995. {
  2996. var compilation = CreateCompilationWithMscorlib(@"
  2997. using System;
  2998. [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  2999. class XAttribute : Attribute
  3000. {
  3001. public void F1(int i)
  3002. {
  3003. }
  3004. private int PrivateField;
  3005. public static int SharedProperty { get; set; }
  3006. public int? ReadOnlyProperty
  3007. {
  3008. get { return null; }
  3009. }
  3010. public decimal BadDecimalType { get; set; }
  3011. public System.DateTime BadDateType { get; set; }
  3012. public Attribute[] BadArrayType { get; set; }
  3013. }
  3014. [X(NotFound = null)]
  3015. [X(F1 = null)]
  3016. [X(PrivateField = null)]
  3017. [X(SharedProperty = null)]
  3018. [X(ReadOnlyProperty = null)]
  3019. [X(BadDecimalType = null)]
  3020. [X(BadDateType = null)]
  3021. [X(BadArrayType = null)]
  3022. class A
  3023. {
  3024. }
  3025. ", compOptions: TestOptions.Dll);
  3026. compilation.VerifyDiagnostics( // (21,4): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?)
  3027. // [X(NotFound = null)]
  3028. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound"),
  3029. // (22,4): error CS0617: 'F1' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.
  3030. // [X(F1 = null)]
  3031. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "F1").WithArguments("F1"),
  3032. // (23,4): error CS0122: 'XAttribute.PrivateField' is inaccessible due to its protection level
  3033. // [X(PrivateField = null)]
  3034. Diagnostic(ErrorCode.ERR_BadAccess, "PrivateField").WithArguments("XAttribute.PrivateField"),
  3035. // (24,4): error CS0617: 'SharedProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.
  3036. // [X(SharedProperty = null)]
  3037. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "SharedProperty").WithArguments("SharedProperty"),
  3038. // (25,4): error CS0617: 'ReadOnlyProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.
  3039. // [X(ReadOnlyProperty = null)]
  3040. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ReadOnlyProperty").WithArguments("ReadOnlyProperty"),
  3041. // (26,4): error CS0655: 'BadDecimalType' is not a valid named attribute argument because it is not a valid attribute parameter type
  3042. // [X(BadDecimalType = null)]
  3043. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDecimalType").WithArguments("BadDecimalType"),
  3044. // (27,4): error CS0655: 'BadDateType' is not a valid named attribute argument because it is not a valid attribute parameter type
  3045. // [X(BadDateType = null)]
  3046. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDateType").WithArguments("BadDateType"),
  3047. // (28,4): error CS0655: 'BadArrayType' is not a valid named attribute argument because it is not a valid attribute parameter type
  3048. // [X(BadArrayType = null)]
  3049. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadArrayType").WithArguments("BadArrayType"));
  3050. }
  3051. [Fact]
  3052. public void AttributeNoMultipleAndInvalidTarget()
  3053. {
  3054. string source = @"
  3055. using CustomAttribute;
  3056. [Base(1)]
  3057. [BaseAttribute(""SOS"")]
  3058. static class AttributeMod
  3059. {
  3060. [Derived('Q')]
  3061. [Derived('C')]
  3062. public class Foo
  3063. {
  3064. }
  3065. [BaseAttribute(1)]
  3066. [Base("""")]
  3067. public class Bar
  3068. {
  3069. }
  3070. }";
  3071. var references = new[] { new MetadataImageReference(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) };
  3072. CSharpCompilationOptions opt = TestOptions.Dll;
  3073. var compilation = CreateCompilationWithMscorlib(source, references, compOptions: opt);
  3074. compilation.VerifyDiagnostics(
  3075. // (4,2): error CS0579: Duplicate 'BaseAttribute' attribute
  3076. Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"BaseAttribute").WithArguments("BaseAttribute"),
  3077. // (7,6): error CS0592: Attribute 'Derived' is not valid on this declaration type. It is only valid on 'struct, method, parameter' declarations.
  3078. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Derived").WithArguments("Derived", "struct, method, parameter"),
  3079. // (8,6): error CS0579: Duplicate 'Derived' attribute
  3080. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Derived").WithArguments("Derived"),
  3081. // (13,6): error CS0579: Duplicate 'Base' attribute
  3082. Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"Base").WithArguments("Base"));
  3083. }
  3084. [Fact]
  3085. public void AttributeAmbiguousSpecification()
  3086. {
  3087. string source = @"
  3088. using System;
  3089. [AttributeUsage(AttributeTargets.All)]
  3090. public class X : Attribute {}
  3091. [AttributeUsage(AttributeTargets.All)]
  3092. public class XAttribute : Attribute { }
  3093. [X] // Error: Ambiguous
  3094. class Class1 { }
  3095. [XAttribute] // Refers to XAttribute
  3096. class Class2 { }
  3097. [@X] // Refers to X
  3098. class Class3 { }
  3099. [@XAttribute] // Refers to XAttribute
  3100. class Class4 { }
  3101. ";
  3102. var compilation = CreateCompilationWithMscorlib(source);
  3103. compilation.VerifyDiagnostics(
  3104. // (10,2): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute'
  3105. // [X] // Error: Ambiguous
  3106. Diagnostic(ErrorCode.ERR_AmbigousAttribute, "X").WithArguments("X", "X", "XAttribute").WithLocation(10, 2));
  3107. }
  3108. [Fact]
  3109. public void AttributeErrorVerbatimIdentifierInSpecification()
  3110. {
  3111. string source = @"
  3112. using System;
  3113. [AttributeUsage(AttributeTargets.All)]
  3114. public class XAttribute : Attribute { }
  3115. [X] // Refers to X
  3116. class Class1 { }
  3117. [XAttribute] // Refers to XAttribute
  3118. class Class2 { }
  3119. [@X] // Error: No attribute named X
  3120. class Class3 { }
  3121. ";
  3122. var compilation = CreateCompilationWithMscorlib(source);
  3123. compilation.VerifyDiagnostics(
  3124. // (13,2): error CS0246: The type or namespace name '@X' could not be found (are you missing a using directive or an assembly reference?)
  3125. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@X").WithArguments("@X"));
  3126. }
  3127. [Fact]
  3128. public void AttributeOpenTypeInAttribute()
  3129. {
  3130. string source = @"
  3131. using System;
  3132. using System.Collections.Generic;
  3133. [AttributeUsage(AttributeTargets.All)]
  3134. public class XAttribute : Attribute
  3135. {
  3136. public XAttribute(Type t) { }
  3137. }
  3138. class G<T>
  3139. {
  3140. [X(typeof(T))] T t1; // Error: open type in attribute
  3141. [X(typeof(List<T>))] T t2; // Error: open type in attribute
  3142. }
  3143. class X
  3144. {
  3145. [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type
  3146. [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type
  3147. }
  3148. ";
  3149. var compilation = CreateCompilationWithMscorlib(source);
  3150. compilation.VerifyDiagnostics(
  3151. // (13,8): error CS0416: 'T': an attribute argument cannot use type parameters
  3152. // [X(typeof(T))] T t1; // Error: open type in attribute
  3153. Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(T)").WithArguments("T"),
  3154. // (14,8): error CS0416: 'System.Collections.Generic.List<T>': an attribute argument cannot use type parameters
  3155. // [X(typeof(List<T>))] T t2; // Error: open type in attribute
  3156. Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(List<T>)").WithArguments("System.Collections.Generic.List<T>"),
  3157. // (13,22): warning CS0169: The field 'G<T>.t1' is never used
  3158. // [X(typeof(T))] T t1; // Error: open type in attribute
  3159. Diagnostic(ErrorCode.WRN_UnreferencedField, "t1").WithArguments("G<T>.t1"),
  3160. // (14,28): warning CS0169: The field 'G<T>.t2' is never used
  3161. // [X(typeof(List<T>))] T t2; // Error: open type in attribute
  3162. Diagnostic(ErrorCode.WRN_UnreferencedField, "t2").WithArguments("G<T>.t2"),
  3163. // (19,32): warning CS0169: The field 'X.x' is never used
  3164. // [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type
  3165. Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("X.x"),
  3166. // (20,29): warning CS0169: The field 'X.y' is never used
  3167. // [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type
  3168. Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("X.y")
  3169. );
  3170. }
  3171. [WorkItem(540924, "DevDiv")]
  3172. [Fact]
  3173. public void AttributeEnumsAsAttributeParameters()
  3174. {
  3175. string source = @"
  3176. using System;
  3177. class EClass
  3178. {
  3179. public enum EEK { a, b, c, d };
  3180. }
  3181. [AttributeUsage(AttributeTargets.Class)]
  3182. internal class HelpAttribute : Attribute
  3183. {
  3184. public HelpAttribute(EClass.EEK[] b1)
  3185. {
  3186. }
  3187. }
  3188. [HelpAttribute(new EClass.EEK[2] { EClass.EEK.b, EClass.EEK.c })]
  3189. public class MainClass
  3190. {
  3191. public static void Main()
  3192. {
  3193. }
  3194. }
  3195. ";
  3196. var compilation = CreateCompilationWithMscorlib(source);
  3197. compilation.VerifyDiagnostics();
  3198. }
  3199. [WorkItem(768798, "DevDiv")]
  3200. [Fact(Skip = "768798")]
  3201. public void AttributeInvalidTargetSpecifier()
  3202. {
  3203. string source = @"
  3204. using System;
  3205. // Below attribute specification generates a warning regarding invalid target specifier,
  3206. // We skip binding the attribute with invalid target specifier,
  3207. // no error generated for invalid use of AttributeUsage on non attribute class.
  3208. [method: AttributeUsage(AttributeTargets.All)]
  3209. class X
  3210. {
  3211. public static void Main() {}
  3212. }
  3213. ";
  3214. var compilation = CreateCompilationWithMscorlib(source);
  3215. compilation.VerifyDiagnostics(
  3216. // (6,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored.
  3217. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type"));
  3218. }
  3219. [WorkItem(768798, "DevDiv")]
  3220. [Fact(Skip = "768798")]
  3221. public void AttributeInvalidTargetSpecifierOnInvalidAttribute()
  3222. {
  3223. string source = @"
  3224. [method: OopsForgotToBindThis(Haha)]
  3225. class X
  3226. {
  3227. public static void Main() {}
  3228. }
  3229. ";
  3230. var compilation = CreateCompilationWithMscorlib(source);
  3231. compilation.VerifyDiagnostics(/*CS0657, CS0246*/);
  3232. }
  3233. [Fact]
  3234. public void AttributeUsageMultipleErrors()
  3235. {
  3236. string source =
  3237. @"using System;
  3238. class A
  3239. {
  3240. [AttributeUsage(AttributeTargets.Method)]
  3241. void M1() { }
  3242. [AttributeUsage(0)]
  3243. void M2() { }
  3244. }
  3245. [AttributeUsage(0)]
  3246. class B
  3247. {
  3248. }";
  3249. var compilation = CreateCompilationWithMscorlib(source);
  3250. compilation.VerifyDiagnostics(
  3251. // (4,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations.
  3252. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(4, 6),
  3253. // (6,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations.
  3254. // [AttributeUsage(0)]
  3255. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(6, 6),
  3256. // (9,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute
  3257. Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(9, 2));
  3258. }
  3259. [Fact]
  3260. public void CS0643ERR_DuplicateNamedAttributeArgument02()
  3261. {
  3262. string source = @"
  3263. using System;
  3264. [AttributeUsage(AllowMultiple = true, AllowMultiple = false)]
  3265. class MyAtt : Attribute
  3266. { }
  3267. [MyAtt]
  3268. public class Test
  3269. {
  3270. public static void Main()
  3271. {
  3272. }
  3273. }
  3274. ";
  3275. var compilation = CreateCompilationWithMscorlib(source);
  3276. compilation.VerifyDiagnostics(
  3277. // (3,39): error CS0643: 'AllowMultiple' duplicate named attribute argument
  3278. Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(3, 39),
  3279. // (3,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'validOn' of 'System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)'
  3280. Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(3, 2));
  3281. }
  3282. [WorkItem(541059, "DevDiv")]
  3283. [Fact]
  3284. public void AttributeUsageIsNull()
  3285. {
  3286. string source = @"
  3287. using System;
  3288. [AttributeUsage(null)]
  3289. public class Att1 : Attribute { }
  3290. public class Foo
  3291. {
  3292. public static void Main()
  3293. {
  3294. }
  3295. }
  3296. ";
  3297. var compilation = CreateCompilationWithMscorlib(source);
  3298. compilation.VerifyDiagnostics(
  3299. Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets"));
  3300. }
  3301. [WorkItem(541072, "DevDiv")]
  3302. [Fact]
  3303. public void AttributeContainsGeneric()
  3304. {
  3305. string source = @"
  3306. [Foo<int>]
  3307. class G
  3308. {
  3309. }
  3310. class Foo<T>
  3311. {
  3312. }
  3313. ";
  3314. var compilation = CreateCompilationWithMscorlib(source);
  3315. compilation.VerifyDiagnostics(
  3316. // (2,2): error CS0404: Cannot apply attribute class 'Foo<T>' because it is generic
  3317. // [Foo<int>]
  3318. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Foo<int>").WithArguments("Foo<T>").WithLocation(2, 2));
  3319. }
  3320. /// <summary>
  3321. /// Bug 7620: System.Nullreference Exception throws while the value of parameter AttributeUsage Is Null
  3322. /// </summary>
  3323. [Fact]
  3324. public void CS1502ERR_NullAttributeUsageArgument()
  3325. {
  3326. string source = @"
  3327. using System;
  3328. [AttributeUsage(null)]
  3329. public class Attr : Attribute { }
  3330. public class Foo
  3331. {
  3332. public static void Main()
  3333. {
  3334. }
  3335. }
  3336. ";
  3337. var compilation = CreateCompilationWithMscorlib(source);
  3338. compilation.VerifyDiagnostics(
  3339. // (4,17): error CS1503: Argument 1: cannot convert from '<null>' to 'System.AttributeTargets'
  3340. // [AttributeUsage(null)]
  3341. Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets"));
  3342. }
  3343. /// <summary>
  3344. /// Bug 7632: Debug.Assert() Failure while Attribute Contains Generic
  3345. /// </summary>
  3346. [Fact]
  3347. public void CS0404ERR_GenericAttributeError()
  3348. {
  3349. string source = @"
  3350. [Foo<int>]
  3351. class G
  3352. {
  3353. }
  3354. class Foo<T>
  3355. {
  3356. }
  3357. ";
  3358. var compilation = CreateCompilationWithMscorlib(source);
  3359. compilation.VerifyDiagnostics(
  3360. // (2,2): error CS0404: Cannot apply attribute class 'Foo<T>' because it is generic
  3361. // [Foo<int>]
  3362. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Foo<int>").WithArguments("Foo<T>").WithLocation(2, 2));
  3363. }
  3364. [WorkItem(541423, "DevDiv")]
  3365. [Fact]
  3366. public void ErrorsInMultipleSyntaxTrees()
  3367. {
  3368. var source1 =
  3369. @"using System;
  3370. [module: A]
  3371. [AttributeUsage(AttributeTargets.Class)]
  3372. class A : Attribute
  3373. {
  3374. }
  3375. [AttributeUsage(AttributeTargets.Method)]
  3376. class B : Attribute
  3377. {
  3378. }";
  3379. var source2 =
  3380. @"[module: B]";
  3381. var compilation = CreateCompilationWithMscorlib(new[] { source1, source2 });
  3382. compilation.VerifyDiagnostics(
  3383. // (2,10): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations.
  3384. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(2, 10),
  3385. // (1,10): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations.
  3386. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 10));
  3387. }
  3388. [WorkItem(542533, "DevDiv")]
  3389. [Fact]
  3390. public void ErrorsInMultipleSyntaxTrees_TypeParam()
  3391. {
  3392. var source1 =
  3393. @"using System;
  3394. [AttributeUsage(AttributeTargets.Class)]
  3395. class A : Attribute
  3396. {
  3397. }
  3398. [AttributeUsage(AttributeTargets.Method)]
  3399. class B : Attribute
  3400. {
  3401. }
  3402. class Gen<[A] T> {}
  3403. ";
  3404. var source2 =
  3405. @"class Gen2<[B] T> {}";
  3406. var compilation = CreateCompilationWithMscorlib(new[] { source1, source2 });
  3407. compilation.VerifyDiagnostics(
  3408. // (11,12): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations.
  3409. // class Gen<[A] T> {}
  3410. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(11, 12),
  3411. // (1,13): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations.
  3412. // class Gen2<[B] T> {}
  3413. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 13));
  3414. }
  3415. [WorkItem(541423, "DevDiv")]
  3416. [Fact]
  3417. public void ErrorsInMultiplePartialDeclarations()
  3418. {
  3419. var source =
  3420. @"using System;
  3421. [AttributeUsage(AttributeTargets.Struct)]
  3422. class A : Attribute
  3423. {
  3424. }
  3425. [AttributeUsage(AttributeTargets.Method)]
  3426. class B : Attribute
  3427. {
  3428. }
  3429. [A]
  3430. partial class C
  3431. {
  3432. }
  3433. [B]
  3434. partial class C
  3435. {
  3436. }";
  3437. var compilation = CreateCompilationWithMscorlib(source);
  3438. compilation.VerifyDiagnostics(
  3439. // (10,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations.
  3440. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(10, 2),
  3441. // (14,2): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations.
  3442. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 2));
  3443. }
  3444. [WorkItem(542533, "DevDiv")]
  3445. [Fact]
  3446. public void ErrorsInMultiplePartialDeclarations_TypeParam()
  3447. {
  3448. var source =
  3449. @"using System;
  3450. [AttributeUsage(AttributeTargets.Struct)]
  3451. class A : Attribute
  3452. {
  3453. }
  3454. [AttributeUsage(AttributeTargets.Method)]
  3455. class B : Attribute
  3456. {
  3457. }
  3458. partial class Gen<[A] T>
  3459. {
  3460. }
  3461. partial class Gen<[B] T>
  3462. {
  3463. }";
  3464. var compilation = CreateCompilationWithMscorlib(source);
  3465. compilation.VerifyDiagnostics(
  3466. // (11,20): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations.
  3467. // partial class Gen<[A] T>
  3468. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(11, 20),
  3469. // (14,20): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations.
  3470. // partial class Gen<[B] T>
  3471. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 20));
  3472. }
  3473. [WorkItem(541505, "DevDiv")]
  3474. [Fact]
  3475. public void AttributeArgumentError_CS0120()
  3476. {
  3477. var source =
  3478. @"using System;
  3479. class A : Attribute
  3480. {
  3481. public A(ProtectionLevel p){}
  3482. }
  3483. enum ProtectionLevel
  3484. {
  3485. Privacy = 0
  3486. }
  3487. class F
  3488. {
  3489. int ProtectionLevel;
  3490. [A(ProtectionLevel.Privacy)]
  3491. public int test;
  3492. }
  3493. ";
  3494. var compilation = CreateCompilationWithMscorlib(source);
  3495. compilation.VerifyDiagnostics(
  3496. // (16,6): error CS0120: An object reference is required for the non-static field, method, or property 'F.ProtectionLevel'
  3497. // [A(ProtectionLevel.Privacy)]
  3498. Diagnostic(ErrorCode.ERR_ObjectRequired, "ProtectionLevel").WithArguments("F.ProtectionLevel"),
  3499. // (14,7): warning CS0169: The field 'F.ProtectionLevel' is never used
  3500. // int ProtectionLevel;
  3501. Diagnostic(ErrorCode.WRN_UnreferencedField, "ProtectionLevel").WithArguments("F.ProtectionLevel"),
  3502. // (17,14): warning CS0649: Field 'F.test' is never assigned to, and will always have its default value 0
  3503. // public int test;
  3504. Diagnostic(ErrorCode.WRN_UnassignedInternalField, "test").WithArguments("F.test", "0")
  3505. );
  3506. }
  3507. [Fact, WorkItem(541427, "DevDiv")]
  3508. public void AttributeTargetsString()
  3509. {
  3510. var source = @"
  3511. using System;
  3512. [AttributeUsage(AttributeTargets.All & ~AttributeTargets.Class)] class A : Attribute { }
  3513. [A] class C { }
  3514. ";
  3515. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  3516. // (3,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter' declarations.
  3517. // [A] class C { }
  3518. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter")
  3519. );
  3520. }
  3521. [Fact]
  3522. public void AttributeTargetsAssemblyModule()
  3523. {
  3524. var source = @"
  3525. using System;
  3526. [module: Attr()]
  3527. [AttributeUsage(AttributeTargets.Assembly)]
  3528. class Attr: Attribute { public Attr(){} }";
  3529. var compilation = CreateCompilationWithMscorlib(source);
  3530. compilation.VerifyDiagnostics(
  3531. // (3,10): error CS0592: Attribute 'Attr' is not valid on this declaration type. It is only valid on 'assembly' declarations.
  3532. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Attr").WithArguments("Attr", "assembly"));
  3533. }
  3534. [WorkItem(541259, "DevDiv")]
  3535. [Fact]
  3536. public void CS0182_NonConstantArrayCreationAttributeArgument()
  3537. {
  3538. var source =
  3539. @"using System;
  3540. [A(new int[1] {Program.f})] // error
  3541. [A(new int[1])] // error
  3542. [A(new int[1,1])] // error
  3543. [A(new int[1 - 1])] // OK create an empty array
  3544. [A(new A[0])] // error
  3545. class Program
  3546. {
  3547. static public int f = 10;
  3548. public static void Main()
  3549. {
  3550. typeof(Program).GetCustomAttributes(false);
  3551. }
  3552. }
  3553. [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  3554. class A : Attribute
  3555. {
  3556. public A(object x) { }
  3557. }
  3558. ";
  3559. var compilation = CreateCompilationWithMscorlib(source);
  3560. compilation.VerifyDiagnostics(
  3561. // (3,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  3562. // [A(new int[1] {Program.f})]
  3563. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Program.f"),
  3564. // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  3565. // [A(new int[1])]
  3566. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1]"),
  3567. // (5,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  3568. // [A(new int[1,1])]
  3569. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1,1]"),
  3570. // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  3571. // [A(new A[0])]
  3572. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new A[0]"));
  3573. }
  3574. [WorkItem(541753, "DevDiv")]
  3575. [Fact]
  3576. public void CS0182_NestedArrays()
  3577. {
  3578. var source = @"
  3579. using System;
  3580. [A(new int[][] { new int[] { 1 } })]
  3581. class Program
  3582. {
  3583. static void Main()
  3584. {
  3585. typeof(Program).GetCustomAttributes(false);
  3586. }
  3587. }
  3588. class A : Attribute
  3589. {
  3590. public A(object x) { }
  3591. }
  3592. ";
  3593. var compilation = CreateCompilationWithMscorlib(source);
  3594. compilation.VerifyDiagnostics(
  3595. // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  3596. // [A(new int[][] { new int[] { 1 } })]
  3597. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[][] { new int[] { 1 } }").WithLocation(4, 4));
  3598. }
  3599. [WorkItem(541849, "DevDiv")]
  3600. [Fact]
  3601. public void CS0182_MultidimensionalArrays()
  3602. {
  3603. var source =
  3604. @"using System;
  3605. class MyAttribute : Attribute
  3606. {
  3607. public MyAttribute(params int[][,] x) { }
  3608. }
  3609. [My]
  3610. class Program
  3611. {
  3612. static void Main()
  3613. {
  3614. typeof(Program).GetCustomAttributes(false);
  3615. }
  3616. }
  3617. ";
  3618. var compilation = CreateCompilationWithMscorlib(source);
  3619. compilation.VerifyDiagnostics(
  3620. // (8,2): error CS0181: Attribute constructor parameter 'x' has type 'int[][*,*]', which is not a valid attribute parameter type
  3621. // [My]
  3622. Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("x", "int[][*,*]").WithLocation(8, 2));
  3623. }
  3624. [WorkItem(541858, "DevDiv")]
  3625. [Fact]
  3626. public void AttributeDefaultValueArgument()
  3627. {
  3628. var source =
  3629. @"using System;
  3630. namespace AttributeTest
  3631. {
  3632. [A(3, X = 6)]
  3633. public class A : Attribute
  3634. {
  3635. public int X;
  3636. public A(int x, int y = 4, object a = default(A)) { }
  3637. static void Main()
  3638. {
  3639. typeof(A).GetCustomAttributes(false);
  3640. }
  3641. }
  3642. }
  3643. ";
  3644. var compilation = CompileAndVerify(source, expectedOutput: "");
  3645. }
  3646. [WorkItem(541858, "DevDiv")]
  3647. [Fact]
  3648. public void CS0416_GenericAttributeDefaultValueArgument()
  3649. {
  3650. var source =
  3651. @"using System;
  3652. public class A : Attribute
  3653. {
  3654. public object X;
  3655. static void Main()
  3656. {
  3657. typeof(C<int>.E).GetCustomAttributes(false);
  3658. }
  3659. }
  3660. public class C<T>
  3661. {
  3662. [A(X = default(E))]
  3663. public enum E { }
  3664. [A(X = typeof(E2))]
  3665. public enum E2 { }
  3666. }
  3667. ";
  3668. var compilation = CreateCompilationWithMscorlib(source);
  3669. compilation.VerifyDiagnostics(
  3670. // (14,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  3671. // [A(X = default(E))]
  3672. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(14, 12),
  3673. // (17,12): error CS0416: 'C<T>.E2': an attribute argument cannot use type parameters
  3674. // [A(X = typeof(E2))]
  3675. Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(E2)").WithArguments("C<T>.E2").WithLocation(17, 12));
  3676. }
  3677. [WorkItem(541615, "DevDiv")]
  3678. [Fact]
  3679. public void CS0246_VarAttributeIdentifier()
  3680. {
  3681. var source = @"
  3682. [var()]
  3683. class Program
  3684. {
  3685. public static void Main() {}
  3686. }
  3687. ";
  3688. var compilation = CreateCompilationWithMscorlib(source);
  3689. compilation.VerifyDiagnostics(
  3690. // (2,2): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)
  3691. // [var()]
  3692. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("var").WithLocation(2, 2));
  3693. }
  3694. [Fact]
  3695. public void TestAttributesWithInvalidArgumentsOrder()
  3696. {
  3697. string source = @"
  3698. using System;
  3699. namespace AttributeTest
  3700. {
  3701. [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  3702. [A(3, z: 5, X = 6, y: 1)]
  3703. [A(3, z: 5, 1)]
  3704. [A(3, 1, X = 6, z: 5)]
  3705. [A(X = 6, 0)]
  3706. [A(X = 6, x: 0)]
  3707. public class A : Attribute
  3708. {
  3709. public int X;
  3710. public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); }
  3711. static void Main()
  3712. {
  3713. typeof(A).GetCustomAttributes(false);
  3714. }
  3715. }
  3716. public class B
  3717. {
  3718. }
  3719. }
  3720. ";
  3721. var compilation = CreateCompilationWithMscorlib(source);
  3722. compilation.VerifyDiagnostics(
  3723. // (7,27): error CS1016: Named attribute argument expected
  3724. // [A(3, z: 5, X = 6, y: 1)]
  3725. Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "1").WithLocation(7, 27),
  3726. // (9,24): error CS1016: Named attribute argument expected
  3727. // [A(3, 1, X = 6, z: 5)]
  3728. Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "5").WithLocation(9, 24),
  3729. // (10,15): error CS1016: Named attribute argument expected
  3730. // [A(X = 6, 0)]
  3731. Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(10, 15),
  3732. // (11,18): error CS1016: Named attribute argument expected
  3733. // [A(X = 6, x: 0)]
  3734. Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(11, 18),
  3735. // (8,17): error CS1738: Named argument specifications must appear after all fixed arguments have been specified
  3736. // [A(3, z: 5, 1)]
  3737. Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "1").WithLocation(8, 17));
  3738. }
  3739. [WorkItem(541877, "DevDiv")]
  3740. [Fact]
  3741. public void Bug8772_TestDelegateAttributeNameBinding()
  3742. {
  3743. string source = @"
  3744. using System;
  3745. class A : Attribute
  3746. {
  3747. public A(int x) { Console.WriteLine(x); }
  3748. }
  3749. class C
  3750. {
  3751. [A(Invoke)]
  3752. delegate void F1();
  3753. delegate T F2<[A(Invoke)]T> ();
  3754. const int Invoke = 1;
  3755. static void Main()
  3756. {
  3757. }
  3758. }
  3759. ";
  3760. var compilation = CreateCompilationWithMscorlib(source);
  3761. compilation.VerifyDiagnostics(
  3762. // (11,8): error CS1503: Argument 1: cannot convert from 'method group' to 'int'
  3763. // [A(Invoke)]
  3764. Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(11, 8),
  3765. // (14,22): error CS1503: Argument 1: cannot convert from 'method group' to 'int'
  3766. // delegate T F2<[A(Invoke)]T> ();
  3767. Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(14, 22));
  3768. }
  3769. [Fact]
  3770. public void AmbiguousAttributeErrors_01()
  3771. {
  3772. string source = @"
  3773. namespace ValidWithSuffix
  3774. {
  3775. public class DescriptionAttribute : System.Attribute
  3776. {
  3777. public DescriptionAttribute(string name) { }
  3778. }
  3779. }
  3780. namespace ValidWithoutSuffix
  3781. {
  3782. public class Description : System.Attribute
  3783. {
  3784. public Description(string name) { }
  3785. }
  3786. }
  3787. namespace TestNamespace_01
  3788. {
  3789. using ValidWithSuffix;
  3790. using ValidWithoutSuffix;
  3791. [Description(null)]
  3792. public class Test { }
  3793. [DescriptionAttribute(null)]
  3794. public class Test2 { }
  3795. }
  3796. ";
  3797. var compilation = CreateCompilationWithMscorlib(source);
  3798. compilation.VerifyDiagnostics(
  3799. // (23,6): error CS1614: 'Description' is ambiguous between 'ValidWithoutSuffix.Description' and 'ValidWithSuffix.DescriptionAttribute'; use either '@Description' or 'DescriptionAttribute'
  3800. // [Description(null)]
  3801. Diagnostic(ErrorCode.ERR_AmbigousAttribute, "Description").WithArguments("Description", "ValidWithoutSuffix.Description", "ValidWithSuffix.DescriptionAttribute"));
  3802. }
  3803. [Fact]
  3804. public void AmbiguousAttributeErrors_02()
  3805. {
  3806. string source = @"
  3807. namespace ValidWithSuffix
  3808. {
  3809. public class DescriptionAttribute : System.Attribute
  3810. {
  3811. public DescriptionAttribute(string name) { }
  3812. }
  3813. }
  3814. namespace ValidWithSuffix_And_ValidWithoutSuffix
  3815. {
  3816. public class DescriptionAttribute : System.Attribute
  3817. {
  3818. public DescriptionAttribute(string name) { }
  3819. }
  3820. public class Description : System.Attribute
  3821. {
  3822. public Description(string name) { }
  3823. }
  3824. }
  3825. namespace TestNamespace_02
  3826. {
  3827. using ValidWithSuffix;
  3828. using ValidWithSuffix_And_ValidWithoutSuffix;
  3829. [Description(null)]
  3830. public class Test { }
  3831. [DescriptionAttribute(null)]
  3832. public class Test2 { }
  3833. }
  3834. ";
  3835. var compilation = CreateCompilationWithMscorlib(source);
  3836. compilation.VerifyDiagnostics(
  3837. // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute'
  3838. // [DescriptionAttribute(null)]
  3839. Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute"));
  3840. }
  3841. [Fact]
  3842. public void AmbiguousAttributeErrors_03()
  3843. {
  3844. string source = @"
  3845. namespace ValidWithoutSuffix
  3846. {
  3847. public class Description : System.Attribute
  3848. {
  3849. public Description(string name) { }
  3850. }
  3851. }
  3852. namespace ValidWithSuffix_And_ValidWithoutSuffix
  3853. {
  3854. public class DescriptionAttribute : System.Attribute
  3855. {
  3856. public DescriptionAttribute(string name) { }
  3857. }
  3858. public class Description : System.Attribute
  3859. {
  3860. public Description(string name) { }
  3861. }
  3862. }
  3863. namespace TestNamespace_03
  3864. {
  3865. using ValidWithoutSuffix;
  3866. using ValidWithSuffix_And_ValidWithoutSuffix;
  3867. [Description(null)]
  3868. public class Test { }
  3869. [DescriptionAttribute(null)]
  3870. public class Test2 { }
  3871. }
  3872. ";
  3873. var compilation = CreateCompilationWithMscorlib(source);
  3874. compilation.VerifyDiagnostics();
  3875. }
  3876. [Fact]
  3877. public void AmbiguousAttributeErrors_04()
  3878. {
  3879. string source = @"
  3880. namespace ValidWithSuffix
  3881. {
  3882. public class DescriptionAttribute : System.Attribute
  3883. {
  3884. public DescriptionAttribute(string name) { }
  3885. }
  3886. }
  3887. namespace ValidWithoutSuffix
  3888. {
  3889. public class Description : System.Attribute
  3890. {
  3891. public Description(string name) { }
  3892. }
  3893. }
  3894. namespace ValidWithSuffix_And_ValidWithoutSuffix
  3895. {
  3896. public class DescriptionAttribute : System.Attribute
  3897. {
  3898. public DescriptionAttribute(string name) { }
  3899. }
  3900. public class Description : System.Attribute
  3901. {
  3902. public Description(string name) { }
  3903. }
  3904. }
  3905. namespace TestNamespace_04
  3906. {
  3907. using ValidWithSuffix;
  3908. using ValidWithoutSuffix;
  3909. using ValidWithSuffix_And_ValidWithoutSuffix;
  3910. [Description(null)]
  3911. public class Test { }
  3912. [DescriptionAttribute(null)]
  3913. public class Test2 { }
  3914. }
  3915. ";
  3916. var compilation = CreateCompilationWithMscorlib(source);
  3917. compilation.VerifyDiagnostics(
  3918. // (36,6): error CS0104: 'Description' is an ambiguous reference between 'ValidWithSuffix_And_ValidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description'
  3919. // [Description(null)]
  3920. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "ValidWithSuffix_And_ValidWithoutSuffix.Description", "ValidWithoutSuffix.Description"),
  3921. // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute'
  3922. // [DescriptionAttribute(null)]
  3923. Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute"));
  3924. }
  3925. [Fact]
  3926. public void AmbiguousAttributeErrors_05()
  3927. {
  3928. string source = @"
  3929. namespace InvalidWithSuffix
  3930. {
  3931. public class DescriptionAttribute
  3932. {
  3933. public DescriptionAttribute(string name) { }
  3934. }
  3935. }
  3936. namespace InvalidWithoutSuffix
  3937. {
  3938. public class Description
  3939. {
  3940. public Description(string name) { }
  3941. }
  3942. }
  3943. namespace TestNamespace_05
  3944. {
  3945. using InvalidWithSuffix;
  3946. using InvalidWithoutSuffix;
  3947. [Description(null)]
  3948. public class Test { }
  3949. [DescriptionAttribute(null)]
  3950. public class Test2 { }
  3951. }
  3952. ";
  3953. var compilation = CreateCompilationWithMscorlib(source);
  3954. compilation.VerifyDiagnostics(
  3955. // (23,6): error CS0616: 'InvalidWithoutSuffix.Description' is not an attribute class
  3956. // [Description(null)]
  3957. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Description").WithArguments("InvalidWithoutSuffix.Description"),
  3958. // (26,6): error CS0616: 'InvalidWithSuffix.DescriptionAttribute' is not an attribute class
  3959. // [DescriptionAttribute(null)]
  3960. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix.DescriptionAttribute"));
  3961. }
  3962. [Fact]
  3963. public void AmbiguousAttributeErrors_06()
  3964. {
  3965. string source = @"
  3966. namespace InvalidWithSuffix
  3967. {
  3968. public class DescriptionAttribute
  3969. {
  3970. public DescriptionAttribute(string name) { }
  3971. }
  3972. }
  3973. namespace InvalidWithSuffix_And_InvalidWithoutSuffix
  3974. {
  3975. public class DescriptionAttribute
  3976. {
  3977. public DescriptionAttribute(string name) { }
  3978. }
  3979. public class Description
  3980. {
  3981. public Description(string name) { }
  3982. }
  3983. }
  3984. namespace TestNamespace_06
  3985. {
  3986. using InvalidWithSuffix;
  3987. using InvalidWithSuffix_And_InvalidWithoutSuffix;
  3988. [Description(null)]
  3989. public class Test { }
  3990. [DescriptionAttribute(null)]
  3991. public class Test2 { }
  3992. }
  3993. ";
  3994. var compilation = CreateCompilationWithMscorlib(source);
  3995. compilation.VerifyDiagnostics(
  3996. // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute'
  3997. // [Description(null)]
  3998. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"),
  3999. // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute'
  4000. // [DescriptionAttribute(null)]
  4001. Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"));
  4002. }
  4003. [Fact]
  4004. public void AmbiguousAttributeErrors_07()
  4005. {
  4006. string source = @"
  4007. namespace InvalidWithoutSuffix
  4008. {
  4009. public class Description
  4010. {
  4011. public Description(string name) { }
  4012. }
  4013. }
  4014. namespace InvalidWithSuffix_And_InvalidWithoutSuffix
  4015. {
  4016. public class DescriptionAttribute
  4017. {
  4018. public DescriptionAttribute(string name) { }
  4019. }
  4020. public class Description
  4021. {
  4022. public Description(string name) { }
  4023. }
  4024. }
  4025. namespace TestNamespace_07
  4026. {
  4027. using InvalidWithoutSuffix;
  4028. using InvalidWithSuffix_And_InvalidWithoutSuffix;
  4029. [Description(null)]
  4030. public class Test { }
  4031. [DescriptionAttribute(null)]
  4032. public class Test2 { }
  4033. }
  4034. ";
  4035. var compilation = CreateCompilationWithMscorlib(source);
  4036. compilation.VerifyDiagnostics(
  4037. // (30,6): error CS0616: 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' is not an attribute class
  4038. // [DescriptionAttribute(null)]
  4039. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"),
  4040. // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description'
  4041. // [Description(null)]
  4042. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description"));
  4043. }
  4044. [Fact]
  4045. public void AmbiguousAttributeErrors_08()
  4046. {
  4047. string source = @"
  4048. namespace InvalidWithSuffix
  4049. {
  4050. public class DescriptionAttribute
  4051. {
  4052. public DescriptionAttribute(string name) { }
  4053. }
  4054. }
  4055. namespace InvalidWithoutSuffix
  4056. {
  4057. public class Description
  4058. {
  4059. public Description(string name) { }
  4060. }
  4061. }
  4062. namespace InvalidWithSuffix_And_InvalidWithoutSuffix
  4063. {
  4064. public class DescriptionAttribute
  4065. {
  4066. public DescriptionAttribute(string name) { }
  4067. }
  4068. public class Description
  4069. {
  4070. public Description(string name) { }
  4071. }
  4072. }
  4073. namespace TestNamespace_08
  4074. {
  4075. using InvalidWithSuffix;
  4076. using InvalidWithoutSuffix;
  4077. using InvalidWithSuffix_And_InvalidWithoutSuffix;
  4078. [Description(null)]
  4079. public class Test { }
  4080. [DescriptionAttribute(null)]
  4081. public class Test2 { }
  4082. }
  4083. ";
  4084. var compilation = CreateCompilationWithMscorlib(source);
  4085. compilation.VerifyDiagnostics(
  4086. // (36,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description'
  4087. // [Description(null)]
  4088. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description"),
  4089. // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute'
  4090. // [DescriptionAttribute(null)]
  4091. Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"));
  4092. }
  4093. [Fact]
  4094. public void AmbiguousAttributeErrors_09()
  4095. {
  4096. string source = @"
  4097. namespace InvalidWithoutSuffix_But_ValidWithSuffix
  4098. {
  4099. public class DescriptionAttribute : System.Attribute
  4100. {
  4101. public DescriptionAttribute(string name) { }
  4102. }
  4103. public class Description
  4104. {
  4105. public Description(string name) { }
  4106. }
  4107. }
  4108. namespace InvalidWithSuffix_But_ValidWithoutSuffix
  4109. {
  4110. public class DescriptionAttribute
  4111. {
  4112. public DescriptionAttribute(string name) { }
  4113. }
  4114. public class Description : System.Attribute
  4115. {
  4116. public Description(string name) { }
  4117. }
  4118. }
  4119. namespace TestNamespace_09
  4120. {
  4121. using InvalidWithoutSuffix_But_ValidWithSuffix;
  4122. using InvalidWithSuffix_But_ValidWithoutSuffix;
  4123. [Description(null)]
  4124. public class Test { public static void Main() {} }
  4125. [DescriptionAttribute(null)]
  4126. public class Test2 { }
  4127. }
  4128. ";
  4129. var compilation = CreateCompilationWithMscorlib(source);
  4130. compilation.VerifyDiagnostics(
  4131. // (31,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.Description' and 'InvalidWithoutSuffix_But_ValidWithSuffix.Description'
  4132. // [Description(null)]
  4133. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_But_ValidWithoutSuffix.Description", "InvalidWithoutSuffix_But_ValidWithSuffix.Description"),
  4134. // (34,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute'
  4135. // [DescriptionAttribute(null)]
  4136. Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute"));
  4137. }
  4138. [Fact]
  4139. public void AmbiguousAttributeErrors_10()
  4140. {
  4141. string source = @"
  4142. namespace ValidWithoutSuffix
  4143. {
  4144. public class Description : System.Attribute
  4145. {
  4146. public Description(string name) { }
  4147. }
  4148. }
  4149. namespace InvalidWithoutSuffix
  4150. {
  4151. public class Description
  4152. {
  4153. public Description(string name) { }
  4154. }
  4155. }
  4156. namespace TestNamespace_10
  4157. {
  4158. using ValidWithoutSuffix;
  4159. using InvalidWithoutSuffix;
  4160. [Description(null)]
  4161. public class Test { public static void Main() {} }
  4162. }
  4163. ";
  4164. var compilation = CreateCompilationWithMscorlib(source);
  4165. compilation.VerifyDiagnostics(
  4166. // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description'
  4167. // [Description(null)]
  4168. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithoutSuffix.Description", "ValidWithoutSuffix.Description"));
  4169. }
  4170. [Fact]
  4171. public void AmbiguousAttributeErrors_11()
  4172. {
  4173. string source = @"
  4174. namespace ValidWithSuffix
  4175. {
  4176. public class DescriptionAttribute : System.Attribute
  4177. {
  4178. public DescriptionAttribute(string name) { }
  4179. }
  4180. }
  4181. namespace InvalidWithSuffix
  4182. {
  4183. public class DescriptionAttribute
  4184. {
  4185. public DescriptionAttribute(string name) { }
  4186. }
  4187. }
  4188. namespace TestNamespace_11
  4189. {
  4190. using ValidWithSuffix;
  4191. using InvalidWithSuffix;
  4192. [Description(null)]
  4193. public class Test { public static void Main() {} }
  4194. [DescriptionAttribute(null)]
  4195. public class Test2 { }
  4196. }
  4197. ";
  4198. var compilation = CreateCompilationWithMscorlib(source);
  4199. compilation.VerifyDiagnostics(
  4200. // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute'
  4201. // [Description(null)]
  4202. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute"),
  4203. // (26,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute'
  4204. // [DescriptionAttribute(null)]
  4205. Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute"));
  4206. }
  4207. [Fact]
  4208. public void AmbiguousAttributeErrors_12()
  4209. {
  4210. string source = @"
  4211. namespace InvalidWithSuffix
  4212. {
  4213. public class DescriptionAttribute
  4214. {
  4215. public DescriptionAttribute(string name) { }
  4216. }
  4217. }
  4218. namespace InvalidWithoutSuffix_But_ValidWithSuffix
  4219. {
  4220. public class DescriptionAttribute : System.Attribute
  4221. {
  4222. public DescriptionAttribute(string name) { }
  4223. }
  4224. public class Description
  4225. {
  4226. public Description(string name) { }
  4227. }
  4228. }
  4229. namespace TestNamespace_12
  4230. {
  4231. using InvalidWithoutSuffix_But_ValidWithSuffix;
  4232. using InvalidWithSuffix;
  4233. [Description(null)]
  4234. public class Test { public static void Main() {} }
  4235. [DescriptionAttribute(null)]
  4236. public class Test2 { }
  4237. }
  4238. ";
  4239. var compilation = CreateCompilationWithMscorlib(source);
  4240. compilation.VerifyDiagnostics(
  4241. // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute'
  4242. // [DescriptionAttribute(null)]
  4243. Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute"),
  4244. // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute'
  4245. // [Description(null)]
  4246. Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute"));
  4247. }
  4248. [Fact]
  4249. public void AliasAttributeName()
  4250. {
  4251. var source =
  4252. @"using A = A1;
  4253. using AAttribute = A2;
  4254. class A1 : System.Attribute { }
  4255. class A2 : System.Attribute { }
  4256. [A]class C { }";
  4257. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4258. // (5,2): error CS1614: 'A' is ambiguous between 'A2' and 'A1'; use either '@A' or 'AAttribute'
  4259. Diagnostic(ErrorCode.ERR_AmbigousAttribute, "A").WithArguments("A", "A1", "A2").WithLocation(5, 2));
  4260. }
  4261. [WorkItem(542279, "DevDiv")]
  4262. [Fact]
  4263. public void MethodSignatureAttributes()
  4264. {
  4265. var text =
  4266. @"class A : System.Attribute
  4267. {
  4268. public A(object o) { }
  4269. }
  4270. class B { }
  4271. class C
  4272. {
  4273. [return: A(new B())]
  4274. static object F(
  4275. [A(new B())] object x,
  4276. [param: A(new B())] object y)
  4277. {
  4278. return null;
  4279. }
  4280. }";
  4281. CreateCompilationWithMscorlib(text).VerifyDiagnostics(
  4282. // (8,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4283. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(8, 16),
  4284. // (10,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4285. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(10, 12),
  4286. // (11,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4287. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(11, 19));
  4288. }
  4289. [Fact]
  4290. public void AttributeDiagnosticsForEachArgument()
  4291. {
  4292. var source = @"using System;
  4293. public class A : Attribute
  4294. {
  4295. public A(object[] a) {}
  4296. }
  4297. [A(new object[] { default(E), default(E) })]
  4298. class C<T, U> { public enum E {} }";
  4299. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4300. // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4301. // [A(new object[] { default(E), default(E) })]
  4302. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31),
  4303. // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4304. // [A(new object[] { default(E), default(E) })]
  4305. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19));
  4306. }
  4307. [Fact]
  4308. public void AttributeArgumentDecimalTypeConstant()
  4309. {
  4310. var source = @"using System;
  4311. [A(X = new decimal())]
  4312. public class A : Attribute
  4313. {
  4314. public object X;
  4315. const decimal y = new decimal();
  4316. }";
  4317. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4318. // (2,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4319. // [A(X = new decimal())]
  4320. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new decimal()").WithLocation(2, 8));
  4321. }
  4322. [WorkItem(542533, "DevDiv")]
  4323. [Fact]
  4324. public void DuplicateAttributeOnTypeParameterOfPartialClass()
  4325. {
  4326. string source = @"
  4327. class A : System.Attribute { }
  4328. partial class C<T> { }
  4329. partial class C<[A][A] T> { }
  4330. ";
  4331. CSharpCompilationOptions opt = TestOptions.Dll;
  4332. var compilation = CreateCompilationWithMscorlib(source, null, compOptions: opt);
  4333. compilation.VerifyDiagnostics(
  4334. // (4,2): error CS0579: Duplicate 'A' attribute
  4335. Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A"));
  4336. }
  4337. [WorkItem(542486, "DevDiv")]
  4338. [Fact]
  4339. public void MethodParameterScope()
  4340. {
  4341. string source = @"
  4342. using System;
  4343. class A : Attribute
  4344. {
  4345. public A(int x) { Console.WriteLine(x); }
  4346. }
  4347. class C
  4348. {
  4349. [A(qq)] // CS0103 - no 'qq' in scope
  4350. C(int qq) { }
  4351. [A(rr)] // CS0103 - no 'rr' in scope
  4352. void M(int rr) { }
  4353. int P { [A(value)]set { } } // CS0103 - no 'value' in scope
  4354. static void Main() { }
  4355. }
  4356. ";
  4357. var compilation = CreateCompilationWithMscorlib(source);
  4358. compilation.VerifyDiagnostics(
  4359. // (11,8): error CS0103: The name 'qq' does not exist in the current context
  4360. Diagnostic(ErrorCode.ERR_NameNotInContext, "qq").WithArguments("qq"),
  4361. // (14,8): error CS0103: The name 'rr' does not exist in the current context
  4362. Diagnostic(ErrorCode.ERR_NameNotInContext, "rr").WithArguments("rr"),
  4363. // (17,16): error CS0103: The name 'value' does not exist in the current context
  4364. Diagnostic(ErrorCode.ERR_NameNotInContext, "value").WithArguments("value"));
  4365. var tree = compilation.SyntaxTrees.Single();
  4366. var semanticModel = compilation.GetSemanticModel(tree);
  4367. var attrArgSyntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>();
  4368. Assert.Equal(3, attrArgSyntaxes.Count());
  4369. foreach (var argSyntax in attrArgSyntaxes)
  4370. {
  4371. var info = semanticModel.GetSymbolInfo(argSyntax.Expression);
  4372. Assert.Null(info.Symbol);
  4373. Assert.Equal(0, info.CandidateSymbols.Length);
  4374. Assert.Equal(CandidateReason.None, info.CandidateReason);
  4375. }
  4376. }
  4377. [WorkItem(542486, "DevDiv")]
  4378. [Fact]
  4379. public void MethodTypeParameterScope()
  4380. {
  4381. string source = @"
  4382. using System;
  4383. class A : Attribute
  4384. {
  4385. public A(int x) { Console.WriteLine(x); }
  4386. }
  4387. class C
  4388. {
  4389. [A(typeof(T))] // CS0246 - no 'T' in scope
  4390. void M<T>() { }
  4391. static void Main() { }
  4392. }
  4393. ";
  4394. var compilation = CreateCompilationWithMscorlib(source);
  4395. compilation.VerifyDiagnostics(
  4396. // (11,15): error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
  4397. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "T").WithArguments("T"));
  4398. var tree = compilation.SyntaxTrees.Single();
  4399. var semanticModel = compilation.GetSemanticModel(tree);
  4400. var attrArgSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single();
  4401. var typeofSyntax = (TypeOfExpressionSyntax)attrArgSyntax.Expression;
  4402. var typeofArgSyntax = typeofSyntax.Type;
  4403. Assert.Equal("T", typeofArgSyntax.ToString());
  4404. var info = semanticModel.GetSymbolInfo(typeofArgSyntax);
  4405. Assert.Null(info.Symbol);
  4406. Assert.Equal(0, info.CandidateSymbols.Length);
  4407. Assert.Equal(CandidateReason.None, info.CandidateReason);
  4408. }
  4409. [WorkItem(542625, "DevDiv")]
  4410. [Fact]
  4411. public void DuplicateAttributeOnPartialMethod()
  4412. {
  4413. string source = @"
  4414. class A : System.Attribute { }
  4415. class B : System.Attribute { }
  4416. partial class C
  4417. {
  4418. [return: B]
  4419. [A]
  4420. static partial void Foo();
  4421. [return: B]
  4422. [A]
  4423. static partial void Foo() { }
  4424. }
  4425. ";
  4426. CSharpCompilationOptions opt = TestOptions.Dll;
  4427. var compilation = CreateCompilationWithMscorlib(source, null, compOptions: opt);
  4428. compilation.VerifyDiagnostics(
  4429. // error CS0579: Duplicate 'A' attribute
  4430. Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A"),
  4431. // error CS0579: Duplicate 'B' attribute
  4432. Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"B").WithArguments("B"));
  4433. }
  4434. [WorkItem(542625, "DevDiv")]
  4435. [Fact]
  4436. public void DuplicateAttributeOnTypeParameterOfPartialMethod()
  4437. {
  4438. string source = @"
  4439. class A : System.Attribute { }
  4440. partial class C
  4441. {
  4442. static partial void Foo<[A] T>();
  4443. static partial void Foo<[A] T>() { }
  4444. // partial method without implementation, but another method with same name
  4445. static partial void Foo2<[A] T>();
  4446. static void Foo2<[A] T>() { }
  4447. // partial method without implementation, but another member with same name
  4448. static partial void Foo3<[A] T>();
  4449. private int Foo3;
  4450. // partial method without implementation
  4451. static partial void Foo4<[A][A] T>();
  4452. // partial methods differing by signature
  4453. static partial void Foo5<[A] T>(int x);
  4454. static partial void Foo5<[A] T>();
  4455. // partial method without defining declaration
  4456. static partial void Foo6<[A][A] T>() { }
  4457. }
  4458. ";
  4459. CSharpCompilationOptions opt = TestOptions.Dll;
  4460. var compilation = CreateCompilationWithMscorlib(source, null, compOptions: opt);
  4461. compilation.VerifyDiagnostics(
  4462. // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Foo6<T>()'
  4463. // static partial void Foo6<[A][A] T>() { }
  4464. Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Foo6").WithArguments("C.Foo6<T>()"),
  4465. // (11,17): error CS0111: Type 'C' already defines a member called 'Foo2' with the same parameter types
  4466. // static void Foo2<[A] T>() { }
  4467. Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Foo2").WithArguments("Foo2", "C"),
  4468. // (15,17): error CS0102: The type 'C' already contains a definition for 'Foo3'
  4469. // private int Foo3;
  4470. Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Foo3").WithArguments("C", "Foo3"),
  4471. // (7,30): error CS0579: Duplicate 'A' attribute
  4472. // static partial void Foo<[A] T>() { }
  4473. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A"),
  4474. // (18,34): error CS0579: Duplicate 'A' attribute
  4475. // static partial void Foo4<[A][A] T>();
  4476. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A"),
  4477. // (25,34): error CS0579: Duplicate 'A' attribute
  4478. // static partial void Foo6<[A][A] T>() { }
  4479. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A"),
  4480. // (15,17): warning CS0169: The field 'C.Foo3' is never used
  4481. // private int Foo3;
  4482. Diagnostic(ErrorCode.WRN_UnreferencedField, "Foo3").WithArguments("C.Foo3"));
  4483. }
  4484. [WorkItem(542625, "DevDiv")]
  4485. [Fact]
  4486. public void DuplicateAttributeOnParameterOfPartialMethod()
  4487. {
  4488. string source = @"
  4489. class A : System.Attribute { }
  4490. partial class C
  4491. {
  4492. static partial void Foo([param: A]int y);
  4493. static partial void Foo([A] int y) { }
  4494. // partial method without implementation, but another method with same name
  4495. static partial void Foo2([A] int y);
  4496. static void Foo2([A] int y) { }
  4497. // partial method without implementation, but another member with same name
  4498. static partial void Foo3([A] int y);
  4499. private int Foo3;
  4500. // partial method without implementation
  4501. static partial void Foo4([A][param: A] int y);
  4502. // partial methods differing by signature
  4503. static partial void Foo5([A] int y);
  4504. static partial void Foo5([A] int y, int z);
  4505. // partial method without defining declaration
  4506. static partial void Foo6([A][A] int y) { }
  4507. }
  4508. ";
  4509. CSharpCompilationOptions opt = TestOptions.Dll;
  4510. var compilation = CreateCompilationWithMscorlib(source, null, compOptions: opt);
  4511. compilation.VerifyDiagnostics(
  4512. // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Foo6(int)'
  4513. // static partial void Foo6([A][A] int y) { }
  4514. Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Foo6").WithArguments("C.Foo6(int)"),
  4515. // (11,17): error CS0111: Type 'C' already defines a member called 'Foo2' with the same parameter types
  4516. // static void Foo2([A] int y) { }
  4517. Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Foo2").WithArguments("Foo2", "C"),
  4518. // (15,17): error CS0102: The type 'C' already contains a definition for 'Foo3'
  4519. // private int Foo3;
  4520. Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Foo3").WithArguments("C", "Foo3"),
  4521. // (7,30): error CS0579: Duplicate 'A' attribute
  4522. // static partial void Foo([A] int y) { }
  4523. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A"),
  4524. // (18,41): error CS0579: Duplicate 'A' attribute
  4525. // static partial void Foo4([A][param: A] int y);
  4526. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A"),
  4527. // (25,34): error CS0579: Duplicate 'A' attribute
  4528. // static partial void Foo6([A][A] int y) { }
  4529. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A"),
  4530. // (15,17): warning CS0169: The field 'C.Foo3' is never used
  4531. // private int Foo3;
  4532. Diagnostic(ErrorCode.WRN_UnreferencedField, "Foo3").WithArguments("C.Foo3"));
  4533. }
  4534. [Fact]
  4535. public void PartialMethodOverloads()
  4536. {
  4537. string source = @"
  4538. class A : System.Attribute { }
  4539. partial class C
  4540. {
  4541. static partial void F([A] int y);
  4542. static partial void F(int y, [A]int z);
  4543. }
  4544. ";
  4545. CompileAndVerify(source);
  4546. }
  4547. [WorkItem(543456, "DevDiv")]
  4548. [Fact]
  4549. public void StructLayoutFieldsAreUsed()
  4550. {
  4551. var source =
  4552. @"using System.Runtime.InteropServices;
  4553. [StructLayout(LayoutKind.Sequential)]
  4554. struct S
  4555. {
  4556. int a, b, c;
  4557. }";
  4558. CreateCompilationWithMscorlib(source).VerifyDiagnostics();
  4559. }
  4560. [WorkItem(542662, "DevDiv")]
  4561. [Fact]
  4562. public void FalseDuplicateOnPartial()
  4563. {
  4564. var source =
  4565. @"
  4566. using System;
  4567. class A : Attribute { }
  4568. partial class Program
  4569. {
  4570. static partial void Foo(int x);
  4571. [A]
  4572. static partial void Foo(int x) { }
  4573. static partial void Foo();
  4574. [A]
  4575. static partial void Foo() { }
  4576. static void Main()
  4577. {
  4578. Console.WriteLine(((Action) Foo).Method.GetCustomAttributesData().Count);
  4579. }
  4580. }
  4581. ";
  4582. CompileAndVerify(source, expectedOutput: "1");
  4583. }
  4584. [WorkItem(542652, "DevDiv")]
  4585. [Fact]
  4586. public void Bug9958()
  4587. {
  4588. var source =
  4589. @"
  4590. class A : System.Attribute { }
  4591. partial class C
  4592. {
  4593. static partial void Foo<T,[A] S>();
  4594. static partial void Foo<[A]>() { }
  4595. }";
  4596. CSharpCompilationOptions opt = TestOptions.Dll;
  4597. var compilation = CreateCompilationWithMscorlib(source, null, compOptions: opt);
  4598. compilation.VerifyDiagnostics(
  4599. // (7,32): error CS1001: Identifier expected
  4600. // static partial void Foo<[A]>() { }
  4601. Diagnostic(ErrorCode.ERR_IdentifierExpected, ">"),
  4602. // (7,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Foo<>()'
  4603. // static partial void Foo<[A]>() { }
  4604. Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Foo").WithArguments("C.Foo<>()"));
  4605. }
  4606. [WorkItem(542909, "DevDiv")]
  4607. [Fact]
  4608. public void OverriddenPropertyMissingAccessor()
  4609. {
  4610. var source =
  4611. @"using System;
  4612. class A : Attribute
  4613. {
  4614. public virtual int P { get; set; }
  4615. }
  4616. class B1 : A
  4617. {
  4618. public override int P { get { return base.P; } }
  4619. }
  4620. class B2 : A
  4621. {
  4622. public override int P { set { } }
  4623. }
  4624. [A(P=0)]
  4625. [B1(P=1)]
  4626. [B2(P = 2)]
  4627. class C
  4628. {
  4629. }";
  4630. CreateCompilationWithMscorlib(source).VerifyDiagnostics();
  4631. }
  4632. [WorkItem(542899, "DevDiv")]
  4633. [Fact]
  4634. public void TwoSyntaxTrees()
  4635. {
  4636. var source =
  4637. @"
  4638. using System.Reflection;
  4639. [assembly: AssemblyTitle(""EnterpriseLibraryExtensions"")]
  4640. ";
  4641. var source2 =
  4642. @"
  4643. using Microsoft.Practices.EnterpriseLibrary.Configuration.Design;
  4644. using EnterpriseLibraryExtensions;
  4645. [assembly: ConfigurationDesignManager(typeof(ExtensionDesignManager))]
  4646. ";
  4647. var compilation = CreateCompilationWithMscorlib(new string[] { source, source2 });
  4648. Assert.DoesNotThrow(() => compilation.GetDiagnostics());
  4649. }
  4650. [WorkItem(543785, "DevDiv")]
  4651. [Fact]
  4652. public void OpenGenericTypesUsedAsAttributeArgs()
  4653. {
  4654. var source =
  4655. @"
  4656. class Gen<T>
  4657. {
  4658. [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6;
  4659. }";
  4660. var compilation = CreateCompilationWithMscorlib(source);
  4661. Assert.NotEmpty(compilation.GetDiagnostics());
  4662. compilation.VerifyDiagnostics(
  4663. // (4,6): error CS0246: The type or namespace name 'TypeAttribute' could not be found (are you missing a using directive or an assembly reference?)
  4664. // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6;
  4665. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttribute"),
  4666. // (4,27): error CS0246: The type or namespace name 'L1' could not be found (are you missing a using directive or an assembly reference?)
  4667. // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6;
  4668. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L1").WithArguments("L1"),
  4669. // (4,55): warning CS0649: Field 'Gen<T>.Fld6' is never assigned to, and will always have its default value
  4670. // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6;
  4671. Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld6").WithArguments("Gen<T>.Fld6", ""));
  4672. }
  4673. [WorkItem(543914, "DevDiv")]
  4674. [Fact]
  4675. public void OpenGenericTypeInAttribute()
  4676. {
  4677. var source =
  4678. @"
  4679. class Gen<T> {}
  4680. class Gen2<T>: System.Attribute {}
  4681. [Gen]
  4682. [Gen2]
  4683. public class Test
  4684. {
  4685. public static int Main()
  4686. {
  4687. return 1;
  4688. }
  4689. }";
  4690. CSharpCompilationOptions opt = TestOptions.Dll;
  4691. var compilation = CreateCompilationWithMscorlib(source, null, compOptions: opt);
  4692. compilation.VerifyDiagnostics(
  4693. // (3,16): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
  4694. // class Gen2<T>: System.Attribute {}
  4695. Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute"),
  4696. // (5,2): error CS0404: Cannot apply attribute class 'Gen<T>' because it is generic
  4697. // [Gen]
  4698. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Gen").WithArguments("Gen<T>"),
  4699. // (6,2): error CS0404: Cannot apply attribute class 'Gen2<T>' because it is generic
  4700. // [Gen2]
  4701. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Gen2").WithArguments("Gen2<T>"));
  4702. }
  4703. [Fact]
  4704. public void GenericAttributeTypeFromILSource()
  4705. {
  4706. var ilSource = @"
  4707. .class public Gen<T> { }
  4708. .class public Gen2<T> extends [mscorlib] System.Attribute { }
  4709. ";
  4710. var csharpSource = @"
  4711. [Gen]
  4712. [Gen2]
  4713. public class Test
  4714. {
  4715. public static int Main()
  4716. {
  4717. return 1;
  4718. }
  4719. }";
  4720. var comp = CreateCompilationWithCustomILSource(csharpSource, ilSource);
  4721. comp.VerifyDiagnostics(
  4722. // (2,2): error CS0404: Cannot apply attribute class 'Gen<T>' because it is generic
  4723. // [Gen]
  4724. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Gen").WithArguments("Gen<T>"),
  4725. // (3,2): error CS0404: Cannot apply attribute class 'Gen2<T>' because it is generic
  4726. // [Gen2]
  4727. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Gen2").WithArguments("Gen2<T>"));
  4728. }
  4729. [WorkItem(544230, "DevDiv")]
  4730. [Fact]
  4731. public void Warnings_Unassigned_Unreferenced_AttributeTypeFields()
  4732. {
  4733. var source = @"
  4734. using System;
  4735. [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  4736. class B : Attribute
  4737. {
  4738. public Type PublicField; // CS0649
  4739. private Type PrivateField; // CS0169
  4740. protected Type ProtectedField; // CS0649
  4741. internal Type InternalField; // CS0649
  4742. }";
  4743. var comp = CreateCompilationWithMscorlib(source);
  4744. comp.VerifyDiagnostics(
  4745. // (7,17): warning CS0649: Field 'B.PublicField' is never assigned to, and will always have its default value null
  4746. // public Type PublicField; // CS0649
  4747. Diagnostic(ErrorCode.WRN_UnassignedInternalField, "PublicField").WithArguments("B.PublicField", "null"),
  4748. // (8,18): warning CS0169: The field 'B.PrivateField' is never used
  4749. // private Type PrivateField; // CS0169
  4750. Diagnostic(ErrorCode.WRN_UnreferencedField, "PrivateField").WithArguments("B.PrivateField"),
  4751. // (9,20): warning CS0649: Field 'B.ProtectedField' is never assigned to, and will always have its default value null
  4752. // protected Type ProtectedField; // CS0649
  4753. Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ProtectedField").WithArguments("B.ProtectedField", "null"),
  4754. // (10,19): warning CS0649: Field 'B.InternalField' is never assigned to, and will always have its default value null
  4755. // internal Type InternalField; // CS0649
  4756. Diagnostic(ErrorCode.WRN_UnassignedInternalField, "InternalField").WithArguments("B.InternalField", "null"));
  4757. }
  4758. [WorkItem(544230, "DevDiv")]
  4759. [Fact]
  4760. public void No_Warnings_For_Assigned_AttributeTypeFields()
  4761. {
  4762. var source = @"
  4763. using System;
  4764. [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  4765. class A : Attribute
  4766. {
  4767. public Type PublicField; // No CS0649
  4768. private Type PrivateField; // No CS0649
  4769. protected Type ProtectedField; // No CS0649
  4770. internal Type InternalField; // No CS0649
  4771. [A(PublicField = typeof(int))]
  4772. [A(PrivateField = typeof(int))]
  4773. [A(ProtectedField = typeof(int))]
  4774. [A(InternalField = typeof(int))]
  4775. static void Main()
  4776. {
  4777. }
  4778. }";
  4779. var comp = CreateCompilationWithMscorlib(source);
  4780. comp.VerifyDiagnostics(
  4781. // (13,8): error CS0617: 'PrivateField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.
  4782. // [A(PrivateField = typeof(int))]
  4783. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "PrivateField").WithArguments("PrivateField"),
  4784. // (14,8): error CS0617: 'ProtectedField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.
  4785. // [A(ProtectedField = typeof(int))]
  4786. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ProtectedField").WithArguments("ProtectedField"),
  4787. // (15,8): error CS0617: 'InternalField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.
  4788. // [A(InternalField = typeof(int))]
  4789. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "InternalField").WithArguments("InternalField"));
  4790. }
  4791. [WorkItem(544351, "DevDiv")]
  4792. [Fact]
  4793. public void CS0182_ERR_BadAttributeArgument_Bug_12638()
  4794. {
  4795. var source = @"
  4796. using System;
  4797. [A(X = new Array[] { new[] { 1 } })]
  4798. class A : Attribute
  4799. {
  4800. public object X;
  4801. }";
  4802. var comp = CreateCompilationWithMscorlib(source);
  4803. comp.VerifyDiagnostics(
  4804. // (4,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4805. // [A(X = new Array[] { new[] { 1 } })]
  4806. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new Array[] { new[] { 1 } }").WithLocation(4, 8));
  4807. }
  4808. [WorkItem(544348, "DevDiv")]
  4809. [Fact]
  4810. public void CS0182_ERR_BadAttributeArgument_WithConversions()
  4811. {
  4812. var source =
  4813. @"using System;
  4814. [A((int)(object)""ABC"")]
  4815. class A : Attribute
  4816. {
  4817. public A(int x) { }
  4818. }";
  4819. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4820. // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4821. // [A((int)(object)"ABC")]
  4822. Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(int)(object)""ABC""").WithLocation(3, 4));
  4823. }
  4824. [WorkItem(544348, "DevDiv")]
  4825. [Fact]
  4826. public void CS0182_ERR_BadAttributeArgument_WithConversions_02()
  4827. {
  4828. var source =
  4829. @"using System;
  4830. [A((object[])(object)( new [] { 1 }))]
  4831. class A : Attribute
  4832. {
  4833. public A(object[] x) { }
  4834. }
  4835. [B((object[])(object)(new string[] { ""a"", null }))]
  4836. class B : Attribute
  4837. {
  4838. public B(object[] x) { }
  4839. }
  4840. ";
  4841. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4842. // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4843. // [A((object[])(object)( new [] { 1 }))]
  4844. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "(object[])(object)( new [] { 1 })").WithLocation(3, 4),
  4845. // (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4846. // [B((object[])(object)(new string[] { "a", null }))]
  4847. Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(object[])(object)(new string[] { ""a"", null })").WithLocation(9, 4));
  4848. }
  4849. [WorkItem(529392, "DevDiv")]
  4850. [Fact]
  4851. public void CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue()
  4852. {
  4853. // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g.
  4854. // public class C<T>
  4855. // {
  4856. // public enum E { V }
  4857. // }
  4858. //
  4859. // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type.
  4860. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type.
  4861. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression:
  4862. // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification.
  4863. // (b) It has a compile time constant value.
  4864. // However, native compiler disallows both the above cases.
  4865. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile.
  4866. var source = @"
  4867. using System;
  4868. class A : Attribute
  4869. {
  4870. public object X;
  4871. }
  4872. class C<T>
  4873. {
  4874. [A(X = C<T>.E.V)]
  4875. public enum E { V }
  4876. }";
  4877. var comp = CreateCompilationWithMscorlib(source);
  4878. comp.VerifyDiagnostics(
  4879. // (11,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4880. // [A(X = C<T>.E.V)]
  4881. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C<T>.E.V").WithLocation(11, 12));
  4882. }
  4883. [WorkItem(529392, "DevDiv")]
  4884. [Fact]
  4885. public void AttributeArgument_ConstructedType_ConstantValue()
  4886. {
  4887. // See comments for test CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue
  4888. var source = @"
  4889. using System;
  4890. class A : Attribute
  4891. {
  4892. public object X;
  4893. public static void Main()
  4894. {
  4895. typeof(C<>.E).GetCustomAttributes(false);
  4896. }
  4897. }
  4898. public class C<T>
  4899. {
  4900. [A(X = C<int>.E.V)]
  4901. public enum E { V }
  4902. }";
  4903. CompileAndVerify(source, emitOptions: EmitOptions.RefEmitUnsupported_646014, expectedOutput: "");
  4904. }
  4905. [WorkItem(544512, "DevDiv")]
  4906. [Fact]
  4907. public void LambdaInAttributeArg()
  4908. {
  4909. string source = @"
  4910. public delegate void D();
  4911. public class myAttr : System.Attribute
  4912. {
  4913. public D d
  4914. {
  4915. get { return () => { }; }
  4916. set { }
  4917. }
  4918. }
  4919. [myAttr(d = () => { })]
  4920. class X
  4921. {
  4922. public static int Main()
  4923. {
  4924. return 1;
  4925. }
  4926. }
  4927. ";
  4928. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4929. // (14,9): error CS0655: 'd' is not a valid named attribute argument because it is not a valid attribute parameter type
  4930. // [myAttr(d = () => { })]
  4931. Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "d").WithArguments("d").WithLocation(14, 9));
  4932. }
  4933. [WorkItem(544590, "DevDiv")]
  4934. [Fact]
  4935. public void LambdaInAttributeArg2()
  4936. {
  4937. string source = @"
  4938. using System;
  4939. [AttributeUsage(AttributeTargets.All)]
  4940. public class Foo : Attribute
  4941. {
  4942. public Foo(int sName) { }
  4943. }
  4944. public class Class1 {
  4945. [field: Foo(((System.Func<int>)(() => 5))())]
  4946. public event EventHandler Click;
  4947. public static void Main()
  4948. {
  4949. }
  4950. }
  4951. ";
  4952. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4953. // (11,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  4954. // [field: Foo(((System.Func<int>)(() => 5))())]
  4955. Diagnostic(ErrorCode.ERR_BadAttributeArgument, "((System.Func<int>)(() => 5))()"),
  4956. // (12,31): warning CS0067: The event 'Class1.Click' is never used
  4957. // public event EventHandler Click;
  4958. Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("Class1.Click"));
  4959. }
  4960. [WorkItem(545030, "DevDiv")]
  4961. [Fact]
  4962. public void UserDefinedAttribute_Bug13264()
  4963. {
  4964. string source = @"
  4965. namespace System.Runtime.InteropServices
  4966. {
  4967. [DllImport] // Error
  4968. class DllImportAttribute {}
  4969. }
  4970. namespace System
  4971. {
  4972. [Object] // Warning
  4973. public class Object : System.Attribute {}
  4974. }
  4975. ";
  4976. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  4977. // (4,6): error CS0616: 'System.Runtime.InteropServices.DllImportAttribute' is not an attribute class
  4978. // [DllImport] // Error
  4979. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DllImport").WithArguments("System.Runtime.InteropServices.DllImportAttribute"),
  4980. // (9,6): warning CS0436: The type 'System.Object' in '' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
  4981. // [Object] // Warning
  4982. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("", "System.Object", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "object"));
  4983. }
  4984. [WorkItem(545241, "DevDiv")]
  4985. [Fact]
  4986. public void ConditionalAttributeOnAttribute()
  4987. {
  4988. string source = @"
  4989. using System;
  4990. using System.Diagnostics;
  4991. [Conditional(""A"")]
  4992. class Attr1 : Attribute
  4993. {
  4994. }
  4995. class Attr2 : Attribute
  4996. {
  4997. }
  4998. class Attr3 : Attr1
  4999. {
  5000. }
  5001. [Attr1, Attr2, Attr3]
  5002. class Test
  5003. {
  5004. }
  5005. ";
  5006. Action<ModuleSymbol> sourceValidator = module =>
  5007. {
  5008. var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  5009. var attrs = type.GetAttributes();
  5010. Assert.Equal(3, attrs.Length);
  5011. };
  5012. Action<ModuleSymbol> metadataValidator = module =>
  5013. {
  5014. var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  5015. var attrs = type.GetAttributes();
  5016. Assert.Equal(1, attrs.Length); // only one is not conditional
  5017. Assert.Equal("Attr2", attrs.Single().AttributeClass.Name);
  5018. };
  5019. CompileAndVerify(source, sourceSymbolValidator: sourceValidator, symbolValidator: metadataValidator);
  5020. }
  5021. [WorkItem(545499, "DevDiv")]
  5022. [Fact]
  5023. public void IncompleteMethodParamAttribute()
  5024. {
  5025. string source = @"
  5026. using System;
  5027. public class MyAttribute2 : Attribute
  5028. {
  5029. public Type[] Types;
  5030. }
  5031. public class Test
  5032. {
  5033. public void foo([MyAttribute2(Types = new Type[
  5034. ";
  5035. var compilation = CreateCompilationWithMscorlib(source);
  5036. Assert.NotEmpty(compilation.GetDiagnostics());
  5037. }
  5038. [Fact, WorkItem(545556, "DevDiv")]
  5039. public void NameLookupInDelegateParameterAttribute()
  5040. {
  5041. var source = @"
  5042. using System;
  5043. class A : Attribute
  5044. {
  5045. new const int Equals = 1;
  5046. delegate void F([A(Equals)] int x);
  5047. public A(int x) { }
  5048. }
  5049. ";
  5050. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  5051. // (7,24): error CS1503: Argument 1: cannot convert from 'method group' to 'int'
  5052. // delegate void F([A(Equals)] int x);
  5053. Diagnostic(ErrorCode.ERR_BadArgType, "Equals").WithArguments("1", "method group", "int"));
  5054. }
  5055. [Fact, WorkItem(546234, "DevDiv")]
  5056. public void AmbiguousClassNamespaceLookup()
  5057. {
  5058. // One from source, one from PE
  5059. var source = @"
  5060. using System;
  5061. [System]
  5062. class System : Attribute
  5063. {
  5064. }
  5065. ";
  5066. var compilation = CreateCompilationWithMscorlib(source);
  5067. compilation.VerifyDiagnostics(
  5068. // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
  5069. // using System;
  5070. Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System"),
  5071. // (2,7): error CS7007: A using directive can only be applied to static classes or namespaces; 'System' is a non-static class
  5072. // using System;
  5073. Diagnostic(ErrorCode.ERR_BadUsingType, "System").WithArguments("System").WithLocation(2, 7),
  5074. // (4,16): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?)
  5075. // class System : Attribute
  5076. Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute"),
  5077. // (3,2): error CS0616: 'System' is not an attribute class
  5078. // [System]
  5079. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "System").WithArguments("System"),
  5080. // (2,1): info CS8019: Unnecessary using directive.
  5081. // using System;
  5082. Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using System;"));
  5083. source = @"
  5084. [assembly: X]
  5085. namespace X
  5086. {
  5087. }
  5088. ";
  5089. var source2 = @"
  5090. using System;
  5091. public class X: Attribute
  5092. {
  5093. }
  5094. ";
  5095. var comp1 = CreateCompilationWithMscorlib(source2, assemblyName: "Temp0").ToMetadataReference();
  5096. CreateCompilationWithMscorlib(source, references: new[] { comp1 }).VerifyDiagnostics(
  5097. // (2,12): error CS0616: 'X' is not an attribute class
  5098. // [assembly: X]
  5099. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X"));
  5100. // Multiple from PE, none from Source
  5101. source2 = @"
  5102. using System;
  5103. public class X
  5104. {
  5105. }
  5106. ";
  5107. var source3 = @"
  5108. namespace X
  5109. {
  5110. }
  5111. ";
  5112. var source4 = @"
  5113. [X]
  5114. class Y
  5115. {
  5116. }
  5117. ";
  5118. comp1 = CreateCompilationWithMscorlib(source2, assemblyName: "Temp1").ToMetadataReference();
  5119. var comp2 = CreateCompilation(source3, assemblyName: "Temp2").ToMetadataReference();
  5120. var comp3 = CreateCompilationWithMscorlib(source4, references: new[] { comp1, comp2 });
  5121. comp3.VerifyDiagnostics(
  5122. // (2,2): error CS0434: The namespace 'X' in 'Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with the type 'X' in 'Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
  5123. // [X]
  5124. Diagnostic(ErrorCode.ERR_SameFullNameNsAgg, "X").WithArguments("Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X", "Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X"));
  5125. // Multiple from PE, one from Source: Failure
  5126. var source5 = @"
  5127. [X]
  5128. class X
  5129. {
  5130. }
  5131. ";
  5132. comp3 = CreateCompilationWithMscorlib(source5, references: new[] { comp1, comp2 });
  5133. comp3.VerifyDiagnostics(
  5134. // (2,2): error CS0616: 'X' is not an attribute class
  5135. // [X]
  5136. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X"));
  5137. // Multiple from PE, one from Source: Success
  5138. source5 = @"
  5139. using System;
  5140. [X]
  5141. class X: Attribute
  5142. {
  5143. }
  5144. ";
  5145. CompileAndVerify(source5, emitOptions: EmitOptions.CCI, additionalRefs: new[] { comp1, comp2 });
  5146. // Multiple from PE, multiple from Source
  5147. var source6 = @"
  5148. [X]
  5149. class X
  5150. {
  5151. }
  5152. namespace X
  5153. {
  5154. }
  5155. ";
  5156. comp3 = CreateCompilationWithMscorlib(source6, references: new[] { comp1, comp2 });
  5157. comp3.VerifyDiagnostics(
  5158. // (3,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'X'
  5159. // class X
  5160. Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "X").WithArguments("X", "<global namespace>"));
  5161. // Multiple from PE, one from Source with alias
  5162. var source7 = @"
  5163. using System;
  5164. using X = Foo;
  5165. [X]
  5166. class Foo: Attribute
  5167. {
  5168. }
  5169. ";
  5170. comp3 = CreateCompilationWithMscorlib(source7, references: new[] { comp1, comp2 });
  5171. comp3.VerifyDiagnostics(
  5172. // (4,2): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'X'
  5173. // [X]
  5174. Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "X").WithArguments("X", "<global namespace>"),
  5175. // (4,2): error CS0616: 'X' is not an attribute class
  5176. // [X]
  5177. Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X"));
  5178. }
  5179. [WorkItem(546283, "DevDiv")]
  5180. [Fact]
  5181. public void ApplyIndexerNameAttributeTwice()
  5182. {
  5183. var source =
  5184. @"using System.Runtime.CompilerServices;
  5185. public class IA
  5186. {
  5187. [IndexerName(""ItemX"")]
  5188. [IndexerName(""ItemY"")]
  5189. public virtual int this[int index]
  5190. {
  5191. get { return 1;}
  5192. set {}
  5193. }
  5194. }
  5195. ";
  5196. var compilation = CreateCompilationWithMscorlib(source);
  5197. compilation.VerifyDiagnostics(
  5198. // (6,3): error CS0579: Duplicate 'IndexerName' attribute
  5199. Diagnostic(ErrorCode.ERR_DuplicateAttribute, "IndexerName").WithArguments("IndexerName"));
  5200. var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer);
  5201. Assert.Equal("ItemX", indexer.MetadataName); //First one wins.
  5202. }
  5203. [WorkItem(530524, "DevDiv")]
  5204. [Fact]
  5205. public void PEMethodSymbolExtensionAttribute1()
  5206. {
  5207. var source1 =
  5208. @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
  5209. .assembly extern System.Core {}
  5210. .assembly '<<GeneratedFileName>>'
  5211. {
  5212. .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  5213. }
  5214. .class public E
  5215. {
  5216. .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  5217. .method public hidebysig specialname rtspecialname instance void .ctor() { ret }
  5218. .method public static void M(object o)
  5219. {
  5220. .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  5221. ret
  5222. }
  5223. }";
  5224. var reference1 = CompileIL(source1, appendDefaultHeader: false);
  5225. var source2 =
  5226. @"class C
  5227. {
  5228. static void M(object o)
  5229. {
  5230. o.M();
  5231. }
  5232. }";
  5233. var compilation = CreateCompilationWithMscorlib(source2, new[] { reference1 });
  5234. compilation.VerifyDiagnostics();
  5235. var assembly = compilation.Assembly;
  5236. Assert.Equal(assembly.GetAttributes().Length, 0);
  5237. var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E");
  5238. Assert.Equal(type.GetAttributes().Length, 0);
  5239. var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M");
  5240. Assert.Equal(method.GetAttributes().Length, 0);
  5241. Assert.True(method.TestIsExtensionBitSet);
  5242. Assert.True(method.TestIsExtensionBitTrue);
  5243. Assert.True(method.IsExtensionMethod);
  5244. }
  5245. [WorkItem(530524, "DevDiv")]
  5246. [Fact]
  5247. public void PEMethodSymbolExtensionAttribute2()
  5248. {
  5249. var source1 =
  5250. @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
  5251. .assembly extern System.Core {}
  5252. .assembly '<<GeneratedFileName>>'
  5253. {
  5254. }
  5255. .class public E
  5256. {
  5257. .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  5258. .method public hidebysig specialname rtspecialname instance void .ctor() { ret }
  5259. .method public static void M(object o)
  5260. {
  5261. .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  5262. ret
  5263. }
  5264. }";
  5265. var reference1 = CompileIL(source1, appendDefaultHeader: false);
  5266. var source2 =
  5267. @"class C
  5268. {
  5269. static void M(object o)
  5270. {
  5271. o.M();
  5272. }
  5273. }";
  5274. var compilation = CreateCompilationWithMscorlib(source2, new[] { reference1 });
  5275. compilation.VerifyDiagnostics(
  5276. // (5,11): error CS1061: 'object' does not contain a definition for 'M' and no extension method 'M' accepting a
  5277. // first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
  5278. // o.M();
  5279. Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M"));
  5280. var assembly = compilation.Assembly;
  5281. Assert.Equal(assembly.GetAttributes().Length, 0);
  5282. var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E");
  5283. Assert.Equal(type.GetAttributes().Length, 1);
  5284. var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M");
  5285. Assert.Equal(method.GetAttributes().Length, 1);
  5286. Assert.True(method.TestIsExtensionBitSet);
  5287. Assert.False(method.TestIsExtensionBitTrue);
  5288. Assert.False(method.IsExtensionMethod);
  5289. }
  5290. [WorkItem(530524, "DevDiv")]
  5291. [Fact]
  5292. public void PEMethodSymbolExtensionAttribute3()
  5293. {
  5294. var source1 =
  5295. @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
  5296. .assembly extern System.Core {}
  5297. .assembly '<<GeneratedFileName>>'
  5298. {
  5299. .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  5300. }
  5301. .class public E
  5302. {
  5303. .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  5304. .method public hidebysig specialname rtspecialname instance void .ctor() { ret }
  5305. .method public static void M(object o)
  5306. {
  5307. ret
  5308. }
  5309. }";
  5310. var reference1 = CompileIL(source1, appendDefaultHeader: false);
  5311. var source2 =
  5312. @"class C
  5313. {
  5314. static void M(object o)
  5315. {
  5316. o.M();
  5317. }
  5318. }";
  5319. var compilation = CreateCompilationWithMscorlib(source2, new[] { reference1 });
  5320. compilation.VerifyDiagnostics(
  5321. // (5,11): error CS1061: 'object' does not contain a definition for 'M' and no extension method 'M' accepting a
  5322. // first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
  5323. // o.M();
  5324. Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M"));
  5325. var assembly = compilation.Assembly;
  5326. Assert.Equal(0, assembly.GetAttributes().Length);
  5327. var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E");
  5328. Assert.Equal(0, type.GetAttributes().Length);
  5329. var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M");
  5330. Assert.Equal(0, method.GetAttributes().Length);
  5331. Assert.True(method.TestIsExtensionBitSet);
  5332. Assert.False(method.TestIsExtensionBitTrue);
  5333. Assert.False(method.IsExtensionMethod);
  5334. }
  5335. [WorkItem(530310, "DevDiv")]
  5336. [Fact]
  5337. public void PEParameterSymbolParamArrayAttribute()
  5338. {
  5339. var source1 =
  5340. @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
  5341. .assembly '<<GeneratedFileName>>'
  5342. {
  5343. }
  5344. .class public A
  5345. {
  5346. .method public hidebysig specialname rtspecialname instance void .ctor() { ret }
  5347. .method public static void M(int32 x, int32[] y)
  5348. {
  5349. .param [2]
  5350. .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
  5351. ret
  5352. }
  5353. }";
  5354. var reference1 = CompileIL(source1, appendDefaultHeader: false);
  5355. var source2 =
  5356. @"class C
  5357. {
  5358. static void Main(string[] args)
  5359. {
  5360. A.M(1, 2, 3);
  5361. A.M(1, 2, 3, 4);
  5362. }
  5363. }";
  5364. var compilation = CreateCompilationWithMscorlib(source2, new[] { reference1 });
  5365. compilation.VerifyDiagnostics();
  5366. var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PEMethodSymbol>("M");
  5367. Assert.Equal(0, method.GetAttributes().Length);
  5368. var yParam = method.Parameters[1];
  5369. Assert.True(yParam.IsParams);
  5370. Assert.Equal(0, yParam.GetAttributes().Length);
  5371. }
  5372. [WorkItem(546490, "DevDiv")]
  5373. [Fact]
  5374. public void Bug15984()
  5375. {
  5376. var source1 =
  5377. @"
  5378. .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
  5379. .assembly extern FSharp.Core {}
  5380. .assembly '<<GeneratedFileName>>'
  5381. {
  5382. }
  5383. .class public abstract auto ansi sealed Library1.Foo
  5384. extends [mscorlib]System.Object
  5385. {
  5386. .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 )
  5387. .method public static int32 inc(int32 x) cil managed
  5388. {
  5389. // Code size 5 (0x5)
  5390. .maxstack 8
  5391. IL_0000: nop
  5392. IL_0001: ldarg.0
  5393. IL_0002: ldc.i4.1
  5394. IL_0003: add
  5395. IL_0004: ret
  5396. } // end of method Foo::inc
  5397. } // end of class Library1.Foo
  5398. ";
  5399. var reference1 = CompileIL(source1, appendDefaultHeader: false);
  5400. var compilation = CreateCompilationWithMscorlib("", new[] { reference1 });
  5401. var type = compilation.GetTypeByMetadataName("Library1.Foo");
  5402. Assert.Equal(0, type.GetAttributes()[0].ConstructorArguments.Count());
  5403. }
  5404. [WorkItem(611177, "DevDiv")]
  5405. [Fact]
  5406. public void GenericAttributeType()
  5407. {
  5408. var source = @"
  5409. using System;
  5410. [A<>]
  5411. [A<int>]
  5412. [B]
  5413. [B<>]
  5414. [B<int>]
  5415. [C]
  5416. [C<>]
  5417. [C<int>]
  5418. [C<,>]
  5419. [C<int, int>]
  5420. class Test
  5421. {
  5422. }
  5423. public class A : Attribute
  5424. {
  5425. }
  5426. public class B<T> : Attribute
  5427. {
  5428. }
  5429. public class C<T, U> : Attribute
  5430. {
  5431. }
  5432. ";
  5433. var comp = CreateCompilationWithMscorlib(source);
  5434. comp.VerifyDiagnostics(
  5435. // NOTE: Dev11 reports ERR_AttributeCantBeGeneric for these, but this makes more sense.
  5436. // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments
  5437. // [A<>]
  5438. Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type"),
  5439. // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments
  5440. // [A<int>]
  5441. Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type"),
  5442. // (6,2): error CS0404: Cannot apply attribute class 'B<T>' because it is generic
  5443. // [B]
  5444. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "B").WithArguments("B<T>"),
  5445. // (7,2): error CS0404: Cannot apply attribute class 'B<T>' because it is generic
  5446. // [B<>]
  5447. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "B<>").WithArguments("B<T>"),
  5448. // (8,2): error CS0404: Cannot apply attribute class 'B<T>' because it is generic
  5449. // [B<int>]
  5450. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "B<int>").WithArguments("B<T>"),
  5451. // (9,2): error CS0404: Cannot apply attribute class 'C<T, U>' because it is generic
  5452. // [C]
  5453. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "C").WithArguments("C<T, U>"),
  5454. // (10,2): error CS0404: Cannot apply attribute class 'C<T, U>' because it is generic
  5455. // [C<>]
  5456. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "C<>").WithArguments("C<T, U>"),
  5457. // (11,2): error CS0404: Cannot apply attribute class 'C<T, U>' because it is generic
  5458. // [C<int>]
  5459. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "C<int>").WithArguments("C<T, U>"),
  5460. // (12,2): error CS0404: Cannot apply attribute class 'C<T, U>' because it is generic
  5461. // [C<,>]
  5462. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "C<,>").WithArguments("C<T, U>"),
  5463. // (13,2): error CS0404: Cannot apply attribute class 'C<T, U>' because it is generic
  5464. // [C<int, int>]
  5465. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "C<int, int>").WithArguments("C<T, U>"),
  5466. // (22,21): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
  5467. // public class B<T> : Attribute
  5468. Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "Attribute").WithArguments("System.Attribute"),
  5469. // (26,24): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
  5470. // public class C<T, U> : Attribute
  5471. Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "Attribute").WithArguments("System.Attribute"));
  5472. }
  5473. [WorkItem(611177, "DevDiv")]
  5474. [Fact]
  5475. public void AliasedGenericAttributeType_Source()
  5476. {
  5477. var source = @"
  5478. using System;
  5479. using Alias = C<int>;
  5480. [Alias]
  5481. [Alias<>]
  5482. [Alias<int>]
  5483. class Test
  5484. {
  5485. }
  5486. public class C<T> : Attribute
  5487. {
  5488. }
  5489. ";
  5490. var comp = CreateCompilationWithMscorlib(source);
  5491. comp.VerifyDiagnostics(
  5492. // (5,2): error CS0404: Cannot apply attribute class 'C<int>' because it is generic
  5493. // [Alias]
  5494. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Alias").WithArguments("C<int>"),
  5495. // (6,2): error CS0404: Cannot apply attribute class 'C<int>' because it is generic
  5496. // [Alias<>]
  5497. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Alias<>").WithArguments("C<int>"),
  5498. // (7,2): error CS0404: Cannot apply attribute class 'C<int>' because it is generic
  5499. // [Alias<int>]
  5500. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Alias<int>").WithArguments("C<int>"),
  5501. // (12,21): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
  5502. // public class C<T> : Attribute
  5503. Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "Attribute").WithArguments("System.Attribute"));
  5504. }
  5505. [WorkItem(611177, "DevDiv")]
  5506. [Fact]
  5507. public void AliasedGenericAttributeType_Metadata()
  5508. {
  5509. var il = @"
  5510. .class public auto ansi beforefieldinit C`1<T>
  5511. extends [mscorlib]System.Attribute
  5512. {
  5513. .method public hidebysig specialname rtspecialname
  5514. instance void .ctor() cil managed
  5515. {
  5516. ldarg.0
  5517. call instance void [mscorlib]System.Attribute::.ctor()
  5518. ret
  5519. }
  5520. }
  5521. ";
  5522. var source = @"
  5523. using Alias = C<int>;
  5524. [Alias]
  5525. [Alias<>]
  5526. [Alias<int>]
  5527. class Test
  5528. {
  5529. }
  5530. ";
  5531. // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the
  5532. // attribute at emit-time.
  5533. var comp = CreateCompilationWithCustomILSource(source, il);
  5534. comp.VerifyDiagnostics(
  5535. // (4,2): error CS0404: Cannot apply attribute class 'C<int>' because it is generic
  5536. // [Alias]
  5537. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Alias").WithArguments("C<int>"),
  5538. // (5,2): error CS0404: Cannot apply attribute class 'C<int>' because it is generic
  5539. // [Alias<>]
  5540. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Alias<>").WithArguments("C<int>"),
  5541. // (6,2): error CS0404: Cannot apply attribute class 'C<int>' because it is generic
  5542. // [Alias<int>]
  5543. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Alias<int>").WithArguments("C<int>"));
  5544. }
  5545. [WorkItem(611177, "DevDiv")]
  5546. [Fact]
  5547. public void AliasedGenericAttributeType_Nested()
  5548. {
  5549. var source = @"
  5550. using InnerAlias = Outer<int>.Inner;
  5551. using OuterAlias = Outer<int>;
  5552. [InnerAlias]
  5553. class Test
  5554. {
  5555. [OuterAlias.Inner]
  5556. static void Main()
  5557. {
  5558. }
  5559. }
  5560. public class Outer<T>
  5561. {
  5562. // Not a subtype of Attribute, since that wouldn't compile.
  5563. public class Inner
  5564. {
  5565. }
  5566. }
  5567. ";
  5568. var comp = CreateCompilationWithMscorlib(source);
  5569. comp.VerifyDiagnostics(
  5570. // (5,2): error CS0404: Cannot apply attribute class 'Outer<int>.Inner' because it is generic
  5571. // [InnerAlias]
  5572. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "InnerAlias").WithArguments("Outer<int>.Inner"),
  5573. // (8,17): error CS0404: Cannot apply attribute class 'Outer<int>.Inner' because it is generic
  5574. // [OuterAlias.Inner]
  5575. Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Inner").WithArguments("Outer<int>.Inner"));
  5576. }
  5577. [WorkItem(687816, "DevDiv")]
  5578. [Fact]
  5579. public void VerbatimAliasVersusNonVerbatimAlias()
  5580. {
  5581. var source = @"
  5582. using Action = A.ActionAttribute;
  5583. using ActionAttribute = A.ActionAttribute;
  5584. namespace A
  5585. {
  5586. class ActionAttribute : System.Attribute { }
  5587. }
  5588. class Program
  5589. {
  5590. [Action]
  5591. static void Main(string[] args) { }
  5592. }
  5593. ";
  5594. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  5595. // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute'
  5596. // [Action]
  5597. Diagnostic(ErrorCode.ERR_AmbigousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute"));
  5598. }
  5599. [WorkItem(687816, "DevDiv")]
  5600. [Fact]
  5601. public void DeclarationVersusNonVerbatimAlias()
  5602. {
  5603. var source = @"
  5604. using Action = A.ActionAttribute;
  5605. using A;
  5606. namespace A
  5607. {
  5608. class ActionAttribute : System.Attribute { }
  5609. }
  5610. class Program
  5611. {
  5612. [Action]
  5613. static void Main(string[] args) { }
  5614. }
  5615. ";
  5616. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  5617. // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute'
  5618. // [Action]
  5619. Diagnostic(ErrorCode.ERR_AmbigousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute"));
  5620. }
  5621. [WorkItem(728865, "DevDiv")]
  5622. [Fact]
  5623. public void Repro728865()
  5624. {
  5625. var source = @"
  5626. using System;
  5627. using System.Collections;
  5628. using System.Collections.Generic;
  5629. using System.Reflection;
  5630. using Microsoft.Yeti;
  5631. namespace PFxIntegration
  5632. {
  5633. public class ProducerConsumerScenario
  5634. {
  5635. static void Main(string[] args)
  5636. {
  5637. Type program = typeof(ProducerConsumerScenario);
  5638. MethodInfo methodInfo = program.GetMethod(""ProducerConsumer"");
  5639. Object[] myAttributes = methodInfo.GetCustomAttributes(false); ;
  5640. if (myAttributes.Length > 0)
  5641. {
  5642. Console.WriteLine(""\r\nThe attributes for the method - {0} - are: \r\n"", methodInfo);
  5643. for (int j = 0; j < myAttributes.Length; j++)
  5644. Console.WriteLine(""The type of the attribute is {0}"", myAttributes[j]);
  5645. }
  5646. }
  5647. public enum CollectionType
  5648. {
  5649. Default,
  5650. Queue,
  5651. Stack,
  5652. Bag
  5653. }
  5654. public ProducerConsumerScenario()
  5655. {
  5656. }
  5657. [CartesianRowData(
  5658. new int[] { 5, 100, 100000 },
  5659. new CollectionType[] { CollectionType.Default, CollectionType.Queue, CollectionType.Stack, CollectionType.Bag })]
  5660. public void ProducerConsumer(int inputSize, CollectionType collectionType)
  5661. {
  5662. Console.WriteLine(""Hello"");
  5663. }
  5664. }
  5665. }
  5666. namespace Microsoft.Yeti
  5667. {
  5668. [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
  5669. public class CartesianRowDataAttribute : Attribute
  5670. {
  5671. public CartesianRowDataAttribute()
  5672. {
  5673. }
  5674. public CartesianRowDataAttribute(params object[] data)
  5675. {
  5676. IEnumerable<object>[] asEnum = new IEnumerable<object>[data.Length];
  5677. for (int i = 0; i < data.Length; ++i)
  5678. {
  5679. WrapEnum((IEnumerable)data[i]);
  5680. }
  5681. }
  5682. static void WrapEnum(IEnumerable x)
  5683. {
  5684. foreach (object a in x)
  5685. {
  5686. Console.WriteLine("" - "" + a + "" -"");
  5687. }
  5688. }
  5689. } // class
  5690. } // namespace
  5691. ";
  5692. // TODO: refemit prints numeric values for the enum elements.
  5693. CompileAndVerify(source, emitOptions: EmitOptions.RefEmitBug, expectedOutput: @"
  5694. - 5 -
  5695. - 100 -
  5696. - 100000 -
  5697. - Default -
  5698. - Queue -
  5699. - Stack -
  5700. - Bag -
  5701. The attributes for the method - Void ProducerConsumer(Int32, CollectionType) - are:
  5702. The type of the attribute is Microsoft.Yeti.CartesianRowDataAttribute
  5703. ");
  5704. }
  5705. [WorkItem(728865, "DevDiv")]
  5706. [Fact]
  5707. public void StringArrayArgument1()
  5708. {
  5709. var source = @"
  5710. using System;
  5711. public class Test
  5712. {
  5713. [ArrayOnlyAttribute(new string[] { ""A"" })] //error
  5714. [ObjectOnlyAttribute(new string[] { ""A"" })]
  5715. [ArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work
  5716. void M1() { }
  5717. [ArrayOnlyAttribute(null)]
  5718. [ObjectOnlyAttribute(null)]
  5719. [ArrayOrObjectAttribute(null)] //array
  5720. void M2() { }
  5721. [ArrayOnlyAttribute(new object[] { ""A"" })]
  5722. [ObjectOnlyAttribute(new object[] { ""A"" })]
  5723. [ArrayOrObjectAttribute(new object[] { ""A"" })] //array
  5724. void M3() { }
  5725. }
  5726. public class ArrayOnlyAttribute : Attribute
  5727. {
  5728. public ArrayOnlyAttribute(object[] array) { }
  5729. }
  5730. public class ObjectOnlyAttribute : Attribute
  5731. {
  5732. public ObjectOnlyAttribute(object o) { }
  5733. }
  5734. public class ArrayOrObjectAttribute : Attribute
  5735. {
  5736. public ArrayOrObjectAttribute(object[] array) { }
  5737. public ArrayOrObjectAttribute(object o) { }
  5738. }
  5739. ";
  5740. var comp = CreateCompilationWithMscorlib(source);
  5741. comp.VerifyDiagnostics(
  5742. // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  5743. // [ArrayOnlyAttribute(new string[] { "A" })] //error
  5744. Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOnlyAttribute(new string[] { ""A"" })"),
  5745. // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  5746. // [ArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work
  5747. Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOrObjectAttribute(new string[] { ""A"" })"));
  5748. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  5749. var method1 = type.GetMember<MethodSymbol>("M1");
  5750. var method2 = type.GetMember<MethodSymbol>("M2");
  5751. var method3 = type.GetMember<MethodSymbol>("M3");
  5752. var attrs1 = method1.GetAttributes();
  5753. var value1 = new string[] { "A" };
  5754. attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1);
  5755. attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1);
  5756. attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1);
  5757. var attrs2 = method2.GetAttributes();
  5758. attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5759. attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null);
  5760. attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5761. var attrs3 = method3.GetAttributes();
  5762. var value3 = new object[] { "A" };
  5763. attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3);
  5764. attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3);
  5765. attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3);
  5766. }
  5767. [WorkItem(728865, "DevDiv")]
  5768. [Fact]
  5769. public void StringArrayArgument2()
  5770. {
  5771. var source = @"
  5772. using System;
  5773. public class Test
  5774. {
  5775. [ParamArrayOnlyAttribute(new string[] { ""A"" })] //error
  5776. [ObjectOnlyAttribute(new string[] { ""A"" })]
  5777. [ParamArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work
  5778. void M1() { }
  5779. [ParamArrayOnlyAttribute(null)]
  5780. [ObjectOnlyAttribute(null)]
  5781. [ParamArrayOrObjectAttribute(null)] //array
  5782. void M2() { }
  5783. [ParamArrayOnlyAttribute(new object[] { ""A"" })]
  5784. [ObjectOnlyAttribute(new object[] { ""A"" })]
  5785. [ParamArrayOrObjectAttribute(new object[] { ""A"" })] //array
  5786. void M3() { }
  5787. [ParamArrayOnlyAttribute(""A"")]
  5788. [ObjectOnlyAttribute(""A"")]
  5789. [ParamArrayOrObjectAttribute(""A"")] //object
  5790. void M4() { }
  5791. }
  5792. public class ParamArrayOnlyAttribute : Attribute
  5793. {
  5794. public ParamArrayOnlyAttribute(params object[] array) { }
  5795. }
  5796. public class ObjectOnlyAttribute : Attribute
  5797. {
  5798. public ObjectOnlyAttribute(object o) { }
  5799. }
  5800. public class ParamArrayOrObjectAttribute : Attribute
  5801. {
  5802. public ParamArrayOrObjectAttribute(params object[] array) { }
  5803. public ParamArrayOrObjectAttribute(object o) { }
  5804. }
  5805. ";
  5806. var comp = CreateCompilationWithMscorlib(source);
  5807. comp.VerifyDiagnostics(
  5808. // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  5809. // [ParamArrayOnlyAttribute(new string[] { "A" })] //error
  5810. Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOnlyAttribute(new string[] { ""A"" })"),
  5811. // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  5812. // [ParamArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work
  5813. Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOrObjectAttribute(new string[] { ""A"" })"));
  5814. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  5815. var method1 = type.GetMember<MethodSymbol>("M1");
  5816. var method2 = type.GetMember<MethodSymbol>("M2");
  5817. var method3 = type.GetMember<MethodSymbol>("M3");
  5818. var method4 = type.GetMember<MethodSymbol>("M4");
  5819. // As in the test above (i.e. not affected by params modifier).
  5820. var attrs1 = method1.GetAttributes();
  5821. var value1 = new string[] { "A" };
  5822. attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1);
  5823. attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1);
  5824. attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1);
  5825. // As in the test above (i.e. not affected by params modifier).
  5826. var attrs2 = method2.GetAttributes();
  5827. attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5828. attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null);
  5829. attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5830. // As in the test above (i.e. not affected by params modifier).
  5831. var attrs3 = method3.GetAttributes();
  5832. var value3 = new object[] { "A" };
  5833. attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3);
  5834. attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3);
  5835. attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3);
  5836. var attrs4 = method4.GetAttributes();
  5837. attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { "A" });
  5838. attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, "A");
  5839. attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, "A");
  5840. }
  5841. [WorkItem(728865, "DevDiv")]
  5842. [Fact]
  5843. public void StringArrayArgument3()
  5844. {
  5845. var source = @"
  5846. using System;
  5847. public class Test
  5848. {
  5849. [StringOnlyAttribute(new string[] { ""A"" })]
  5850. [ObjectOnlyAttribute(new string[] { ""A"" })] //error
  5851. [StringOrObjectAttribute(new string[] { ""A"" })] //string
  5852. void M1() { }
  5853. [StringOnlyAttribute(null)]
  5854. [ObjectOnlyAttribute(null)]
  5855. [StringOrObjectAttribute(null)] //string
  5856. void M2() { }
  5857. //[StringOnlyAttribute(new object[] { ""A"" })] //overload resolution failure
  5858. [ObjectOnlyAttribute(new object[] { ""A"" })]
  5859. [StringOrObjectAttribute(new object[] { ""A"" })] //object
  5860. void M3() { }
  5861. [StringOnlyAttribute(""A"")]
  5862. [ObjectOnlyAttribute(""A"")]
  5863. [StringOrObjectAttribute(""A"")] //string
  5864. void M4() { }
  5865. }
  5866. public class StringOnlyAttribute : Attribute
  5867. {
  5868. public StringOnlyAttribute(params string[] array) { }
  5869. }
  5870. public class ObjectOnlyAttribute : Attribute
  5871. {
  5872. public ObjectOnlyAttribute(params object[] array) { }
  5873. }
  5874. public class StringOrObjectAttribute : Attribute
  5875. {
  5876. public StringOrObjectAttribute(params string[] array) { }
  5877. public StringOrObjectAttribute(params object[] array) { }
  5878. }
  5879. ";
  5880. var comp = CreateCompilationWithMscorlib(source);
  5881. comp.VerifyDiagnostics(
  5882. // (7,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
  5883. // [ObjectOnlyAttribute(new string[] { "A" })] //error
  5884. Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ObjectOnlyAttribute(new string[] { ""A"" })"));
  5885. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  5886. var method1 = type.GetMember<MethodSymbol>("M1");
  5887. var method2 = type.GetMember<MethodSymbol>("M2");
  5888. var method3 = type.GetMember<MethodSymbol>("M3");
  5889. var method4 = type.GetMember<MethodSymbol>("M4");
  5890. var attrs1 = method1.GetAttributes();
  5891. var value1 = new string[] { "A" };
  5892. attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1);
  5893. attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1);
  5894. attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1);
  5895. var attrs2 = method2.GetAttributes();
  5896. attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5897. attrs2[1].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5898. attrs2[2].VerifyValue(0, TypedConstantKind.Array, (string[])null);
  5899. var attrs3 = method3.GetAttributes();
  5900. var value3 = new object[] { "A" };
  5901. attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3);
  5902. attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3);
  5903. var attrs4 = method4.GetAttributes();
  5904. var value4 = new object[] { "A" };
  5905. attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4);
  5906. attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4);
  5907. attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4);
  5908. }
  5909. [WorkItem(728865, "DevDiv")]
  5910. [Fact]
  5911. public void IntArrayArgument1()
  5912. {
  5913. var source = @"
  5914. using System;
  5915. public class Test
  5916. {
  5917. //[ArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure
  5918. [ObjectOnlyAttribute(new int[] { 1 })]
  5919. [ArrayOrObjectAttribute(new int[] { 1 })] //object
  5920. void M1() { }
  5921. [ArrayOnlyAttribute(null)]
  5922. [ObjectOnlyAttribute(null)]
  5923. [ArrayOrObjectAttribute(null)] //array
  5924. void M2() { }
  5925. [ArrayOnlyAttribute(new object[] { 1 })]
  5926. [ObjectOnlyAttribute(new object[] { 1 })]
  5927. [ArrayOrObjectAttribute(new object[] { 1 })] //array
  5928. void M3() { }
  5929. }
  5930. public class ArrayOnlyAttribute : Attribute
  5931. {
  5932. public ArrayOnlyAttribute(object[] array) { }
  5933. }
  5934. public class ObjectOnlyAttribute : Attribute
  5935. {
  5936. public ObjectOnlyAttribute(object o) { }
  5937. }
  5938. public class ArrayOrObjectAttribute : Attribute
  5939. {
  5940. public ArrayOrObjectAttribute(object[] array) { }
  5941. public ArrayOrObjectAttribute(object o) { }
  5942. }
  5943. ";
  5944. var comp = CreateCompilationWithMscorlib(source);
  5945. comp.VerifyDiagnostics();
  5946. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  5947. var method1 = type.GetMember<MethodSymbol>("M1");
  5948. var method2 = type.GetMember<MethodSymbol>("M2");
  5949. var method3 = type.GetMember<MethodSymbol>("M3");
  5950. var attrs1 = method1.GetAttributes();
  5951. var value1 = new int[] { 1 };
  5952. attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1);
  5953. attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1);
  5954. var attrs2 = method2.GetAttributes();
  5955. attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5956. attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null);
  5957. attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  5958. var attrs3 = method3.GetAttributes();
  5959. var value3 = new object[] { 1 };
  5960. attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3);
  5961. attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3);
  5962. attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3);
  5963. }
  5964. [WorkItem(728865, "DevDiv")]
  5965. [Fact]
  5966. public void IntArrayArgument2()
  5967. {
  5968. var source = @"
  5969. using System;
  5970. public class Test
  5971. {
  5972. //[ParamArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure
  5973. [ObjectOnlyAttribute(new int[] { 1 })]
  5974. [ParamArrayOrObjectAttribute(new int[] { 1 })] //object
  5975. void M1() { }
  5976. [ParamArrayOnlyAttribute(null)]
  5977. [ObjectOnlyAttribute(null)]
  5978. [ParamArrayOrObjectAttribute(null)] //array
  5979. void M2() { }
  5980. [ParamArrayOnlyAttribute(new object[] { 1 })]
  5981. [ObjectOnlyAttribute(new object[] { 1 })]
  5982. [ParamArrayOrObjectAttribute(new object[] { 1 })] //array
  5983. void M3() { }
  5984. [ParamArrayOnlyAttribute(1)]
  5985. [ObjectOnlyAttribute(1)]
  5986. [ParamArrayOrObjectAttribute(1)] //object
  5987. void M4() { }
  5988. }
  5989. public class ParamArrayOnlyAttribute : Attribute
  5990. {
  5991. public ParamArrayOnlyAttribute(params object[] array) { }
  5992. }
  5993. public class ObjectOnlyAttribute : Attribute
  5994. {
  5995. public ObjectOnlyAttribute(object o) { }
  5996. }
  5997. public class ParamArrayOrObjectAttribute : Attribute
  5998. {
  5999. public ParamArrayOrObjectAttribute(params object[] array) { }
  6000. public ParamArrayOrObjectAttribute(object o) { }
  6001. }
  6002. ";
  6003. var comp = CreateCompilationWithMscorlib(source);
  6004. comp.VerifyDiagnostics();
  6005. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  6006. var method1 = type.GetMember<MethodSymbol>("M1");
  6007. var method2 = type.GetMember<MethodSymbol>("M2");
  6008. var method3 = type.GetMember<MethodSymbol>("M3");
  6009. var method4 = type.GetMember<MethodSymbol>("M4");
  6010. // As in the test above (i.e. not affected by params modifier).
  6011. var attrs1 = method1.GetAttributes();
  6012. var value1 = new int[] { 1 };
  6013. attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1);
  6014. attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1);
  6015. // As in the test above (i.e. not affected by params modifier).
  6016. var attrs2 = method2.GetAttributes();
  6017. attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  6018. attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null);
  6019. attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null);
  6020. // As in the test above (i.e. not affected by params modifier).
  6021. var attrs3 = method3.GetAttributes();
  6022. var value3 = new object[] { 1 };
  6023. attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3);
  6024. attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3);
  6025. attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3);
  6026. var attrs4 = method4.GetAttributes();
  6027. attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { 1 });
  6028. attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, 1);
  6029. attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, 1);
  6030. }
  6031. [WorkItem(728865, "DevDiv")]
  6032. [Fact]
  6033. public void IntArrayArgument3()
  6034. {
  6035. var source = @"
  6036. using System;
  6037. public class Test
  6038. {
  6039. [IntOnlyAttribute(new int[] { 1 })]
  6040. [ObjectOnlyAttribute(new int[] { 1 })]
  6041. [IntOrObjectAttribute(new int[] { 1 })] //int
  6042. void M1() { }
  6043. [IntOnlyAttribute(null)]
  6044. [ObjectOnlyAttribute(null)]
  6045. //[IntOrObjectAttribute(null)] //ambiguous
  6046. void M2() { }
  6047. //[IntOnlyAttribute(new object[] { 1 })] //overload resolution failure
  6048. [ObjectOnlyAttribute(new object[] { 1 })]
  6049. [IntOrObjectAttribute(new object[] { 1 })] //object
  6050. void M3() { }
  6051. [IntOnlyAttribute(1)]
  6052. [ObjectOnlyAttribute(1)]
  6053. [IntOrObjectAttribute(1)] //int
  6054. void M4() { }
  6055. }
  6056. public class IntOnlyAttribute : Attribute
  6057. {
  6058. public IntOnlyAttribute(params int[] array) { }
  6059. }
  6060. public class ObjectOnlyAttribute : Attribute
  6061. {
  6062. public ObjectOnlyAttribute(params object[] array) { }
  6063. }
  6064. public class IntOrObjectAttribute : Attribute
  6065. {
  6066. public IntOrObjectAttribute(params int[] array) { }
  6067. public IntOrObjectAttribute(params object[] array) { }
  6068. }
  6069. ";
  6070. var comp = CreateCompilationWithMscorlib(source);
  6071. comp.VerifyDiagnostics();
  6072. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  6073. var method1 = type.GetMember<MethodSymbol>("M1");
  6074. var method2 = type.GetMember<MethodSymbol>("M2");
  6075. var method3 = type.GetMember<MethodSymbol>("M3");
  6076. var method4 = type.GetMember<MethodSymbol>("M4");
  6077. var attrs1 = method1.GetAttributes();
  6078. var value1 = new int[] { 1 };
  6079. attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1);
  6080. attrs1[1].VerifyValue(0, TypedConstantKind.Array, new object[] { value1 });
  6081. attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1);
  6082. var attrs2 = method2.GetAttributes();
  6083. var value2 = (object[])null;
  6084. attrs2[0].VerifyValue(0, TypedConstantKind.Array, value2);
  6085. attrs2[1].VerifyValue(0, TypedConstantKind.Array, value2);
  6086. var attrs3 = method3.GetAttributes();
  6087. var value3 = new object[] { 1 };
  6088. attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3);
  6089. attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3);
  6090. var attrs4 = method4.GetAttributes();
  6091. var value4 = new object[] { 1 };
  6092. attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4);
  6093. attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4);
  6094. attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4);
  6095. }
  6096. [WorkItem(739630, "DevDiv")]
  6097. [Fact]
  6098. public void NullVersusEmptyArray()
  6099. {
  6100. var source = @"
  6101. using System;
  6102. public class ArrayAttribute : Attribute
  6103. {
  6104. public int[] field;
  6105. public ArrayAttribute(int[] param) { }
  6106. }
  6107. public class Test
  6108. {
  6109. [Array(null)]
  6110. void M0() { }
  6111. [Array(new int[] { })]
  6112. void M1() { }
  6113. [Array(null, field=null)]
  6114. void M2() { }
  6115. [Array(new int[] { }, field = null)]
  6116. void M3() { }
  6117. [Array(null, field = new int[] { })]
  6118. void M4() { }
  6119. [Array(new int[] { }, field = new int[] { })]
  6120. void M5() { }
  6121. static void Main() { }
  6122. }
  6123. ";
  6124. var comp = CreateCompilationWithMscorlib(source);
  6125. comp.VerifyDiagnostics();
  6126. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
  6127. var methods = Enumerable.Range(0, 6).Select(i => type.GetMember<MethodSymbol>("M" + i));
  6128. var attrs = methods.Select(m => m.GetAttributes().Single()).ToArray();
  6129. var nullArray = (int[])null;
  6130. var emptyArray = new int[0];
  6131. const string fieldName = "field";
  6132. attrs[0].VerifyValue(0, TypedConstantKind.Array, nullArray);
  6133. attrs[1].VerifyValue(0, TypedConstantKind.Array, emptyArray);
  6134. attrs[2].VerifyValue(0, TypedConstantKind.Array, nullArray);
  6135. attrs[2].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray);
  6136. attrs[3].VerifyValue(0, TypedConstantKind.Array, emptyArray);
  6137. attrs[3].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray);
  6138. attrs[4].VerifyValue(0, TypedConstantKind.Array, nullArray);
  6139. attrs[4].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray);
  6140. attrs[5].VerifyValue(0, TypedConstantKind.Array, emptyArray);
  6141. attrs[5].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray);
  6142. }
  6143. [Fact]
  6144. [WorkItem(530266, "DevDiv")]
  6145. public void UnboundGenericTypeInTypedConstant()
  6146. {
  6147. var source = @"
  6148. using System;
  6149. public class TestAttribute : Attribute
  6150. {
  6151. public TestAttribute(Type x){}
  6152. }
  6153. [TestAttribute(typeof(Target<>))]
  6154. class Target<T>
  6155. {}";
  6156. var comp = CreateCompilationWithMscorlib(source, compOptions: TestOptions.Dll);
  6157. comp.VerifyDiagnostics();
  6158. var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Target");
  6159. var typeInAttribute = (NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value;
  6160. Assert.True(typeInAttribute.IsUnboundGenericType);
  6161. Assert.True(((INamedTypeSymbol)typeInAttribute).IsUnboundGenericType);
  6162. Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString());
  6163. var comp2 = CreateCompilationWithMscorlib("", new[] { comp.EmitToImageReference() });
  6164. type = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Target");
  6165. Assert.IsAssignableFrom<PENamedTypeSymbol>(type);
  6166. typeInAttribute = (NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value;
  6167. Assert.True(typeInAttribute.IsUnboundGenericType);
  6168. Assert.True(((INamedTypeSymbol)typeInAttribute).IsUnboundGenericType);
  6169. Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString());
  6170. }
  6171. #endregion
  6172. }
  6173. }