PageRenderTime 59ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/Src/Compilers/CSharp/Test/Emit/BreakingChanges.cs

https://github.com/EkardNT/Roslyn
C# | 1602 lines | 1480 code | 95 blank | 27 comment | 26 complexity | 2168fe6e8c14fc1301f1f513a0e633a1 MD5 | raw file

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

  1. // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  2. using System.Linq;
  3. using Microsoft.CodeAnalysis.CSharp.Symbols;
  4. using Microsoft.CodeAnalysis.CSharp.Syntax;
  5. using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
  6. using Microsoft.CodeAnalysis.Test.Utilities;
  7. using Roslyn.Test.Utilities;
  8. using Xunit;
  9. namespace Microsoft.CodeAnalysis.CSharp.UnitTests
  10. {
  11. public class BreakingChanges : CSharpTestBase
  12. {
  13. [Fact, WorkItem(527050, "DevDiv")]
  14. [Trait("Feature", "Directives")]
  15. public void TestCS1024DefineWithUnicodeInMiddle()
  16. {
  17. var test = @"#de\u0066in\U00000065 ABC";
  18. // This is now a negative test, this should not be allowed.
  19. SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_PPDirectiveExpected, @"de\u0066in\U00000065"));
  20. }
  21. [Fact, WorkItem(527951, "DevDiv")]
  22. public void CS0133ERR_NotConstantExpression05()
  23. {
  24. var text = @"
  25. class A
  26. {
  27. public void Do()
  28. {
  29. const object o1 = null;
  30. const string o2 = (string)o1; // Dev10 reports CS0133
  31. }
  32. }
  33. ";
  34. var comp = CreateCompilationWithMscorlib(text);
  35. comp.VerifyDiagnostics(
  36. // (7,22): warning CS0219: The variable 'o2' is assigned but its value is never used
  37. // const string o2 = (string)o1; // Dev10 reports CS0133
  38. Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o2").WithArguments("o2")
  39. );
  40. }
  41. [WorkItem(527943, "DevDiv")]
  42. [Fact]
  43. public void CS0146ERR_CircularBase05()
  44. {
  45. var text = @"
  46. interface IFace<T> { }
  47. class B : IFace<B.C.D>
  48. {
  49. public class C
  50. {
  51. public class D { }
  52. }
  53. }
  54. ";
  55. var comp = CreateCompilationWithMscorlib(text);
  56. // In Dev10, there was an error - ErrorCode.ERR_CircularBase at (4,7)
  57. Assert.Equal(0, comp.GetDiagnostics().Count());
  58. }
  59. [WorkItem(540371, "DevDiv"), WorkItem(530792, "DevDiv")]
  60. [Fact]
  61. void CS0507ERR_CantChangeAccessOnOverride_TestSynthesizedSealedAccessorsInDifferentAssembly()
  62. {
  63. var source1 = @"
  64. using System.Collections.Generic;
  65. public class Base<T>
  66. {
  67. public virtual List<T> Property1 { get { return null; } protected internal set { } }
  68. public virtual List<T> Property2 { protected internal get { return null; } set { } }
  69. }";
  70. var compilation1 = CreateCompilationWithMscorlib(source1);
  71. var source2 = @"
  72. using System.Collections.Generic;
  73. public class Derived : Base<int>
  74. {
  75. public sealed override List<int> Property1 { get { return null; } }
  76. public sealed override List<int> Property2 { set { } }
  77. }";
  78. var comp = CreateCompilationWithMscorlib(source2, new[] { new CSharpCompilationReference(compilation1) });
  79. comp.VerifyDiagnostics();
  80. // This is not a breaking change - but it is a change in behavior from Dev10
  81. // Dev10 used to report following errors -
  82. // Error CS0507: 'Derived.Property1.set': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property1.set'
  83. // Error CS0507: 'Derived.Property2.get': cannot change access modifiers when overriding 'protected' inherited member 'Base<int>.Property2.get'
  84. // Roslyn makes this case work by synthesizing 'protected' accessors for the missing ones
  85. var baseClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Base");
  86. var baseProperty1 = baseClass.GetMember<PropertySymbol>("Property1");
  87. var baseProperty2 = baseClass.GetMember<PropertySymbol>("Property2");
  88. Assert.Equal(Accessibility.Public, baseProperty1.DeclaredAccessibility);
  89. Assert.Equal(Accessibility.Public, baseProperty1.GetMethod.DeclaredAccessibility);
  90. Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty1.SetMethod.DeclaredAccessibility);
  91. Assert.Equal(Accessibility.Public, baseProperty2.DeclaredAccessibility);
  92. Assert.Equal(Accessibility.ProtectedOrInternal, baseProperty2.GetMethod.DeclaredAccessibility);
  93. Assert.Equal(Accessibility.Public, baseProperty2.SetMethod.DeclaredAccessibility);
  94. var derivedClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived");
  95. var derivedProperty1 = derivedClass.GetMember<SourcePropertySymbol>("Property1");
  96. var derivedProperty2 = derivedClass.GetMember<SourcePropertySymbol>("Property2");
  97. Assert.Equal(Accessibility.Public, derivedProperty1.DeclaredAccessibility);
  98. Assert.Equal(Accessibility.Public, derivedProperty1.GetMethod.DeclaredAccessibility);
  99. Assert.Null(derivedProperty1.SetMethod);
  100. Assert.Equal(Accessibility.Public, derivedProperty2.DeclaredAccessibility);
  101. Assert.Null(derivedProperty2.GetMethod);
  102. Assert.Equal(Accessibility.Public, derivedProperty2.SetMethod.DeclaredAccessibility);
  103. var derivedProperty1Synthesized = derivedProperty1.SynthesizedSealedAccessorOpt;
  104. var derivedProperty2Synthesized = derivedProperty2.SynthesizedSealedAccessorOpt;
  105. Assert.Equal(MethodKind.PropertySet, derivedProperty1Synthesized.MethodKind);
  106. Assert.Equal(Accessibility.Protected, derivedProperty1Synthesized.DeclaredAccessibility);
  107. Assert.Equal(MethodKind.PropertyGet, derivedProperty2Synthesized.MethodKind);
  108. Assert.Equal(Accessibility.Protected, derivedProperty2Synthesized.DeclaredAccessibility);
  109. }
  110. // Confirm that this error no longer exists
  111. [Fact]
  112. public void CS0609ERR_NameAttributeOnOverride()
  113. {
  114. var text = @"
  115. using System.Runtime.CompilerServices;
  116. public class idx
  117. {
  118. public virtual int this[int iPropIndex]
  119. {
  120. get { return 0; }
  121. set { }
  122. }
  123. }
  124. public class MonthDays : idx
  125. {
  126. [IndexerName(""MonthInfoIndexer"")]
  127. public override int this[int iPropIndex]
  128. {
  129. get { return 1; }
  130. set { }
  131. }
  132. }
  133. ";
  134. var compilation = CreateCompilationWithMscorlib(text);
  135. compilation.VerifyDiagnostics();
  136. var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("MonthDays").Indexers.Single();
  137. Assert.Equal(Microsoft.CodeAnalysis.WellKnownMemberNames.Indexer, indexer.Name);
  138. Assert.Equal("MonthInfoIndexer", indexer.MetadataName);
  139. }
  140. [WorkItem(527116, "DevDiv")]
  141. [Fact]
  142. public void RegressWarningInSingleMultiLineMixedXml()
  143. {
  144. var text = @"
  145. /// <summary>
  146. /** This is the summary */
  147. /// </summary>
  148. class Test
  149. {
  150. /** <summary> */
  151. /// This is the summary1
  152. /** </summary> */
  153. public int Field = 0;
  154. /** <summary> */
  155. /// This is the summary2
  156. /// </summary>
  157. string Prop { get; set; }
  158. /// <summary>
  159. /** This is the summary3
  160. * </summary> */
  161. static int Main() { return new Test().Field; }
  162. }
  163. ";
  164. var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments);
  165. Assert.NotNull(tree);
  166. Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
  167. // Dev10 allows (no warning)
  168. // Roslyn gives Warning CS1570 - "XML Comment has badly formed XML..."
  169. Assert.Equal(8, tree.GetDiagnostics().Count());
  170. }
  171. [Fact, WorkItem(527093, "DevDiv")]
  172. public void NoCS1570ForUndefinedXmlNamespace()
  173. {
  174. var text = @"
  175. /// <xml> xmlns:s=""uuid: BDC6E3F0-6DA3-11d1-A2A3 - 00AA00C14882"">
  176. /// <s:inventory>
  177. /// </s:inventory>
  178. /// </xml>
  179. class A { }
  180. ";
  181. var tree = Parse(text, options: TestOptions.RegularWithDocumentationComments);
  182. Assert.NotNull(tree);
  183. Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
  184. // Native Warning CS1570 - "XML Comment has badly formed XML..."
  185. // Roslyn no
  186. Assert.Empty(tree.GetDiagnostics());
  187. }
  188. [Fact, WorkItem(541345, "DevDiv")]
  189. public void CS0019_TestNullCoalesceWithNullOperandsErrors()
  190. {
  191. var source = @"
  192. class Program
  193. {
  194. static void Main()
  195. {
  196. // This is acceptable by the native compiler and treated as a non-constant null literal.
  197. // That violates the specification; we now correctly treat this as an error.
  198. object a = null ?? null;
  199. // The null coalescing operator never produces a compile-time constant even when
  200. // the arguments are constants.
  201. const object b = null ?? ""ABC"";
  202. const string c = ""DEF"" ?? null;
  203. const int d = (int?)null ?? 123;
  204. // It is legal, though pointless, to use null literals and constants in coalescing
  205. // expressions, provided you don't try to make the result a constant. These should
  206. // produce no errors:
  207. object z = null ?? ""GHI"";
  208. string y = ""JKL"" ?? null;
  209. int x = (int?)null ?? 456;
  210. }
  211. }
  212. ";
  213. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  214. Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>"),
  215. Diagnostic(ErrorCode.ERR_NotConstantExpression, @"null ?? ""ABC""").WithArguments("b"),
  216. Diagnostic(ErrorCode.ERR_NotConstantExpression, @"""DEF"" ?? null").WithArguments("c"),
  217. Diagnostic(ErrorCode.ERR_NotConstantExpression, "(int?)null ?? 123").WithArguments("d"));
  218. }
  219. [Fact, WorkItem(528676, "DevDiv"), WorkItem(528676, "DevDiv")]
  220. // CS0657WRN_AttributeLocationOnBadDeclaration_AfterAttrDeclOrDelegate
  221. void CS1730ERR_CantUseAttributeOnInvaildLocation()
  222. {
  223. var test = @"using System;
  224. [AttributeUsage(AttributeTargets.All)]
  225. public class Foo : Attribute
  226. {
  227. public int Name;
  228. public Foo(int sName) { Name = sName; }
  229. }
  230. public delegate void EventHandler(object sender, EventArgs e);
  231. [assembly: Foo(5)]
  232. public class Test { }
  233. ";
  234. // In Dev10, this is a warning CS0657
  235. // Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "assembly").WithArguments("assembly", "type")
  236. SyntaxFactory.ParseSyntaxTree(test).GetDiagnostics().Verify(Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "assembly"));
  237. }
  238. [WorkItem(528711, "DevDiv")]
  239. [Fact]
  240. public void CS9259_StructLayoutCycle()
  241. {
  242. var text =
  243. @"struct S1<T>
  244. {
  245. S1<S1<T>>.S2 x;
  246. struct S2
  247. {
  248. static T x;
  249. }
  250. }";
  251. var comp = CreateCompilationWithMscorlib(text);
  252. comp.VerifyDiagnostics(
  253. // (3,18): warning CS0169: The field 'S1<T>.x' is never used
  254. // S1<S1<T>>.S2 x;
  255. Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(3, 18),
  256. // (6,18): warning CS0169: The field 'S1<T>.S2.x' is never used
  257. // static T x;
  258. Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.S2.x").WithLocation(6, 18)
  259. );
  260. }
  261. [WorkItem(528094, "DevDiv")]
  262. [Fact]
  263. public void FormattingUnicodeNotPartOfId()
  264. {
  265. string source = @"
  266. // <Area> Lexical - Unicode Characters</Area>
  267. // <Title>
  268. // Compiler considers identifiers, which differ only in formatting-character, as different ones;
  269. // This is not actually correct behaviour but for the time being this is what we expect
  270. //</Title>
  271. //<RelatedBugs>DDB:133151</RelatedBugs>
  272. // <Expects Status=Success></Expects>
  273. #define A
  274. using System;
  275. class Program
  276. {
  277. static int Main()
  278. {
  279. int x = 0;
  280. #if A == A\uFFFB
  281. x=1;
  282. #endif
  283. Console.Write(x);
  284. return x;
  285. }
  286. }
  287. ";
  288. // Dev10 print '0'
  289. CompileAndVerify(source, expectedOutput: "1");
  290. }
  291. [WorkItem(529000, "DevDiv")]
  292. [Fact]
  293. public void NoCS0121ForSwitchedParamNames_Dev10814222()
  294. {
  295. string source = @"
  296. using System;
  297. // Bug Dev10: 814222 resolved as Won't Fix
  298. class Test
  299. {
  300. static void Main()
  301. {
  302. Console.Write(Bar(x: 1, y: ""T0"")); // Dev10:CS0121
  303. Test01.Main01();
  304. }
  305. public static int Bar(int x, string y, params int[] z) { return 1; }
  306. public static int Bar(string y, int x) { return 0; } // Roslyn pick this one
  307. }
  308. class Test01
  309. {
  310. public static int Bar<T>(int x, T y, params int[] z) { return 1; }
  311. public static int Bar<T>(string y, int x) { return 0; } // Roslyn pick this one
  312. public static int Foo<T>(int x, T y) { return 1; }
  313. public static int Foo<T>(string y, int x) { return 0; } // Roslyn pick this one
  314. public static int AbcDef<T>(int x, T y) { return 0; } // Roslyn pick this one
  315. public static int AbcDef<T>(string y, int x, params int[] z) { return 1; }
  316. public static void Main01()
  317. {
  318. Console.Write(Bar<string>(x: 1, y: ""T1"")); // Dev10:CS0121
  319. Console.Write(Foo<string>(x: 1, y: ""T2"")); // Dev10:CS0121
  320. Console.Write(AbcDef<string>(x: 1, y: ""T3"")); // Dev10:CS0121
  321. }
  322. }
  323. ";
  324. CompileAndVerify(source, expectedOutput: "0000");
  325. }
  326. [WorkItem(529001, "DevDiv")]
  327. [WorkItem(529002, "DevDiv")]
  328. [Fact]
  329. public void CS0185ERR_LockNeedsReference_RequireRefType()
  330. {
  331. var source = @"
  332. class C
  333. {
  334. void M<T, TClass, TStruct>()
  335. where TClass : class
  336. where TStruct : struct
  337. {
  338. lock (default(object)) ;
  339. lock (default(int)) ; // CS0185
  340. lock (default(T)) {} // new CS0185 - no constraints (Bug#10755)
  341. lock (default(TClass)) {}
  342. lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756)
  343. }
  344. }
  345. ";
  346. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  347. // (8,32): warning CS0642: Possible mistaken empty statement
  348. // lock (default(object)) ;
  349. Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"),
  350. // (9,29): warning CS0642: Possible mistaken empty statement
  351. // lock (default(int)) ; // CS0185
  352. Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"),
  353. // (9,15): error CS0185: 'int' is not a reference type as required by the lock statement
  354. // lock (default(int)) ; // CS0185
  355. Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(int)").WithArguments("int"),
  356. // (10,15): error CS0185: 'T' is not a reference type as required by the lock statement
  357. // lock (default(T)) {} // new CS0185 - no constraints (Bug#10755)
  358. Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(T)").WithArguments("T"),
  359. // (12,15): error CS0185: 'TStruct' is not a reference type as required by the lock statement
  360. // lock (default(TStruct)) {} // new CS0185 - constraints to value type (Bug#10756)
  361. Diagnostic(ErrorCode.ERR_LockNeedsReference, "default(TStruct)").WithArguments("TStruct"));
  362. }
  363. [WorkItem(528972, "DevDiv")]
  364. [Fact]
  365. public void CS0121ERR_AmbigCall_Lambda1()
  366. {
  367. var text = @"
  368. using System;
  369. class A
  370. {
  371. static void Main()
  372. {
  373. Foo( delegate () { throw new Exception(); }); // both Dev10 & Roslyn no error
  374. Foo(x: () => { throw new Exception(); }); // Dev10: CS0121, Roslyn: no error
  375. }
  376. public static void Foo(Action x)
  377. {
  378. Console.WriteLine(1);
  379. }
  380. public static void Foo(Func<int> x)
  381. {
  382. Console.WriteLine(2); // Roslyn call this one
  383. }
  384. }
  385. ";
  386. // Dev11 FIXED this, no error anymore (So Not breaking Dev11)
  387. // Dev10 reports CS0121 because ExpressionBinder::WhichConversionIsBetter fails to unwrap
  388. // the NamedArgumentSpecification to find the UNBOUNDLAMBDA and, thus, never calls
  389. // WhichLambdaConversionIsBetter.
  390. CreateCompilationWithMscorlib(text).VerifyDiagnostics();
  391. }
  392. [Fact, WorkItem(529202, "DevDiv")]
  393. public void NoCS0029_ErrorOnZeroToEnumToTypeConversion()
  394. {
  395. string source = @"
  396. class Program
  397. {
  398. static void Main()
  399. {
  400. S s = 0;
  401. }
  402. }
  403. enum E
  404. {
  405. Zero, One, Two
  406. }
  407. struct S
  408. {
  409. public static implicit operator S(E s)
  410. {
  411. return E.Zero;
  412. }
  413. }";
  414. // Dev10/11: (11,9): error CS0029: Cannot implicitly convert type 'int' to 'S'
  415. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  416. // (6,15): error CS0029: Cannot implicitly convert type 'int' to 'S'
  417. // S s = 0;
  418. Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "S")
  419. );
  420. }
  421. [Fact, WorkItem(529242, "DevDiv")]
  422. public void ThrowOverflowExceptionForUncheckedCheckedLambda()
  423. {
  424. string source = @"
  425. using System;
  426. class Program
  427. {
  428. static void Main()
  429. {
  430. Func<int, int> d = checked(delegate(int i)
  431. {
  432. int max = int.MaxValue;
  433. try
  434. {
  435. int n = max + 1;
  436. }
  437. catch (OverflowException)
  438. {
  439. Console.Write(""OV ""); // Roslyn throw
  440. }
  441. return i;
  442. });
  443. var r = unchecked(d(9));
  444. Console.Write(r);
  445. }
  446. }
  447. ";
  448. CompileAndVerify(source, expectedOutput: "OV 9");
  449. }
  450. [WorkItem(529262)]
  451. [Fact]
  452. public void PartialMethod_ParameterAndTypeParameterNames()
  453. {
  454. var source =
  455. @"using System;
  456. using System.Reflection;
  457. partial class C
  458. {
  459. static partial void M<T, U>(T x, U y);
  460. static partial void M<T1, T2>(T1 y, T2 x)
  461. {
  462. Console.Write(""{0}, {1} | "", x, y);
  463. var m = typeof(C).GetMethod(""M"", BindingFlags.Static | BindingFlags.NonPublic);
  464. var tp = m.GetGenericArguments();
  465. Console.Write(""{0}, {1} | "", tp[0].Name, tp[1].Name);
  466. var p = m.GetParameters();
  467. Console.Write(""{0}, {1}"", p[0].Name, p[1].Name);
  468. }
  469. static void Main()
  470. {
  471. M(x: 1, y: 2);
  472. }
  473. }";
  474. // Dev12 would emit "2, 1 | T1, T2 | x, y".
  475. CompileAndVerify(source, emitOptions: EmitOptions.RefEmitBug, expectedOutput: "2, 1 | T, U | x, y");
  476. }
  477. [Fact, WorkItem(529279, "DevDiv")]
  478. public void NewCS0029_ImplicitlyUnwrapGenericNullable()
  479. {
  480. string source = @"
  481. public class GenC<T, U> where T : struct, U
  482. {
  483. public void Test(T t)
  484. {
  485. T? nt = t;
  486. U valueUn = nt;
  487. }
  488. }";
  489. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  490. // (7,21): error CS0029: Cannot implicitly convert type 'T?' to 'U'
  491. // U valueUn = nt;
  492. Diagnostic(ErrorCode.ERR_NoImplicitConv, "nt").WithArguments("T?", "U"));
  493. }
  494. [Fact, WorkItem(529280, "DevDiv"), WorkItem(546864, "DevDiv")]
  495. public void ExplicitUDCWithGenericConstraints()
  496. {
  497. // This compiles successfully in Dev10 dues to a bug; a user-defined conversion
  498. // that converts from or to an interface should never be chosen. If you are
  499. // converting from Alpha to Beta via standard conversion, then Beta to Gamma
  500. // via user-defined conversion, then Gamma to Delta via standard conversion, then
  501. // none of Alpha, Beta, Gamma or Delta should be allowed to be interfaces. The
  502. // Dev10 compiler only checks Alpha and Delta, not Beta and Gamma.
  503. //
  504. // Unfortunately, real-world code both in devdiv and in the wild depends on this
  505. // behaviour, so we are replicating the bug in Roslyn.
  506. string source = @"using System;
  507. public interface IFoo { void Method(); }
  508. public class CT : IFoo { public void Method() { } }
  509. public class GenC<T> where T : IFoo
  510. {
  511. public T valueT;
  512. public static explicit operator T(GenC<T> val)
  513. {
  514. Console.Write(""ExpConv"");
  515. return val.valueT;
  516. }
  517. }
  518. public class Test
  519. {
  520. public static void Main()
  521. {
  522. var _class = new GenC<IFoo>();
  523. var ret = (CT)_class;
  524. }
  525. }
  526. ";
  527. // CompileAndVerify(source, expectedOutput: "ExpConv");
  528. CreateCompilationWithMscorlib(source).VerifyDiagnostics();
  529. }
  530. [Fact, WorkItem(529362, "DevDiv")]
  531. public void TestNullCoalescingOverImplicitExplictUDC()
  532. {
  533. string source = @"using System;
  534. struct GenS<T> where T : struct
  535. {
  536. public static int Flag;
  537. public static explicit operator T?(GenS<T> s)
  538. {
  539. Flag = 3;
  540. return default(T);
  541. }
  542. public static implicit operator T(GenS<T> s)
  543. {
  544. Flag = 2;
  545. return default(T);
  546. }
  547. }
  548. class Program
  549. {
  550. public static void Main()
  551. {
  552. int? int_a1 = 1;
  553. GenS<int>? s28 = new GenS<int>();
  554. // Due to related bug dev10: 742047 is won't fix
  555. // so expects the code will call explicit conversion operator
  556. int? result28 = s28 ?? int_a1;
  557. Console.WriteLine(GenS<int>.Flag);
  558. }
  559. }
  560. ";
  561. // Native compiler picks explict conversion - print 3
  562. CompileAndVerify(source, expectedOutput: "2");
  563. }
  564. [Fact, WorkItem(529362, "DevDiv")]
  565. public void TestNullCoalescingOverImplicitExplictUDC_2()
  566. {
  567. string source = @"using System;
  568. struct S
  569. {
  570. public static explicit operator int?(S? s)
  571. {
  572. Console.WriteLine(""Explicit"");
  573. return 3;
  574. }
  575. public static implicit operator int(S? s)
  576. {
  577. Console.WriteLine(""Implicit"");
  578. return 2;
  579. }
  580. }
  581. class Program
  582. {
  583. public static void Main()
  584. {
  585. int? nn = -1;
  586. S? s = new S();
  587. int? ret = s ?? nn;
  588. }
  589. }
  590. ";
  591. // Native compiler picks explict conversion
  592. CompileAndVerify(source, expectedOutput: "Implicit");
  593. }
  594. [Fact, WorkItem(529363, "DevDiv")]
  595. public void AssignmentNullCoalescingOperator()
  596. {
  597. string source = @"using System;
  598. class NullCoallescingTest
  599. {
  600. public static void Main()
  601. {
  602. int? a;
  603. int c;
  604. var x = (a = null) ?? (c = 123);
  605. Console.WriteLine(c);
  606. }
  607. }
  608. ";
  609. // Native compiler no error (print -123)
  610. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  611. // (10,27): error CS0165: Use of unassigned local variable 'c'
  612. // Console.WriteLine(c);
  613. Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"),
  614. // (7,14): warning CS0219: The variable 'a' is assigned but its value is never used
  615. // int? a;
  616. Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a"));
  617. }
  618. [Fact, WorkItem(529464, "DevDiv")]
  619. public void MultiDimensionArrayWithDiffTypeIndexDevDiv31328()
  620. {
  621. var text = @"
  622. class A
  623. {
  624. public static void Main()
  625. {
  626. byte[,] arr = new byte[1, 1];
  627. ulong i1 = 0;
  628. int i2 = 1;
  629. arr[i1, i2] = 127; // Dev10 CS0266
  630. }
  631. }
  632. ";
  633. // Dev10 Won't fix bug#31328 for md array with different types' index and involving ulong
  634. // CS0266: Cannot implicitly convert type 'ulong' to 'int'. ...
  635. CreateCompilationWithMscorlib(text).VerifyDiagnostics();
  636. }
  637. [Fact]
  638. public void PointerArithmetic_SubtractNullLiteral()
  639. {
  640. var text = @"
  641. unsafe class C
  642. {
  643. long M(int* p)
  644. {
  645. return p - null; //Dev10 reports CS0019
  646. }
  647. }
  648. ";
  649. // Dev10: the null literal is treated as though it is converted to void*, making the subtraction illegal (ExpressionBinder::GetPtrBinOpSigs).
  650. // Roslyn: the null literal is converted to int*, making the subtraction legal.
  651. CreateCompilationWithMscorlib(text, compOptions: TestOptions.UnsafeDll).VerifyDiagnostics();
  652. }
  653. [Fact]
  654. public void CS0181ERR_BadAttributeParamType_Nullable()
  655. {
  656. var text = @"
  657. [Boom]
  658. class Boom : System.Attribute
  659. {
  660. public Boom(int? x = 0) { }
  661. static void Main()
  662. {
  663. typeof(Boom).GetCustomAttributes(true);
  664. }
  665. }
  666. ";
  667. // Roslyn: error CS0181: Attribute constructor parameter 'x' has type 'int?', which is not a valid attribute parameter type
  668. // Dev10/11: no error, but throw at runtime - System.Reflection.CustomAttributeFormatException
  669. CreateCompilationWithMscorlib(text).VerifyDiagnostics(
  670. Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Boom").WithArguments("x", "int?"));
  671. }
  672. [Fact, WorkItem(544232, "DevDiv"), WorkItem(544232, "DevDiv")]
  673. public void CS0208ERR_ManagedAddr_TypeParamPtr_Dev10_133087()
  674. {
  675. var text = @"
  676. class A { public class B { } }
  677. class C<T> : A
  678. {
  679. public static C<T*[]>.B b1;
  680. public static C<int*[]>.B b2;
  681. }
  682. public class Test
  683. {
  684. public static void Main()
  685. {
  686. C<int>.b1 = new A.B();
  687. C<string>.b2 = new A.B();
  688. }
  689. }
  690. ";
  691. // Roslyn: error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
  692. // Dev10/11: no error
  693. CreateCompilationWithMscorlib(text).VerifyDiagnostics(
  694. Diagnostic(ErrorCode.ERR_ManagedAddr, "T*").WithArguments("T"));
  695. }
  696. [Fact, WorkItem(544232, "DevDiv"), WorkItem(544232, "DevDiv")]
  697. public void CS0208ERR_ManagedAddr_TypeParamPtr_Dev10_176771()
  698. {
  699. var text = @"
  700. class A { public interface I { } }
  701. class F<T> : A where T : F<object*>.I { }
  702. ";
  703. // Roslyn: error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object')
  704. // Dev10/11: no error
  705. CreateCompilationWithMscorlib(text).VerifyDiagnostics(
  706. Diagnostic(ErrorCode.ERR_ManagedAddr, "object*").WithArguments("object"));
  707. }
  708. /// <summary>
  709. /// When determining whether the LHS of a null-coalescing operator (??) is non-null, the native compiler strips off casts.
  710. ///
  711. /// We have decided not to reproduce this behavior.
  712. /// </summary>
  713. [Fact]
  714. public void CastOnLhsOfConditionalOperator()
  715. {
  716. var text = @"
  717. class C
  718. {
  719. static void Main(string[] args)
  720. {
  721. int i;
  722. int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable.
  723. int k;
  724. int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts.
  725. int m;
  726. int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator
  727. }
  728. }
  729. ";
  730. // Roslyn: error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object')
  731. // Dev10/11: no error
  732. CreateCompilationWithMscorlib(text).VerifyDiagnostics(
  733. // This is new in Roslyn.
  734. // (7,29): error CS0165: Use of unassigned local variable 'i'
  735. // int? j = (int?)1 ?? i; //dev10 accepts, since it treats the RHS as unreachable.
  736. Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i"),
  737. // These match Dev10.
  738. // (10,36): error CS0165: Use of unassigned local variable 'k'
  739. // int? l = ((int?)1 ?? j) ?? k; // If the LHS of the LHS is non-null, then the LHS should be non-null, but dev10 only handles casts.
  740. Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k"),
  741. // (13,57): error CS0165: Use of unassigned local variable 'm'
  742. // int? n = ((int?)1).HasValue ? ((int?)1).Value : m; //dev10 does not strip casts in a comparable conditional operator
  743. Diagnostic(ErrorCode.ERR_UseDefViolation, "m").WithArguments("m"));
  744. }
  745. [WorkItem(529974, "DevDiv")]
  746. [Fact]
  747. public void TestCollisionForLoopControlVariable()
  748. {
  749. var source = @"
  750. namespace Microsoft.Test.XmlGen.Protocols.Saml2
  751. {
  752. using System;
  753. using System.Collections.Generic;
  754. public class ProxyRestriction
  755. {
  756. XmlGenIntegerAttribute count;
  757. private List<XmlGenAttribute> Attributes { get; set; }
  758. public ProxyRestriction()
  759. {
  760. for (int count = 0; count < 10; count++)
  761. {
  762. }
  763. for (int i = 0; i < this.Attributes.Count; i++)
  764. {
  765. XmlGenAttribute attribute = this.Attributes[i];
  766. if (attribute.LocalName == null)
  767. {
  768. if (count is XmlGenIntegerAttribute)
  769. {
  770. count = (XmlGenIntegerAttribute)attribute;
  771. }
  772. else
  773. {
  774. count = new XmlGenIntegerAttribute(attribute);
  775. this.Attributes[i] = count;
  776. }
  777. break;
  778. }
  779. }
  780. if (count == null)
  781. {
  782. this.Attributes.Add(new XmlGenIntegerAttribute(String.Empty, null, String.Empty, -1, false));
  783. }
  784. }
  785. }
  786. internal class XmlGenAttribute
  787. {
  788. public object LocalName { get; internal set; }
  789. }
  790. internal class XmlGenIntegerAttribute : XmlGenAttribute
  791. {
  792. public XmlGenIntegerAttribute(string empty1, object count, string empty2, int v, bool isPresent)
  793. {
  794. }
  795. public XmlGenIntegerAttribute(XmlGenAttribute attribute)
  796. {
  797. }
  798. }
  799. }
  800. public class Program
  801. {
  802. public static void Main() { }
  803. }";
  804. // Dev11 reported no errors for the above repro and allowed the name 'count' to bind to different
  805. // variables within the same declaration space. According to the old spec the error should be reported.
  806. // In Roslyn the single definition rule is relaxed and we do not give an error, but for a different reason.
  807. CreateCompilationWithMscorlib(source).VerifyDiagnostics();
  808. }
  809. [Fact, WorkItem(530301, "DevDiv")]
  810. public void NoMore_CS0458WRN_AlwaysNull02()
  811. {
  812. CreateCompilationWithMscorlib(
  813. @"
  814. public class Test
  815. {
  816. const bool ct = true;
  817. public static int Main()
  818. {
  819. var a = (true & null) ?? null; // CS0458
  820. if (((null & true) == null)) // CS0458
  821. return 0;
  822. var b = !(null | false); // CS0458
  823. if ((false | null) != null) // CS0458
  824. return 1;
  825. const bool cf = false;
  826. var d = ct & null ^ null; // CS0458 - Roslyn Warn this ONLY
  827. d ^= !(null | cf); // CS0458
  828. return -1;
  829. }
  830. }
  831. ")
  832. // We decided to not report WRN_AlwaysNull in some cases.
  833. .VerifyDiagnostics(
  834. // Diagnostic(ErrorCode.WRN_AlwaysNull, "true & null").WithArguments("bool?"),
  835. // Diagnostic(ErrorCode.WRN_AlwaysNull, "null & true").WithArguments("bool?"),
  836. // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | false").WithArguments("bool?"),
  837. // Diagnostic(ErrorCode.WRN_AlwaysNull, "false | null").WithArguments("bool?"),
  838. Diagnostic(ErrorCode.WRN_AlwaysNull, "ct & null ^ null").WithArguments("bool?") //,
  839. // Diagnostic(ErrorCode.WRN_AlwaysNull, "null | cf").WithArguments("bool?")
  840. );
  841. }
  842. [WorkItem(530403, "DevDiv")]
  843. [Fact]
  844. public void CS0135_local_param_cannot_be_declared()
  845. {
  846. // Dev11 missed this error. The issue is that an a is a field of c, and then it is a local in parts of d.
  847. // by then referring to the field without the this keyword, it should be flagged as declaring a competing variable (as it is confusing).
  848. var text = @"
  849. using System;
  850. public class c
  851. {
  852. int a = 0;
  853. void d(bool b) {
  854. if(b)
  855. {
  856. int a = 1;
  857. Console.WriteLine(a);
  858. }
  859. else
  860. {
  861. a = 2;
  862. }
  863. a = 3;
  864. Console.WriteLine(a);
  865. }
  866. }
  867. ";
  868. var comp = CreateCompilationWithMscorlib(text);
  869. // In Roslyn the single definition rule is relaxed and we do not give an error.
  870. comp.VerifyDiagnostics();
  871. }
  872. [Fact, WorkItem(530518, "DevDiv")]
  873. public void ExpressionTreeExplicitOpVsConvert()
  874. {
  875. var text = @"
  876. using System;
  877. using System.Linq;
  878. using System.Linq.Expressions;
  879. class Test
  880. {
  881. public static explicit operator int(Test x) { return 1; }
  882. static void Main()
  883. {
  884. Expression<Func<Test, long?>> testExpr1 = x => (long?)x;
  885. Console.WriteLine(testExpr1);
  886. Expression<Func<Test, decimal?>> testExpr2 = x => (decimal?)x;
  887. Console.WriteLine(testExpr2);
  888. }
  889. }
  890. ";
  891. // Native Compiler: x => Convert(Convert(op_Explicit(x)))
  892. CompileAndVerify(text, additionalRefs: new[] { LinqAssemblyRef }, expectedOutput:
  893. @"x => Convert(Convert(Convert(x)))
  894. x => Convert(Convert(Convert(x)))
  895. ");
  896. }
  897. [Fact, WorkItem(530531, "DevDiv")]
  898. void ExpressionTreeNoCovertForIdentityConversion()
  899. {
  900. var source = @"
  901. using System;
  902. using System.Linq;
  903. using System.Linq.Expressions;
  904. class Test
  905. {
  906. static void Main()
  907. {
  908. Expression<Func<Guid, bool>> e = (x) => x != null;
  909. Console.WriteLine(e);
  910. Console.WriteLine(e.Compile()(default(Guid)));
  911. }
  912. }
  913. ";
  914. // Native compiler: x => (Convert(x) != Convert(null))
  915. CompileAndVerify(source, additionalRefs: new[] { LinqAssemblyRef }, expectedOutput:
  916. @"x => (Convert(x) != null)
  917. True
  918. ");
  919. }
  920. [Fact, WorkItem(530548, "DevDiv")]
  921. public void CS0219WRN_UnreferencedVarAssg_RHSMidRefType()
  922. {
  923. string source = @"
  924. public interface Base { }
  925. public struct Derived : Base { }
  926. public class Test
  927. {
  928. public static void Main()
  929. {
  930. var b1 = new Derived(); // Both Warning CS0219
  931. var b2 = (Base)new Derived(); // Both NO Warn (reference type)
  932. var b3 = (Derived)((Base)new Derived()); // Rolsyn Warning CS0219
  933. }
  934. }
  935. ";
  936. // Native compiler no error (print -123)
  937. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  938. // (8,13): warning CS0219: The variable 'b1' is assigned but its value is never used
  939. // var b1 = new Derived(); // Both Warning CS0219
  940. Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1"),
  941. // (10,13): warning CS0219: The variable 'b3' is assigned but its value is never used
  942. // var b3 = (Derived)((Base)new Derived()); // Rolsyn Warning CS0219
  943. Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b3").WithArguments("b3"));
  944. }
  945. [Fact, WorkItem(530556, "DevDiv")]
  946. public void NoCS0591ERR_InvalidAttributeArgument()
  947. {
  948. string source = @"
  949. using System;
  950. [AttributeUsage(AttributeTargets.All + 0xFFFFFF)]
  951. class MyAtt : Attribute { }
  952. [AttributeUsage((AttributeTargets)0xffff)]
  953. class MyAtt1 : Attribute { }
  954. public class Test {}
  955. ";
  956. // Native compiler error CS0591: Invalid value for argument to 'AttributeUsage' attribute
  957. CreateCompilationWithMscorlib(source).VerifyDiagnostics();
  958. }
  959. [Fact, WorkItem(530586, "DevDiv")]
  960. public void ThrowOnceInIteratorFinallyBlock()
  961. {
  962. string source = @"
  963. //<Title> Finally block runs twice in iterator</Title>
  964. //<RelatedBug>Dev10:473561-->8444?</RelatedBug>
  965. using System;
  966. using System.Collections;
  967. class Program
  968. {
  969. public static void Main()
  970. {
  971. var demo = new test();
  972. try
  973. {
  974. foreach (var x in demo.Foo()) { }
  975. }
  976. catch (Exception)
  977. {
  978. Console.Write(""EX "");
  979. }
  980. Console.WriteLine(demo.count);
  981. }
  982. class test
  983. {
  984. public int count = 0;
  985. public IEnumerable Foo()
  986. {
  987. try
  988. {
  989. yield return null;
  990. try
  991. {
  992. yield break;
  993. }
  994. catch
  995. { }
  996. }
  997. finally
  998. {
  999. Console.Write(""++ "");
  1000. ++count;
  1001. throw new Exception();
  1002. }
  1003. }
  1004. }
  1005. }
  1006. ";
  1007. // Native print "++ ++ EX 2"
  1008. CompileAndVerify(source, expectedOutput: " ++ EX 1");
  1009. }
  1010. [Fact, WorkItem(530587, "DevDiv")]
  1011. public void NoFormatCharInIDEqual()
  1012. {
  1013. string source = @"
  1014. #define A
  1015. using System;
  1016. class Program
  1017. {
  1018. static int Main()
  1019. {
  1020. int x = 0;
  1021. #if A == A\uFFFB
  1022. x=1;
  1023. #endif
  1024. Console.Write(x);
  1025. return x;
  1026. }
  1027. }
  1028. ";
  1029. CompileAndVerify(source, expectedOutput: "1"); // Native print 0
  1030. }
  1031. [Fact, WorkItem(530614, "DevDiv")]
  1032. public void CS1718WRN_ComparisonToSelf_Roslyn()
  1033. {
  1034. string source = @"
  1035. enum esbyte : sbyte { e0, e1 };
  1036. public class z_1495j12
  1037. {
  1038. public static void Main()
  1039. {
  1040. if (esbyte.e0 == esbyte.e0)
  1041. {
  1042. System.Console.WriteLine(""T"");
  1043. }
  1044. }}
  1045. ";
  1046. // Native compiler no warn
  1047. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  1048. // (7,5): warning CS1718: Comparison made to same variable; did you mean to compare something else?
  1049. Diagnostic(ErrorCode.WRN_ComparisonToSelf, "esbyte.e0 == esbyte.e0"));
  1050. }
  1051. [Fact, WorkItem(530629, "DevDiv")]
  1052. public void CS0414WRN_UnreferencedFieldAssg_Roslyn()
  1053. {
  1054. string source = @"
  1055. namespace VS7_336319
  1056. {
  1057. public sealed class PredefinedTypes
  1058. {
  1059. public class Kind { public static int Decimal; }
  1060. }
  1061. public class ExpressionBinder
  1062. {
  1063. private static PredefinedTypes PredefinedTypes = null;
  1064. private void Foo()
  1065. {
  1066. if (0 == (int)PredefinedTypes.Kind.Decimal) { }
  1067. }
  1068. }
  1069. }
  1070. ";
  1071. // Native compiler no warn
  1072. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  1073. // (10,40): warning CS0414: The field 'VS7_336319.ExpressionBinder.PredefinedTypes' is assigned but its value is never used
  1074. // private static PredefinedTypes PredefinedTypes = null;
  1075. Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "PredefinedTypes").WithArguments("VS7_336319.ExpressionBinder.PredefinedTypes"));
  1076. }
  1077. [Fact, WorkItem(530666, "DevDiv")]
  1078. public void ExpressionTreeWithNullableUDCandOperator()
  1079. {
  1080. string source = @"
  1081. using System;
  1082. using System.Linq.Expressions;
  1083. struct B
  1084. {
  1085. public static implicit operator int?(B x)
  1086. {
  1087. return 1;
  1088. }
  1089. public static int operator +(B x, int y)
  1090. {
  1091. return 2 + y;
  1092. }
  1093. static int Main()
  1094. {
  1095. Expression<Func<B, int?>> f = x => x + x;
  1096. var ret = f.Compile()(new B());
  1097. Console.WriteLine(ret);
  1098. return ret.Value - 3;
  1099. }
  1100. }
  1101. ";
  1102. // Native compiler throw
  1103. CompileAndVerify(source, additionalRefs: new[] { SystemCoreRef }, expectedOutput: "3");
  1104. }
  1105. [Fact, WorkItem(530696, "DevDiv")]
  1106. public void CS0121Err_AmbigiousMethodCall()
  1107. {
  1108. string source = @"
  1109. class G<T> { }
  1110. class C
  1111. {
  1112. static void M(params double[] x)
  1113. {
  1114. System.Console.WriteLine(1);
  1115. }
  1116. static void M(params G<int>[] x)
  1117. {
  1118. System.Console.WriteLine(2);
  1119. }
  1120. static void Main()
  1121. {
  1122. M();
  1123. }
  1124. }
  1125. ";
  1126. CreateCompilationWithMscorlib(source).VerifyDiagnostics(
  1127. // (15,13): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(params double[])' and 'C.M(params G<int>[])'
  1128. // M();
  1129. Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(params double[])", "C.M(params G<int>[])"));
  1130. }
  1131. [Fact, WorkItem(530653, "DevDiv")]
  1132. public void RepeatedObsoleteWarnings()
  1133. {
  1134. // <quote source="Srivatsn's comments from bug 16642">
  1135. // Inside a method body if you access a static field twice thus:
  1136. //
  1137. // var x = ObsoleteType.field1;
  1138. // var y = ObsoleteType.field1;
  1139. //
  1140. // then the native compiler reports ObsoleteType as obsolete only once. This is because the native compiler caches
  1141. // the lookup of typenames for certain cases and doesn’t report errors on the second lookup as that just comes
  1142. // from the cache. Note how I said caches sometimes. If you simply say -
  1143. //
  1144. // var x= new ObsoleteType();
  1145. // var y = new ObsoleteType();
  1146. //
  1147. // Then the native compiler reports the error twice. I don’t think we should replicate this in Roslyn. Note however
  1148. // that this is a breaking change because if the first line had been #pragma disabled, then the code would compile
  1149. // without warnings in Dev11 but we will report warnings. I think it’s a corner enough scenario and the native
  1150. // behavior is quirky enough to warrant a break.
  1151. // </quote>
  1152. CompileAndVerify(@"
  1153. using System;
  1154. [Obsolete]
  1155. public class ObsoleteType
  1156. {
  1157. public static readonly int field = 0;
  1158. }
  1159. public class Program
  1160. {
  1161. public static void Main()
  1162. {
  1163. #pragma warning disable 0612
  1164. var x = ObsoleteType.field;
  1165. #pragma warning restore 0612
  1166. var y = ObsoleteType.field; // In Dev11, this line doesn't produce a warning.
  1167. }
  1168. }").VerifyDiagnostics(
  1169. // (15,17): warning CS0612: 'ObsoleteType' is obsolete
  1170. // var y = ObsoleteType.field;
  1171. Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "ObsoleteType").WithArguments("ObsoleteType"));
  1172. }
  1173. [Fact, WorkItem(530303, "DevDiv")]
  1174. public void TestReferenceResolution()
  1175. {
  1176. var cs1Compilation = CreateCSharpCompilation("CS1",
  1177. @"public class CS1 {}",
  1178. compilationOptions: TestOptions.Dll);
  1179. var cs1Verifier = CompileAndVerify(cs1Compilation);
  1180. cs1Verifier.VerifyDiagnostics();
  1181. var cs2Compilation = CreateCSharpCompilation("CS2",
  1182. @"public class CS2<T> {}",
  1183. compilationOptions: TestOptions.Dll,
  1184. referencedCompilations: new Compilation[] { cs1Compilation });
  1185. var cs2Verifier = CompileAndVerify(cs2Compilation);
  1186. cs2Verifier.VerifyDiagnostics();
  1187. var cs3Compilation = CreateCSharpCompilation("CS3",
  1188. @"public class CS3 : CS2<CS1> {}",
  1189. compilationOptions: TestOptions.Dll,
  1190. referencedCompilations: new Compilation[] { cs1Compilation, cs2Compilation });
  1191. var cs3Verifier = CompileAndVerify(cs3Compilation, emitOptions: EmitOptions.RefEmitBug);
  1192. cs3Verifier.VerifyDiagnostics();
  1193. var cs4Compilation = CreateCSharpCompilation("CS4",
  1194. @"public class Program
  1195. {
  1196. static void Main()
  1197. {
  1198. System.Console.WriteLine(typeof(CS3));
  1199. }
  1200. }",
  1201. compilationOptions: TestOptions.Exe,
  1202. referencedCompilations: new Compilation[] { cs2Compilation, cs3Compilation });
  1203. cs4Compilation.VerifyDiagnostics();
  1204. }
  1205. [Fact, WorkItem(531014, "DevDiv")]
  1206. public void TestVariableAndTypeNameClashes()
  1207. {
  1208. CompileAndVerify(@"
  1209. using System;
  1210. public class Class1
  1211. {
  1212. internal class A4 { internal class B { } internal static string F() { return ""A4""; } }
  1213. internal class A5 { internal class B { } internal static string F() { return ""A5""; } }
  1214. internal class A6 { internal class B { } internal static string F() { return ""A6""; } }
  1215. internal delegate void D(); // Check the wierd E.M cases.
  1216. internal class Outer2
  1217. {
  1218. internal static void F(A4 A4)
  1219. {
  1220. A5 A5; const A6 A6 = null;
  1221. Console.WriteLine(typeof(A4.B));
  1222. Console.WriteLine(typeof(A5.B));
  1223. Console.WriteLine(typeof(A6.B));
  1224. Console.WriteLine(A4.F());
  1225. Console.WriteLine(A5.F());
  1226. Console.WriteLine(A6.F());
  1227. Console.WriteLine(default(A4) == null);
  1228. Console.WriteLine(default(A5) == null);
  1229. Console.WriteLine(default(A6) == null);
  1230. }
  1231. }
  1232. }").VerifyDiagnostics(
  1233. // Breaking Change: See bug 17395. Dev11 had a bug because of which it didn't report the below warnings.
  1234. // (13,16): warning CS0168: The variable 'A5' is declared but never used
  1235. // A5 A5; const A6 A6 = null;
  1236. Diagnostic(ErrorCode.WRN_UnreferencedVar, "A5").WithArguments("A5"),
  1237. // (13,29): warning CS0219: The variable 'A6' is assigned but its value is never used
  1238. // A5 A5; const A6 A6 = null;
  1239. Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "A6").WithArguments("A6"));
  1240. }
  1241. [WorkItem(530584, "DevDiv")]
  1242. [Fact]
  1243. public void NotRuntimeAmbiguousBecauseOfReturnTypes()
  1244. {
  1245. var source = @"
  1246. using System;
  1247. class Base<T, S>
  1248. {
  1249. public virtual int Foo(ref S x) { return 0; }
  1250. public virtual string Foo(out T x)
  1251. {
  1252. x = default(T); return ""Base.Out"";
  1253. }
  1254. }
  1255. class Derived : Base<int, int>
  1256. {
  1257. public override string Foo(out int x)
  1258. {
  1259. x = 0; return ""Derived.Out"";
  1260. }
  1261. static void Main()
  1262. {
  1263. int x;
  1264. Console.WriteLine(new Derived().Foo(out x));
  1265. }
  1266. }
  1267. ";
  1268. // BREAK: Dev11 reports WRN_MultipleRuntimeOverrideMatches, but there
  1269. // is no runtime ambiguity because the return types differ.
  1270. CompileAndVerify(source, expectedOutput: "Derived.Out");
  1271. }
  1272. [WorkItem(695311, "DevDiv")]
  1273. [Fact]
  1274. public void NestedCollectionInitializerOnGenericProperty()
  1275. {
  1276. var libSource = @"
  1277. using System.Collections;
  1278. public interface IAdd
  1279. {
  1280. void Add(object o);
  1281. }
  1282. public struct S : IEnumerable, IAdd
  1283. {
  1284. private ArrayList list;
  1285. public void Add(object o)
  1286. {
  1287. list = list ?? new ArrayList();
  1288. list.Add(o);
  1289. }
  1290. public IEnumerator GetEnumerator()
  1291. {
  1292. return (list ?? new ArrayList()).GetEnumerator();
  1293. }
  1294. }
  1295. public class C : IEnumerable, IAdd
  1296. {
  1297. private readonly ArrayList list = new ArrayList();
  1298. public void Add(object o)
  1299. {
  1300. list.Add(o);
  1301. }
  1302. public IEnumerator GetEnumerator()
  1303. {
  1304. return list.GetEnumerator();
  1305. }
  1306. }
  1307. public class Wrapper<T> : IEnumerable where T : IEnumerable, new()
  1308. {
  1309. public Wrapper()
  1310. {
  1311. this.Item = new T();
  1312. }
  1313. public T Item { get; private set; }
  1314. public IEnumerator GetEnumerator()
  1315. {
  1316. return Item.GetEnumerator();
  1317. }
  1318. }
  1319. public static class Util
  1320. {
  1321. public static int Count(IEnumerable i)
  1322. {
  1323. int count = 0;
  1324. foreach (var v in i) count++;
  1325. return count;
  1326. }
  1327. }
  1328. ";
  1329. var libRef = CreateCompilationWithMscorlib(libSource, assemblyName: "lib").EmitToImageReference();
  1330. {
  1331. var source = @"
  1332. using System;
  1333. using System.Collections;
  1334. class Test
  1335. {
  1336. static void Main()
  1337. {
  1338. Console.Write(Util.Count(Foo<S>()));
  1339. Console.Write(Util.Count(Foo<C>()));
  1340. }
  1341. static Wrapper<T> Foo<T>() where T : IEnumerable, IAdd, new()
  1342. {
  1343. return new Wrapper<T> { Item = { 1, 2, 3} };
  1344. }
  1345. }
  1346. ";
  1347. // As in dev11.
  1348. var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.Exe);
  1349. CompileAndVerify(comp, expectedOutput: "03");
  1350. }
  1351. {
  1352. var source = @"
  1353. using System;
  1354. using System.Collections;
  1355. class Test
  1356. {
  1357. static void Main()
  1358. {
  1359. Console.Write(Util.Count(Foo<C>()));
  1360. }
  1361. static Wrapper<T> Foo<T>() where T : class, IEnumerable, IAdd, new()
  1362. {
  1363. return new Wrapper<T> { Item = { 1, 2, 3} };
  1364. }
  1365. }
  1366. ";
  1367. // As in dev11.
  1368. // NOTE: The spec will likely be updated to make this illegal.
  1369. var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.Exe);
  1370. CompileAndVerify(comp, expectedOutput: "3");
  1371. }
  1372. {
  1373. var source = @"
  1374. using System;
  1375. using System.Collections;
  1376. class Test
  1377. {
  1378. static void Main()
  1379. {
  1380. Console.Write(Util.Count(Foo<S>()));
  1381. }
  1382. static Wrapper<T> Foo<T>() where T : struct, IEnumerable, IAdd
  1383. {
  1384. return new Wrapper<T> { Item = { 1, 2, 3} };
  1385. }
  1386. }
  1387. ";
  1388. // BREAK: dev11 compiles and prints "0"
  1389. var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.Exe);
  1390. comp.VerifyDiagnostics(
  1391. // (15,33): error CS1918: Members of property 'Wrapper<T>.Item' of type 'T' cannot be assigned with an object initializer because it is of a value type
  1392. // return new Wrapper<T> { Item = { 1, 2, 3} };
  1393. Diagnostic(ErrorCode.ERR_ValueTypePropertyInObjectInitializer, "Item").WithArguments("Wrapper<T>.Item", "T"));
  1394. }
  1395. }
  1396. [Fact]
  1397. [WorkItem(770424, "DevDiv")]

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