PageRenderTime 102ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/Src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelAPITests.cs

https://github.com/EkardNT/Roslyn
C# | 3182 lines | 2664 code | 457 blank | 61 comment | 7 complexity | a419aa8711e65a8f533b53b24d32f8d5 MD5 | raw file

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

  1. // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Immutable;
  5. using System.Linq;
  6. using Microsoft.CodeAnalysis.CSharp.Symbols;
  7. using Microsoft.CodeAnalysis.CSharp.Syntax;
  8. using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
  9. using Microsoft.CodeAnalysis.Test.Utilities;
  10. using Microsoft.CodeAnalysis.Text;
  11. using Roslyn.Test.Utilities;
  12. using Xunit;
  13. namespace Microsoft.CodeAnalysis.CSharp.UnitTests
  14. {
  15. public class SemanticTests : CSharpTestBase
  16. {
  17. [Fact]
  18. public void LocalSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilation()
  19. {
  20. var text = @"public class C { public void M() { int x = 10; } }";
  21. var tree = Parse(text);
  22. var comp = CreateCompilationWithMscorlib(tree);
  23. var model1 = comp.GetSemanticModel(tree);
  24. var model2 = comp.GetSemanticModel(tree);
  25. Assert.NotEqual(model1, model2);
  26. var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First();
  27. var symbol1 = model1.GetDeclaredSymbol(vardecl);
  28. var symbol2 = model2.GetDeclaredSymbol(vardecl);
  29. Assert.NotSame(symbol1, symbol2);
  30. Assert.Equal(symbol1, symbol2);
  31. }
  32. [Fact]
  33. public void LocalSymbolsAreDifferentArossSemanticModelsFromDifferentCompilations()
  34. {
  35. var text = @"public class C { public void M() { int x = 10; } }";
  36. var tree = Parse(text);
  37. var comp1 = CreateCompilationWithMscorlib(tree);
  38. var comp2 = CreateCompilationWithMscorlib(tree);
  39. var model1 = comp1.GetSemanticModel(tree);
  40. var model2 = comp2.GetSemanticModel(tree);
  41. Assert.NotEqual(model1, model2);
  42. var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First();
  43. var symbol1 = model1.GetDeclaredSymbol(vardecl);
  44. var symbol2 = model2.GetDeclaredSymbol(vardecl);
  45. Assert.NotSame(symbol1, symbol2);
  46. Assert.NotEqual(symbol1, symbol2);
  47. }
  48. [Fact]
  49. public void RangeVariableSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilation()
  50. {
  51. var text = @"using System.Linq; public class C { public void M() { var q = from c in string.Empty select c; } }";
  52. var tree = Parse(text);
  53. var comp = CreateCompilationWithMscorlibAndSystemCore(new[] { tree });
  54. var model1 = comp.GetSemanticModel(tree);
  55. var model2 = comp.GetSemanticModel(tree);
  56. Assert.NotEqual(model1, model2);
  57. var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryClauseSyntax>().First();
  58. var symbol1 = model1.GetDeclaredSymbol(vardecl);
  59. var symbol2 = model2.GetDeclaredSymbol(vardecl);
  60. Assert.NotSame(symbol1, symbol2);
  61. Assert.Equal(symbol1, symbol2);
  62. }
  63. [Fact]
  64. public void RangeVariableSymbolsAreDifferentArossSemanticModelsFromDifferentCompilations()
  65. {
  66. var text = @"using System.Linq; public class C { public void M() { var q = from c in string.Empty select c; } }";
  67. var tree = Parse(text);
  68. var comp1 = CreateCompilationWithMscorlibAndSystemCore(new[] { tree });
  69. var comp2 = CreateCompilationWithMscorlibAndSystemCore(new[] { tree });
  70. var model1 = comp1.GetSemanticModel(tree);
  71. var model2 = comp2.GetSemanticModel(tree);
  72. Assert.NotEqual(model1, model2);
  73. var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryClauseSyntax>().First();
  74. var symbol1 = model1.GetDeclaredSymbol(vardecl);
  75. var symbol2 = model2.GetDeclaredSymbol(vardecl);
  76. Assert.NotSame(symbol1, symbol2);
  77. Assert.NotEqual(symbol1, symbol2);
  78. }
  79. [Fact]
  80. public void LabelSymbolsAreEquivalentAcrossSemanticModelsFromSameCompilation()
  81. {
  82. var text = @"public class C { public void M() { label: goto label; } }";
  83. var tree = Parse(text);
  84. var comp = CreateCompilationWithMscorlib(tree);
  85. var model1 = comp.GetSemanticModel(tree);
  86. var model2 = comp.GetSemanticModel(tree);
  87. Assert.NotEqual(model1, model2);
  88. var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<GotoStatementSyntax>().First();
  89. var symbol1 = model1.GetSymbolInfo(statement.Expression).Symbol;
  90. var symbol2 = model2.GetSymbolInfo(statement.Expression).Symbol;
  91. Assert.Equal(false, ReferenceEquals(symbol1, symbol2));
  92. Assert.Equal(symbol1, symbol2);
  93. }
  94. [Fact]
  95. public void LambdaParameterSymbolsAreEquivalentAcrossSemanticModelsFromSameCompilation()
  96. {
  97. var text = @"using System; public class C { public void M() { Func<int,int> f = (p) => p; } }";
  98. var tree = Parse(text);
  99. var comp = CreateCompilationWithMscorlib(tree);
  100. var model1 = comp.GetSemanticModel(tree);
  101. var model2 = comp.GetSemanticModel(tree);
  102. Assert.NotEqual(model1, model2);
  103. var paramdecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
  104. var symbol1 = model1.GetDeclaredSymbol(paramdecl);
  105. var symbol2 = model2.GetDeclaredSymbol(paramdecl);
  106. Assert.NotSame(symbol1, symbol2);
  107. Assert.Equal(symbol1.ContainingSymbol, symbol2.ContainingSymbol);
  108. Assert.Equal(symbol1, symbol2);
  109. }
  110. [Fact]
  111. public void LambdaParameterSymbolsAreDifferentAcrossSemanticModelsFromDifferentCompilations()
  112. {
  113. var text = @"using System; public class C { public void M() { Func<int,int> f = (p) => p; } }";
  114. var tree1 = Parse(text);
  115. var tree2 = Parse(text);
  116. var comp1 = CreateCompilationWithMscorlib(tree1);
  117. var comp2 = CreateCompilationWithMscorlib(tree2);
  118. var model1 = comp1.GetSemanticModel(tree1);
  119. var model2 = comp2.GetSemanticModel(tree2);
  120. Assert.NotEqual(model1, model2);
  121. var paramdecl1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
  122. var symbol1 = model1.GetDeclaredSymbol(paramdecl1);
  123. var paramdecl2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
  124. var symbol2 = model2.GetDeclaredSymbol(paramdecl2);
  125. Assert.NotSame(symbol1, symbol2);
  126. Assert.NotEqual(symbol1.ContainingSymbol, symbol2.ContainingSymbol);
  127. Assert.NotEqual(symbol1, symbol2);
  128. }
  129. [WorkItem(539740, "DevDiv")]
  130. [Fact]
  131. public void NamespaceWithoutName()
  132. {
  133. var text = "namespace";
  134. var tree = Parse(text);
  135. var comp = CreateCompilationWithMscorlib(tree);
  136. var model = comp.GetSemanticModel(tree);
  137. var errors = comp.GetDiagnostics().ToArray();
  138. Assert.Equal(3, errors.Length);
  139. var nsArray = tree.GetCompilationUnitRoot().DescendantNodes().Where(node => node.IsKind(SyntaxKind.NamespaceDeclaration)).ToArray();
  140. Assert.Equal(1, nsArray.Length);
  141. var nsSyntax = nsArray[0] as NamespaceDeclarationSyntax;
  142. var symbol = model.GetDeclaredSymbol(nsSyntax);
  143. Assert.Equal(string.Empty, symbol.Name);
  144. }
  145. [Fact]
  146. public void LazyBoundUsings1()
  147. {
  148. var text =
  149. @"
  150. // Peter Golde[7/19/2010]: I managed to construct the following interesting example today,
  151. // which Dev10 does compile. Interestingly, the resolution of one “using” can depend
  152. // on the resolution of another “using” later in the same namespace.
  153. using K = A.Q;
  154. using L = B.R;
  155. class B
  156. {
  157. public class R
  158. {
  159. public class Q
  160. {
  161. public class S : K { }
  162. }
  163. }
  164. }
  165. class A : L
  166. {
  167. public K.S v = null;
  168. }
  169. ";
  170. var comp = CreateCompilationWithMscorlib(text);
  171. var global = comp.GlobalNamespace;
  172. var a = global.GetTypeMembers("A", 0).Single();
  173. var abase = a.BaseType;
  174. Assert.Equal("B.R", abase.ToTestDisplayString());
  175. var b = global.GetTypeMembers("B", 0).Single();
  176. var r = b.GetTypeMembers("R", 0).Single();
  177. var q = r.GetTypeMembers("Q", 0).Single();
  178. var v = a.GetMembers("v").Single() as FieldSymbol;
  179. var s = v.Type;
  180. Assert.Equal("B.R.Q.S", s.ToTestDisplayString());
  181. var sbase = s.BaseType;
  182. Assert.Equal("B.R.Q", sbase.ToTestDisplayString());
  183. }
  184. [Fact]
  185. public void Diagnostics1()
  186. {
  187. var text =
  188. @"
  189. class A : A {}
  190. ";
  191. var tree = Parse(text);
  192. var comp = CreateCompilationWithMscorlib(tree);
  193. var errs = comp.GetSemanticModel(tree).GetDeclarationDiagnostics();
  194. Assert.Equal(1, errs.Count());
  195. }
  196. [Fact]
  197. public void DiagnosticsInOneTree()
  198. {
  199. var partial1 =
  200. @"
  201. partial class A
  202. {
  203. void foo() { int x = y; }
  204. }
  205. class C : B {}
  206. ";
  207. var partial2 =
  208. @"
  209. partial class A
  210. {
  211. int q; //an unused field in a partial type
  212. void bar() { int x = z; }
  213. }
  214. class B : NonExistent {}
  215. ";
  216. var partial1Tree = Parse(partial1);
  217. var partial2Tree = Parse(partial2);
  218. var comp = CreateCompilationWithMscorlib(new SyntaxTree[] { partial1Tree, partial2Tree });
  219. var errs = comp.GetSemanticModel(partial1Tree).GetDiagnostics();
  220. Assert.Equal(1, errs.Count());
  221. }
  222. [Fact]
  223. public void Bindings1()
  224. {
  225. var text =
  226. @"
  227. class B : A {}
  228. class A {}
  229. ";
  230. var tree = Parse(text);
  231. var comp = CreateCompilationWithMscorlib(tree);
  232. var bdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  233. var bbase = bdecl.BaseList.Types[0] as TypeSyntax;
  234. var model = comp.GetSemanticModel(tree);
  235. var info = model.GetSymbolInfo(bbase);
  236. Assert.NotNull(info.Symbol);
  237. var a = comp.GlobalNamespace.GetTypeMembers("A", 0).Single();
  238. Assert.Equal(a, info.Symbol);
  239. Assert.Equal(a, model.GetTypeInfo(bbase).Type);
  240. }
  241. [Fact]
  242. public void BaseScope1()
  243. {
  244. // ensure the base clause is not bound in the scope of the class
  245. var text =
  246. @"
  247. public class C : B {}
  248. public class A {
  249. public class B {}
  250. }
  251. public class B : A {}
  252. ";
  253. var tree = Parse(text);
  254. var comp = CreateCompilationWithMscorlib(tree);
  255. var cdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  256. var cbase = cdecl.BaseList.Types[0] as TypeSyntax;
  257. var model = comp.GetSemanticModel(tree);
  258. var info = model.GetSymbolInfo(cbase);
  259. Assert.NotNull(info.Symbol);
  260. var b = comp.GlobalNamespace.GetTypeMembers("B", 0).Single();
  261. Assert.Equal(b, info.Symbol);
  262. Assert.Equal(b, model.GetTypeInfo(cbase).Type);
  263. }
  264. [Fact]
  265. public void BaseScope2()
  266. {
  267. // ensure type parameters are in scope in the base clause
  268. var text =
  269. @"
  270. public class C<T> : A<T> { }
  271. public class A<T> : B { }
  272. public class B {
  273. public class T { }
  274. }
  275. ";
  276. var tree = Parse(text);
  277. var comp = CreateCompilationWithMscorlib(tree);
  278. var cdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  279. var cbase = cdecl.BaseList.Types[0] as TypeSyntax;
  280. var model = comp.GetSemanticModel(tree);
  281. var info = model.GetSymbolInfo(cbase);
  282. Assert.NotNull(info.Symbol);
  283. var cbasetype = info.Symbol as NamedTypeSymbol;
  284. var c = comp.GlobalNamespace.GetTypeMembers("C", 1).Single();
  285. Assert.Equal(c.BaseType, cbasetype);
  286. }
  287. [Fact]
  288. public void Bindings2()
  289. {
  290. var text =
  291. @"
  292. class B<T> : A<T> {}
  293. class A<T> {}
  294. ";
  295. var tree = Parse(text);
  296. var comp = CreateCompilationWithMscorlib(tree);
  297. var bdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  298. var bbase = bdecl.BaseList.Types[0] as TypeSyntax; // A<T>
  299. var model = comp.GetSemanticModel(tree);
  300. var info = model.GetSymbolInfo(bbase);
  301. Assert.NotNull(info.Symbol);
  302. var at2 = info.Symbol as NamedTypeSymbol;
  303. Assert.Equal(at2, model.GetTypeInfo(bbase).Type);
  304. var a = comp.GlobalNamespace.GetTypeMembers("A", 1).Single();
  305. var at = a.TypeParameters.First();
  306. var b = comp.GlobalNamespace.GetTypeMembers("B", 1).Single();
  307. var bt = b.TypeParameters.First();
  308. Assert.Equal(a.OriginalDefinition, at2.OriginalDefinition);
  309. Assert.Equal(b.TypeParameters.First(), at2.TypeArguments.First());
  310. }
  311. [Fact]
  312. public void Bindings3()
  313. {
  314. var text =
  315. @"using System;
  316. using System.Collections.Generic;
  317. using System.Linq;
  318. class Program
  319. {
  320. static Program Field;
  321. }";
  322. var tree1 = Parse(text);
  323. var compilation = CreateCompilationWithMscorlib(tree1);
  324. var tree2 = Parse(text);
  325. var classProgram = tree2.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  326. var staticProgramField = classProgram.Members[0] as FieldDeclarationSyntax;
  327. var program = staticProgramField.Declaration.Type;
  328. var model = compilation.GetSemanticModel(tree1);
  329. Assert.Throws<ArgumentException>(() =>
  330. {
  331. // tree2 not in the compilation
  332. var lookup = model.GetSymbolInfo(program);
  333. });
  334. }
  335. [Fact]
  336. public void Bindings4()
  337. {
  338. var text =
  339. @"using System;
  340. using System.Collections.Generic;
  341. using System.Linq;
  342. class Program
  343. {
  344. Program p;
  345. static void Main(string[] args)
  346. {
  347. }
  348. }";
  349. var tree1 = Parse(text);
  350. var compilation = CreateCompilationWithMscorlib(tree1);
  351. var decl = tree1.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  352. var field = decl.Members[0] as FieldDeclarationSyntax;
  353. var type = field.Declaration.Type;
  354. var model = compilation.GetSemanticModel(tree1);
  355. var info = model.GetSymbolInfo(type);
  356. Assert.Equal(compilation.GlobalNamespace.GetTypeMembers("Program", 0).Single(), info.Symbol);
  357. }
  358. [Fact]
  359. public void Bindings5()
  360. {
  361. var text =
  362. @"using System;
  363. using System.Collections.Generic;
  364. using System.Linq;
  365. class Program
  366. {
  367. static void Main(string[] args)
  368. {
  369. }
  370. }";
  371. var tree1 = Parse(text);
  372. var tree2 = Parse(text);
  373. var compilation = CreateCompilationWithMscorlib(new SyntaxTree[] { tree1, tree2 });
  374. var decl = tree1.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  375. var method = decl.Members[0] as MethodDeclarationSyntax;
  376. var type = method.ParameterList.Parameters[0].Type;
  377. var model = compilation.GetSemanticModel(tree1);
  378. var info = model.GetSymbolInfo(type);
  379. Assert.Equal<Symbol>(compilation.GetSpecialType(SpecialType.System_String), (info.Symbol as ArrayTypeSymbol).ElementType);
  380. }
  381. [Fact]
  382. public void Speculative1()
  383. {
  384. var text =
  385. @"
  386. class B {
  387. object x;
  388. }
  389. class A {}
  390. ";
  391. var tree = Parse(text);
  392. var comp = CreateCompilationWithMscorlib(tree);
  393. var bdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  394. var xdecl = bdecl.Members[0] as FieldDeclarationSyntax;
  395. var model = comp.GetSemanticModel(tree);
  396. TypeSyntax speculate = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("A"));
  397. var symbolInfo = model.GetSpeculativeSymbolInfo(xdecl.SpanStart, speculate, SpeculativeBindingOption.BindAsTypeOrNamespace);
  398. var lookup = symbolInfo.Symbol as TypeSymbol;
  399. Assert.NotNull(lookup);
  400. var a = comp.GlobalNamespace.GetTypeMembers("A", 0).Single();
  401. Assert.Equal(a, lookup);
  402. }
  403. [Fact]
  404. public void GetType1()
  405. {
  406. var text =
  407. @"
  408. class A {
  409. class B {}
  410. }
  411. ";
  412. var tree = Parse(text);
  413. var comp = CreateCompilationWithMscorlib(tree);
  414. var adecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
  415. var bdecl = adecl.Members[0] as TypeDeclarationSyntax;
  416. var model = comp.GetSemanticModel(tree);
  417. var a1 = model.GetDeclaredSymbol(adecl);
  418. var b1 = model.GetDeclaredSymbol(bdecl);
  419. var global = comp.GlobalNamespace;
  420. var a2 = global.GetTypeMembers("A", 0).Single();
  421. var b2 = a2.GetTypeMembers("B", 0).Single();
  422. Assert.Equal(a2, a1);
  423. Assert.Equal(b2, b1);
  424. }
  425. [Fact]
  426. public void DottedName()
  427. {
  428. var text =
  429. @"
  430. class Main {
  431. A.B x; // this refers to the B within A.
  432. }
  433. class A {
  434. public class B {}
  435. }
  436. class B {}
  437. ";
  438. var tree = Parse(text);
  439. var comp = CreateCompilationWithMscorlib(tree);
  440. var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
  441. var root = tree.GetCompilationUnitRoot();
  442. var mainDecl = root.Members[0] as TypeDeclarationSyntax;
  443. var mainType = model.GetDeclaredSymbol(mainDecl);
  444. var aDecl = root.Members[1] as TypeDeclarationSyntax;
  445. var aType = model.GetDeclaredSymbol(aDecl);
  446. var abDecl = aDecl.Members[0] as TypeDeclarationSyntax;
  447. var abType = model.GetDeclaredSymbol(abDecl);
  448. var bDecl = root.Members[2] as TypeDeclarationSyntax;
  449. var bType = model.GetDeclaredSymbol(bDecl);
  450. var xDecl = mainDecl.Members[0] as FieldDeclarationSyntax;
  451. var xSym = mainType.GetMembers("x").Single() as FieldSymbol;
  452. Assert.Equal<ISymbol>(abType, xSym.Type);
  453. var info = model.GetSymbolInfo((xDecl.Declaration.Type as QualifiedNameSyntax).Right);
  454. Assert.Equal(abType, info.Symbol);
  455. }
  456. [Fact]
  457. public void AliasQualifiedName()
  458. {
  459. var text =
  460. @"
  461. class B {}
  462. namespace N {
  463. class C : global::B {}
  464. class B {}
  465. }
  466. ";
  467. var tree = Parse(text);
  468. var comp = CreateCompilationWithMscorlib(tree);
  469. var model = comp.GetSemanticModel(tree);
  470. var root = tree.GetCompilationUnitRoot();
  471. var nDecl = root.Members[0] as NamespaceDeclarationSyntax;
  472. var n2Decl = root.Members[1] as NamespaceDeclarationSyntax;
  473. var cDecl = n2Decl.Members[0] as TypeDeclarationSyntax;
  474. var cBase = (cDecl.BaseList.Types[0] as AliasQualifiedNameSyntax).Name;
  475. var cBaseType = model.GetSymbolInfo(cBase).Symbol;
  476. var bOuter = comp.GlobalNamespace.GetTypeMembers("B", 0).Single();
  477. var bInner = (comp.GlobalNamespace.GetMembers("N").Single() as NamespaceSymbol).GetTypeMembers("B", 0).Single();
  478. Assert.Equal(bOuter, cBaseType);
  479. }
  480. [Fact, WorkItem(528655, "DevDiv")]
  481. public void ErrorSymbolForInvalidCode()
  482. {
  483. var text = @"
  484. public class A
  485. {
  486. int foo { void foo() {} } // Error
  487. static int Main() { return 1; }
  488. }
  489. ";
  490. var tree = Parse(text);
  491. var comp = CreateCompilationWithMscorlib(tree);
  492. var mems = comp.SourceModule.GlobalNamespace.GetMembers();
  493. var typeA = mems.Where(s => s.Name == "A").Select(s => s);
  494. Assert.Equal(1, typeA.Count());
  495. var invalid = mems.Where(s => s.Name == "<invalid-global-code>").Select(s => s);
  496. Assert.Equal(1, invalid.Count());
  497. }
  498. [Fact, WorkItem(543225, "DevDiv"), WorkItem(529057, "DevDiv")]
  499. public void MergePartialMethodAndParameterSymbols()
  500. {
  501. var text = @"
  502. using System;
  503. partial class PC
  504. {
  505. partial void PM(int pp);
  506. }
  507. partial class PC
  508. {
  509. partial void PM(int pp) {}
  510. }
  511. ";
  512. var tree = Parse(text);
  513. var comp = CreateCompilationWithMscorlib(tree);
  514. var pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("PC").Single();
  515. var pMethodSym = pTypeSym.GetMembers("PM").Single();
  516. var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
  517. var pType01 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().First();
  518. var pType02 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Last();
  519. Assert.NotEqual(pType01, pType02);
  520. var ptSym01 = model.GetDeclaredSymbol(pType01);
  521. var ptSym02 = model.GetDeclaredSymbol(pType02);
  522. // same partial type symbol
  523. Assert.Same(ptSym01, ptSym02);
  524. Assert.Equal(2, ptSym01.Locations.Length);
  525. var pMethod01 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
  526. var pMethod02 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Last();
  527. Assert.NotEqual(pMethod01, pMethod02);
  528. var pmSym01 = model.GetDeclaredSymbol(pMethod01);
  529. var pmSym02 = model.GetDeclaredSymbol(pMethod02);
  530. // different partial method symbols:(
  531. Assert.NotSame(pmSym01, pmSym02);
  532. // the declaration one is what one can get from GetMembers()
  533. Assert.Same(pMethodSym, pmSym01);
  534. // with decl|impl point to each nother
  535. Assert.Null(pmSym01.PartialDefinitionPart);
  536. Assert.Same(pmSym02, pmSym01.PartialImplementationPart);
  537. Assert.Same(pmSym01, pmSym02.PartialDefinitionPart);
  538. Assert.Null(pmSym02.PartialImplementationPart);
  539. var pParam01 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
  540. var pParam02 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Last();
  541. Assert.NotEqual(pParam01, pParam02);
  542. var ppSym01 = model.GetDeclaredSymbol(pParam01);
  543. var ppSym02 = model.GetDeclaredSymbol(pParam02);
  544. Assert.NotSame(ppSym01, ppSym02);
  545. Assert.Equal(1, ppSym01.Locations.Length);
  546. Assert.Equal(1, ppSym02.Locations.Length);
  547. }
  548. [Fact, WorkItem(544221, "DevDiv")]
  549. public void GetTypeInfoForOptionalParameterDefaultValueInDelegate()
  550. {
  551. var text = @"
  552. using System;
  553. class Test
  554. {
  555. public delegate void DFoo(byte i = 1);
  556. protected internal void MFoo(sbyte j = 2) { }
  557. }
  558. ";
  559. var tree = Parse(text);
  560. var comp = CreateCompilationWithMscorlib(tree);
  561. var model = comp.GetSemanticModel(tree);
  562. var root = tree.GetCompilationUnitRoot();
  563. var exprs = root.DescendantNodes().OfType<LiteralExpressionSyntax>().ToArray();
  564. Assert.Equal(2, exprs.Length);
  565. var type1 = model.GetTypeInfo(exprs[0]);
  566. var type2 = model.GetTypeInfo(exprs[1]);
  567. Assert.NotNull(type1.Type);
  568. Assert.Equal("System.Int32", type1.Type.ToTestDisplayString());
  569. Assert.NotNull(type2.Type);
  570. Assert.Equal("System.Int32", type2.Type.ToTestDisplayString());
  571. }
  572. [Fact, WorkItem(544231, "DevDiv")]
  573. public void GetDeclSymbolForParameterOfPartialMethod()
  574. {
  575. var text1 = @"
  576. using System;
  577. partial class Partial001
  578. {
  579. static partial void Foo(ulong x);
  580. }
  581. ";
  582. var text2 = @"
  583. using System;
  584. partial class Partial001
  585. {
  586. static partial void Foo(ulong x) { }
  587. static int Main() { return 1; }
  588. }
  589. ";
  590. var tree1 = Parse(text1);
  591. var tree2 = Parse(text2);
  592. var comp = CreateCompilationWithMscorlib(new List<SyntaxTree> {tree1, tree2});
  593. var model1 = comp.GetSemanticModel(tree1);
  594. var model2 = comp.GetSemanticModel(tree2);
  595. var root1 = tree1.GetCompilationUnitRoot();
  596. var root2 = tree1.GetCompilationUnitRoot();
  597. var para1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
  598. var para2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
  599. var sym1 = model1.GetDeclaredSymbol(para1);
  600. var sym2 = model2.GetDeclaredSymbol(para2);
  601. Assert.NotNull(sym1);
  602. Assert.NotNull(sym2);
  603. Assert.Equal("System.UInt64 x", sym1.ToTestDisplayString());
  604. Assert.Equal("System.UInt64 x", sym2.ToTestDisplayString());
  605. Assert.NotEqual(sym1.Locations[0], sym2.Locations[0]);
  606. }
  607. [Fact, WorkItem(544473, "DevDiv")]
  608. public void GetDeclSymbolForTypeParameterOfPartialMethod()
  609. {
  610. var text1 = @"
  611. using System;
  612. partial class Partial001
  613. {
  614. static partial void Foo<T>(T x);
  615. }
  616. ";
  617. var text2 = @"
  618. using System;
  619. partial class Partial001
  620. {
  621. static partial void Foo<T>(T x) { }
  622. static int Main() { return 1; }
  623. }
  624. ";
  625. var tree1 = Parse(text1);
  626. var tree2 = Parse(text2);
  627. var comp = CreateCompilationWithMscorlib(new List<SyntaxTree> { tree1, tree2 });
  628. var model1 = comp.GetSemanticModel(tree1);
  629. var model2 = comp.GetSemanticModel(tree2);
  630. var root1 = tree1.GetCompilationUnitRoot();
  631. var root2 = tree1.GetCompilationUnitRoot();
  632. var para1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType<TypeParameterSyntax>().First();
  633. var para2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType<TypeParameterSyntax>().First();
  634. var sym1 = model1.GetDeclaredSymbol(para1);
  635. var sym2 = model2.GetDeclaredSymbol(para2);
  636. Assert.NotNull(sym1);
  637. Assert.NotNull(sym2);
  638. Assert.Equal("T", sym1.ToTestDisplayString());
  639. Assert.Equal("T", sym2.ToTestDisplayString());
  640. Assert.NotEqual(sym1.Locations[0], sym2.Locations[0]);
  641. }
  642. [Fact]
  643. public void GetDeclaredSymbolForAnonymousTypeProperty01()
  644. {
  645. var text = @"
  646. using System;
  647. struct AnonTypeTest
  648. {
  649. static long Prop
  650. {
  651. get
  652. {
  653. short @short = -1;
  654. var anonType = new { id = 123, @do = ""QC"", @short, Prop };
  655. return anonType.id + anonType.@short;
  656. }
  657. }
  658. }
  659. ";
  660. var tree = Parse(text);
  661. var comp = CreateCompilationWithMscorlib(tree);
  662. var model = comp.GetSemanticModel(tree);
  663. var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
  664. Assert.Equal(4, anonProps.Count());
  665. var symList = from ap in anonProps
  666. let apsym = model.GetDeclaredSymbol(ap)
  667. orderby apsym.Name
  668. select apsym.Name;
  669. var results = string.Join(", ", symList);
  670. Assert.Equal("do, id, Prop, short", results);
  671. }
  672. [Fact]
  673. public void GetDeclaredSymbolForAnonymousTypeProperty02()
  674. {
  675. var text = @"
  676. using System;
  677. class AnonTypeTest
  678. {
  679. long field = 111;
  680. void M(byte p1, ref sbyte p2, out string p3, params string[] ary)
  681. {
  682. ulong local = 12345;
  683. var anonType = new { local, this.field, p1, p2, ary };
  684. p3 = anonType.ary.Length > 0 ? anonType.ary[0] : """";
  685. }
  686. }
  687. ";
  688. var tree = Parse(text);
  689. var comp = CreateCompilationWithMscorlib(tree);
  690. var model = comp.GetSemanticModel(tree);
  691. var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
  692. Assert.Equal(5, anonProps.Count());
  693. var symList = from ap in anonProps
  694. let apsym = model.GetDeclaredSymbol(ap)
  695. orderby apsym.Name
  696. select apsym.Name;
  697. var results = string.Join(", ", symList);
  698. Assert.Equal("ary, field, local, p1, p2", results);
  699. }
  700. [Fact]
  701. public void GetDeclaredSymbolForAnonymousTypeProperty03()
  702. {
  703. var text = @"
  704. using System;
  705. enum E { a, b, c }
  706. class Base
  707. {
  708. protected E baseField = E.b;
  709. protected virtual Base BaseProp { get { return this; } }
  710. public Func<string, char> deleField;
  711. }
  712. class AnonTypeTest : Base
  713. {
  714. protected override Base BaseProp { get { return null; } }
  715. char this[string @string]
  716. {
  717. get
  718. {
  719. var anonType = new { id = deleField, base.BaseProp, base.baseField, ret = @string };
  720. return anonType.id(anonType.ret);
  721. }
  722. }
  723. }
  724. ";
  725. var tree = Parse(text);
  726. var comp = CreateCompilationWithMscorlib(tree);
  727. var model = comp.GetSemanticModel(tree);
  728. var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
  729. Assert.Equal(4, anonProps.Count());
  730. var symList = from ap in anonProps
  731. let apsym = model.GetDeclaredSymbol(ap)
  732. orderby apsym.Name
  733. select apsym.Name;
  734. var results = string.Join(", ", symList);
  735. Assert.Equal("baseField, BaseProp, id, ret", results);
  736. }
  737. [Fact]
  738. public void GetDeclaredSymbolForAnonymousTypeProperty04()
  739. {
  740. var text = @"
  741. using System;
  742. enum E { a, b, c }
  743. struct S
  744. {
  745. public static E sField;
  746. public interface IFoo { }
  747. public IFoo GetFoo { get; set; }
  748. public IFoo GetFoo2() { return null; }
  749. }
  750. class AnonTypeTest
  751. {
  752. event Action<ushort> Eve
  753. {
  754. add
  755. {
  756. var anonType = new { a1 = new { S.sField, ifoo = new { new S().GetFoo } } };
  757. }
  758. remove
  759. {
  760. var anonType = new { a1 = new { a2 = new { a2 = S.sField, a3 = new { a3 = new S().GetFoo2() } } } };
  761. }
  762. }
  763. }
  764. ";
  765. var tree = Parse(text);
  766. var comp = CreateCompilationWithMscorlib(tree);
  767. var model = comp.GetSemanticModel(tree);
  768. var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
  769. Assert.Equal(9, anonProps.Count());
  770. var symList = from ap in anonProps
  771. let apsym = model.GetDeclaredSymbol(ap)
  772. orderby apsym.Name
  773. select apsym.Name;
  774. var results = string.Join(", ", symList);
  775. Assert.Equal("a1, a1, a2, a2, a3, a3, GetFoo, ifoo, sField", results);
  776. }
  777. [Fact(), WorkItem(542861, "DevDiv"), WorkItem(529673, "DevDiv")]
  778. public void GetSymbolInfoForAccessorParameters()
  779. {
  780. var text = @"
  781. using System;
  782. public class Test
  783. {
  784. object[] _Items = new object[3];
  785. public object this[int index]
  786. {
  787. get
  788. {
  789. return _Items[index];
  790. }
  791. set
  792. {
  793. _Items[index] = value;
  794. }
  795. }
  796. }
  797. ";
  798. var tree = Parse(text);
  799. var comp = CreateCompilationWithMscorlib(tree);
  800. var model = comp.GetSemanticModel(tree);
  801. var descendants = tree.GetCompilationUnitRoot().DescendantNodes();
  802. var paras = descendants.OfType<ParameterSyntax>();
  803. Assert.Equal(1, paras.Count());
  804. var parasym = model.GetDeclaredSymbol(paras.First());
  805. var ploc = parasym.Locations[0];
  806. var args = descendants.OfType<ArgumentSyntax>().Where(s => s.ToString() == "index").Select(s => s);
  807. Assert.Equal(2, args.Count());
  808. var argsym1 = model.GetSymbolInfo(args.First().Expression).Symbol;
  809. var argsym2 = model.GetSymbolInfo(args.Last().Expression).Symbol;
  810. Assert.NotNull(argsym1);
  811. Assert.NotNull(argsym2);
  812. Assert.Equal(ploc, argsym1.Locations[0]);
  813. Assert.Equal(ploc, argsym2.Locations[0]);
  814. Assert.Equal(parasym.Kind, argsym1.Kind);
  815. Assert.Equal(parasym.Kind, argsym2.Kind);
  816. // SourceSimpleParameterSymbol vs. SourceClonedComplexParameterSymbol
  817. Assert.NotEqual(parasym, argsym1);
  818. Assert.NotEqual(parasym, argsym2);
  819. }
  820. [WorkItem(545648, "DevDiv")]
  821. [Fact]
  822. public void AliasDeclaredSymbolWithConflict()
  823. {
  824. var source = @"
  825. using X = System;
  826. class X { }
  827. ";
  828. var comp = CreateCompilationWithMscorlib(source);
  829. var tree = comp.SyntaxTrees.Single();
  830. var model = comp.GetSemanticModel(tree);
  831. var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingDirectiveSyntax>().Single();
  832. var symbol = model.GetDeclaredSymbol(aliasSyntax);
  833. Assert.Equal(symbol.Target, comp.GlobalNamespace.GetMember<NamespaceSymbol>("System"));
  834. comp.VerifyDiagnostics(
  835. // (2,1): info CS8019: Unnecessary using directive.
  836. // using X = System;
  837. Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using X = System;"));
  838. }
  839. [WorkItem(529751, "DevDiv")]
  840. [Fact]
  841. public void ExternAlias()
  842. {
  843. var source = @"
  844. extern alias X;
  845. class Test
  846. {
  847. static void Main()
  848. {
  849. X::C c = null;
  850. }
  851. }
  852. ";
  853. var comp1 = CreateCompilationWithMscorlib("public class C { }");
  854. var ref1 = new MetadataImageReference(CompileAndVerify(comp1).EmittedAssemblyData, aliases: ImmutableArray.Create("X"));
  855. var comp2 = CreateCompilationWithMscorlib(source, new[] { ref1 });
  856. var tree = comp2.SyntaxTrees.Single();
  857. var model = comp2.GetSemanticModel(tree);
  858. var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single();
  859. // Compilation.GetExternAliasTarget defines this behavior: the target is a merged namespace
  860. // with the same name as the alias, contained in the global namespace of the compilation.
  861. var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax);
  862. var aliasTarget = (NamespaceSymbol)aliasSymbol.Target;
  863. Assert.Equal(NamespaceKind.Module, aliasTarget.Extent.Kind);
  864. Assert.Equal("", aliasTarget.Name);
  865. Assert.True(aliasTarget.IsGlobalNamespace);
  866. Assert.Null(aliasTarget.ContainingNamespace);
  867. Assert.Equal(0, comp2.GlobalNamespace.GetMembers("X").Length); //Doesn't contain the alias target namespace as a child.
  868. var aliasQualifiedSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AliasQualifiedNameSyntax>().Single();
  869. Assert.Equal(aliasSymbol, model.GetAliasInfo(aliasQualifiedSyntax.Alias));
  870. comp2.VerifyDiagnostics(
  871. // (8,14): warning CS0219: The variable 'c' is assigned but its value is never used
  872. // X::C c = null;
  873. Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c"));
  874. }
  875. [Fact, WorkItem(546687, "DevDiv"), WorkItem(529751, "DevDiv")]
  876. public void ExternAliasWithoutTarget()
  877. {
  878. var source = @"
  879. extern alias X;
  880. class Test
  881. {
  882. static void Main()
  883. {
  884. X::C c = null;
  885. }
  886. }
  887. ";
  888. var comp = CreateCompilationWithMscorlib(source);
  889. var tree = comp.SyntaxTrees.Single();
  890. var model = comp.GetSemanticModel(tree);
  891. var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single();
  892. var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax);
  893. Assert.IsType<MissingNamespaceSymbol>(aliasSymbol.Target);
  894. var aliasQualifiedSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AliasQualifiedNameSyntax>().Single();
  895. Assert.Equal(aliasSymbol, model.GetAliasInfo(aliasQualifiedSyntax.Alias));
  896. comp.VerifyDiagnostics(
  897. // (2,14): error CS0430: The extern alias 'X' was not specified in a /reference option
  898. // extern alias X;
  899. Diagnostic(ErrorCode.ERR_BadExternAlias, "X").WithArguments("X"),
  900. // (8,12): error CS0234: The type or namespace name 'C' does not exist in the namespace 'X' (are you missing an assembly reference?)
  901. // X::C c = null;
  902. Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C").WithArguments("C", "X"));
  903. }
  904. [WorkItem(545648, "DevDiv")]
  905. [Fact]
  906. public void UsingDirectiveAliasSemanticInfo()
  907. {
  908. var source = "using X = System;";
  909. var comp = CreateCompilationWithMscorlib(source);
  910. comp.VerifyDiagnostics(
  911. // (1,1): info CS8019: Unnecessary using directive.
  912. // using X = System;
  913. Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using X = System;"));
  914. var tree = comp.SyntaxTrees.Single();
  915. var model = comp.GetSemanticModel(tree);
  916. var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<NameEqualsSyntax>().Single().Name;
  917. Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(aliasSyntax));
  918. var usingSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingDirectiveSyntax>().Single();
  919. Assert.Equal(SymbolKind.Alias, model.GetDeclaredSymbol(usingSyntax).Kind);
  920. }
  921. [WorkItem(545882, "DevDiv")]
  922. [Fact]
  923. public void SpeculativelyBindConstructorInitializerInPlaceOfActual()
  924. {
  925. var source = @"class C
  926. {
  927. C(int x) { }
  928. C() : this((int) 1) { }
  929. }";
  930. var comp = CreateCompilationWithMscorlib(source);
  931. comp.VerifyDiagnostics();
  932. var tree = comp.SyntaxTrees.Single();
  933. var model = comp.GetSemanticModel(tree);
  934. var oldSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
  935. var newSyntax = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer);
  936. var info = model.GetSpeculativeSymbolInfo(oldSyntax.SpanStart, newSyntax);
  937. var symbol = info.Symbol;
  938. Assert.NotNull(symbol);
  939. Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"), symbol.ContainingType);
  940. Assert.Equal(SymbolKind.Method, symbol.Kind);
  941. var method = (MethodSymbol)symbol;
  942. Assert.Equal(MethodKind.Constructor, method.MethodKind);
  943. Assert.Equal(0, method.ParameterCount);
  944. }
  945. [WorkItem(545882, "DevDiv")]
  946. [Fact]
  947. public void SpeculativelyBindConstructorInitializerInNewLocation()
  948. {
  949. var source = @"class C
  950. {
  951. C() { }
  952. }";
  953. var comp = CreateCompilationWithMscorlib(source);
  954. comp.VerifyDiagnostics();
  955. var tree = comp.SyntaxTrees.Single();
  956. var model = comp.GetSemanticModel(tree);
  957. var oldSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
  958. var newSyntax = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer);
  959. var info = model.GetSpeculativeSymbolInfo(oldSyntax.ParameterList.Span.End, newSyntax);
  960. Assert.Equal(SymbolInfo.None, info);
  961. }
  962. [Fact]
  963. public void TestGetSpeculativeSemanticModelInFieldInitializer()
  964. {
  965. var compilation = CreateCompilationWithMscorlib(@"
  966. class C
  967. {
  968. object y = 1;
  969. }
  970. ");
  971. var tree = compilation.SyntaxTrees[0];
  972. var root = tree.GetCompilationUnitRoot();
  973. var typeDecl = (TypeDeclarationSyntax)root.Members[0];
  974. var fieldDecl = (FieldDeclarationSyntax)typeDecl.Members[0];
  975. var varDecl = fieldDecl.Declaration.Variables.First();
  976. var model = compilation.GetSemanticModel(tree);
  977. Assert.False(model.IsSpeculativeSemanticModel);
  978. Assert.Null(model.ParentModel);
  979. Assert.Equal(0, model.OriginalPositionForSpeculation);
  980. // Speculate on the equals value syntax (initializer)
  981. // Conversion info available, ConvertedType: Object.
  982. var equalsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression(@"(string)""Hello"""));
  983. var expr = equalsValue.Value;
  984. int position = varDecl.Initializer.SpanStart;
  985. SemanticModel speculativeModel;
  986. bool success = model.TryGetSpeculativeSemanticModel(position, equalsValue, out speculativeModel);
  987. Assert.True(success);
  988. Assert.NotNull(speculativeModel);
  989. Assert.True(speculativeModel.IsSpeculativeSemanticModel);
  990. Assert.Equal(model, speculativeModel.ParentModel);
  991. Assert.Equal(position, speculativeModel.OriginalPositionForSpeculation);
  992. var typeInfo = speculativeModel.GetTypeInfo(expr);
  993. Assert.NotNull(typeInfo.Type);
  994. Assert.Equal("String", typeInfo.Type.Name);
  995. Assert.Equal("Object", typeInfo.ConvertedType.Name);
  996. var constantInfo = speculativeModel.GetConstantValue(expr);
  997. Assert.True(constantInfo.HasValue, "must be a constant");
  998. Assert.Equal("Hello", constantInfo.Value);
  999. }
  1000. [Fact]
  1001. public void TestGetSpeculativeSemanticModelInEnumMember()
  1002. {
  1003. var compilation = CreateCompilationWithMscorlib(@"
  1004. enum C
  1005. {
  1006. y = 1
  1007. }
  1008. ");
  1009. var tree = compilation.SyntaxTrees[0];
  1010. var root = tree.GetCompilationUnitRoot();
  1011. var typeDecl = (EnumDeclarationSyntax)root.Members[0];
  1012. var enumMemberDecl = (EnumMemberDeclarationSyntax)typeDecl.Members[0];
  1013. var equalsValue = enumMemberDecl.EqualsValue;
  1014. var initializer = equalsValue.Value;
  1015. var model = compilation.GetSemanticModel(tree);
  1016. // Speculate on the equals value syntax (initializer)
  1017. // Conversion info available, ConvertedType: Int32.
  1018. var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("(short)0"));
  1019. var expr = newEqualsValue.Value;
  1020. SemanticModel speculativeModel;
  1021. bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
  1022. Assert.True(success);
  1023. Assert.NotNull(speculativeModel);
  1024. var typeInfo = speculativeModel.GetTypeInfo(expr);
  1025. Assert.NotNull(typeInfo.Type);
  1026. Assert.Equal("Int16", typeInfo.Type.Name);
  1027. Assert.Equal("Int32", typeInfo.ConvertedType.Name);
  1028. var constantInfo = speculativeModel.GetConstantValue(expr);
  1029. Assert.True(constantInfo.HasValue, "must be a constant");
  1030. Assert.Equal((short)0, constantInfo.Value);
  1031. }
  1032. [Fact]
  1033. [WorkItem(648305, "DevDiv")]
  1034. public void TestGetSpeculativeSemanticModelInDefaultValueArgument()
  1035. {
  1036. var compilation = CreateCompilationWithMscorlib(@"
  1037. class C
  1038. {
  1039. void M(int x = 1)
  1040. {
  1041. string y = ""Hello"";
  1042. }
  1043. }
  1044. ");
  1045. var tree = compilation.SyntaxTrees[0];
  1046. var root = tree.GetCompilationUnitRoot();
  1047. var typeDecl = (TypeDeclarationSyntax)root.Members[0];
  1048. var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
  1049. var equalsValue = methodDecl.ParameterList.Parameters[0].Default;
  1050. var paramDefaultArg = equalsValue.Value;
  1051. var model = compilation.GetSemanticModel(tree);
  1052. var ti = model.GetTypeInfo(paramDefaultArg);
  1053. // Speculate on the equals value syntax (initializer)
  1054. // Conversion info available, ConvertedType: Int32.
  1055. var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("(short)0"));
  1056. var expr = newEqualsValue.Value;
  1057. SemanticModel speculativeModel;
  1058. bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
  1059. Assert.True(success);
  1060. Assert.NotNull(speculativeModel);
  1061. var typeInfo = speculativeModel.GetTypeInfo(expr);
  1062. Assert.NotNull(typeInfo.Type);
  1063. Assert.Equal("Int16", typeInfo.Type.Name);
  1064. Assert.Equal("Int32", typeInfo.ConvertedType.Name);
  1065. var constantInfo = speculativeModel.GetConstantValue(expr);
  1066. Assert.True(constantInfo.HasValue, "must be a constant");
  1067. Assert.Equal((short)0, constantInfo.Value);
  1068. }
  1069. [Fact]
  1070. [WorkItem(746002, "DevDiv")]
  1071. public void TestGetSpeculativeSemanticModelInDefaultValueArgument2()
  1072. {
  1073. var compilation = CreateCompilationWithMscorlib(@"
  1074. using System;
  1075. enum E
  1076. {
  1077. A = 1,
  1078. B = 2
  1079. }
  1080. interface I
  1081. {
  1082. void M1(E e = E.A);
  1083. }
  1084. ");
  1085. var tree = compilation.SyntaxTrees[0];
  1086. var root = tree.GetCompilationUnitRoot();
  1087. var interfaceDecl = (TypeDeclarationSyntax)root.Members[1];
  1088. var methodDecl = (MethodDeclarationSyntax)interfaceDecl.Members[0];
  1089. var param = methodDecl.ParameterList.Parameters[0];
  1090. var equalsValue = param.Default;
  1091. var paramDefaultArg = equalsValue.Value;
  1092. var model = compilation.GetSemanticModel(tree);
  1093. // Speculate on the equals value syntax (initializer) with a non-null parent
  1094. var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("E.B | E.A"));
  1095. newEqualsValue = param.ReplaceNode(equalsValue, newEqualsValue).Default;
  1096. var binaryExpr = newEqualsValue.Value;
  1097. SemanticModel speculativeModel;
  1098. bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
  1099. Assert.True(success);
  1100. Assert.NotNull(speculativeModel);
  1101. var typeInfo = speculativeModel.GetTypeInfo(binaryExpr);
  1102. Assert.NotNull(typeInfo.Type);
  1103. Assert.Equal("E", typeInfo.Type.Name);
  1104. Assert.Equal("E", typeInfo.ConvertedType.Name);
  1105. }
  1106. [Fact]
  1107. [WorkItem(657701, "DevDiv")]
  1108. public void TestGetSpeculativeSemanticModelInConstructorDefaultValueArgument()
  1109. {
  1110. var compilation = CreateCompilationWithMscorlib(@"
  1111. class C
  1112. {
  1113. C(int x = 1)
  1114. {
  1115. string y = ""Hello"";
  1116. }
  1117. }
  1118. ");
  1119. var tree = compilation.SyntaxTrees[0];
  1120. var root = tree.GetCompilationUnitRoot();
  1121. var typeDecl = (TypeDeclarationSyntax)root.Members[0];
  1122. var constructorDecl = (ConstructorDeclarationSyntax)typeDecl.Members[0];
  1123. var equalsValue = constructorDecl.ParameterList.Parameters[0].Default;
  1124. var paramDefaultArg = equalsValue.Value;
  1125. var model = compilation.GetSemanticModel(tree);
  1126. var ti = model.GetTypeInfo(paramDefaultArg);
  1127. // Speculate on the equals value syntax (initializer)
  1128. // Conversion info available, ConvertedType: Int32.
  1129. var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("(short)0"));
  1130. var expr = newEqualsValue.Value;
  1131. SemanticModel speculativeModel;
  1132. bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
  1133. Assert.True(success);
  1134. Assert.NotNull(speculativeModel);
  1135. var typeInfo = speculativeModel.GetTypeInfo(expr);
  1136. Assert.NotNull(typeInfo.Type);
  1137. Assert.Equal("Int16", typeInfo.Type.Name);
  1138. Assert.Equal("Int32", typeInfo.ConvertedType.Name);
  1139. var constantInfo = speculativeModel.GetConstantValue(expr);
  1140. Assert.True(constantInfo.HasValue, "must be a constant");
  1141. Assert.Equal((short)0, constantInfo.Value);
  1142. }
  1143. [WorkItem(529893, "DevDiv")]
  1144. [Fact]
  1145. public void AliasCalledVar()
  1146. {
  1147. var source = @"
  1148. using var = Q;
  1149. class Q
  1150. {
  1151. var q;
  1152. }
  1153. ";
  1154. var comp = CreateCompilationWithMscorlib(source);
  1155. comp.VerifyDiagnostics(
  1156. // (6,9): warning CS0169: The field 'Q.q' is never used
  1157. // var q;
  1158. Diagnostic(ErrorCode.WRN_UnreferencedField, "q").WithArguments("Q.q"));
  1159. var classQ = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Q");
  1160. var fieldQ = classQ.GetMember<FieldSymbol>("q");
  1161. Assert.Equal(classQ, fieldQ.Type);
  1162. var tree = comp.SyntaxTrees.Single();
  1163. var model = comp.GetSemanticModel(tree);
  1164. var aliasDecl = tree.GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>().Single();

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