PageRenderTime 149ms CodeModel.GetById 3ms app.highlight 125ms RepoModel.GetById 1ms app.codeStats 1ms

/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
   1// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
   2
   3using System;
   4using System.Collections.Generic;
   5using System.Collections.Immutable;
   6using System.Linq;
   7using Microsoft.CodeAnalysis.CSharp.Symbols;
   8using Microsoft.CodeAnalysis.CSharp.Syntax;
   9using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
  10using Microsoft.CodeAnalysis.Test.Utilities;
  11using Microsoft.CodeAnalysis.Text;
  12using Roslyn.Test.Utilities;
  13using Xunit;
  14
  15namespace Microsoft.CodeAnalysis.CSharp.UnitTests
  16{
  17    public class SemanticTests : CSharpTestBase
  18    {
  19        [Fact]
  20        public void LocalSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilation()
  21        {
  22            var text = @"public class C { public void M() { int x = 10; } }";
  23            var tree = Parse(text);
  24            var comp = CreateCompilationWithMscorlib(tree); 
  25
  26            var model1 = comp.GetSemanticModel(tree);
  27            var model2 = comp.GetSemanticModel(tree);
  28            Assert.NotEqual(model1, model2);
  29
  30            var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First();
  31            var symbol1 = model1.GetDeclaredSymbol(vardecl);
  32            var symbol2 = model2.GetDeclaredSymbol(vardecl);
  33
  34            Assert.NotSame(symbol1, symbol2);
  35            Assert.Equal(symbol1, symbol2);
  36        }
  37
  38        [Fact]
  39        public void LocalSymbolsAreDifferentArossSemanticModelsFromDifferentCompilations()
  40        {
  41            var text = @"public class C { public void M() { int x = 10; } }";
  42            var tree = Parse(text);
  43            var comp1 = CreateCompilationWithMscorlib(tree);
  44            var comp2 = CreateCompilationWithMscorlib(tree);
  45
  46            var model1 = comp1.GetSemanticModel(tree);
  47            var model2 = comp2.GetSemanticModel(tree);
  48            Assert.NotEqual(model1, model2);
  49
  50            var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First();
  51            var symbol1 = model1.GetDeclaredSymbol(vardecl);
  52            var symbol2 = model2.GetDeclaredSymbol(vardecl);
  53
  54            Assert.NotSame(symbol1, symbol2);
  55            Assert.NotEqual(symbol1, symbol2);
  56        }
  57
  58        [Fact]
  59        public void RangeVariableSymbolsAreEquivalentAcrossSemanticModelsFromTheSameCompilation()
  60        {
  61            var text = @"using System.Linq; public class C { public void M() { var q = from c in string.Empty select c; } }";
  62            var tree = Parse(text);
  63            var comp = CreateCompilationWithMscorlibAndSystemCore(new[] { tree });
  64
  65            var model1 = comp.GetSemanticModel(tree);
  66            var model2 = comp.GetSemanticModel(tree);
  67            Assert.NotEqual(model1, model2);
  68
  69            var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryClauseSyntax>().First();
  70            var symbol1 = model1.GetDeclaredSymbol(vardecl);
  71            var symbol2 = model2.GetDeclaredSymbol(vardecl);
  72
  73            Assert.NotSame(symbol1, symbol2);
  74            Assert.Equal(symbol1, symbol2);
  75        }
  76
  77        [Fact]
  78        public void RangeVariableSymbolsAreDifferentArossSemanticModelsFromDifferentCompilations()
  79        {
  80            var text = @"using System.Linq; public class C { public void M() { var q = from c in string.Empty select c; } }";
  81            var tree = Parse(text);
  82            var comp1 = CreateCompilationWithMscorlibAndSystemCore(new[] { tree });
  83            var comp2 = CreateCompilationWithMscorlibAndSystemCore(new[] { tree });
  84
  85            var model1 = comp1.GetSemanticModel(tree);
  86            var model2 = comp2.GetSemanticModel(tree);
  87            Assert.NotEqual(model1, model2);
  88
  89            var vardecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryClauseSyntax>().First();
  90            var symbol1 = model1.GetDeclaredSymbol(vardecl);
  91            var symbol2 = model2.GetDeclaredSymbol(vardecl);
  92
  93            Assert.NotSame(symbol1, symbol2);
  94            Assert.NotEqual(symbol1, symbol2);
  95        }
  96
  97        [Fact]
  98        public void LabelSymbolsAreEquivalentAcrossSemanticModelsFromSameCompilation()
  99        {
 100            var text = @"public class C { public void M() { label: goto label; } }";
 101            var tree = Parse(text);
 102            var comp = CreateCompilationWithMscorlib(tree);
 103
 104            var model1 = comp.GetSemanticModel(tree);
 105            var model2 = comp.GetSemanticModel(tree);
 106            Assert.NotEqual(model1, model2);
 107
 108            var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<GotoStatementSyntax>().First();
 109            var symbol1 = model1.GetSymbolInfo(statement.Expression).Symbol;
 110            var symbol2 = model2.GetSymbolInfo(statement.Expression).Symbol;
 111
 112            Assert.Equal(false, ReferenceEquals(symbol1, symbol2));
 113            Assert.Equal(symbol1, symbol2);
 114        }
 115
 116        [Fact]
 117        public void LambdaParameterSymbolsAreEquivalentAcrossSemanticModelsFromSameCompilation()
 118        {
 119            var text = @"using System; public class C { public void M() { Func<int,int> f = (p) => p; } }";
 120            var tree = Parse(text);
 121            var comp = CreateCompilationWithMscorlib(tree);
 122
 123            var model1 = comp.GetSemanticModel(tree);
 124            var model2 = comp.GetSemanticModel(tree);
 125            Assert.NotEqual(model1, model2);
 126
 127            var paramdecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
 128            var symbol1 = model1.GetDeclaredSymbol(paramdecl);
 129            var symbol2 = model2.GetDeclaredSymbol(paramdecl);
 130
 131            Assert.NotSame(symbol1, symbol2);
 132            Assert.Equal(symbol1.ContainingSymbol, symbol2.ContainingSymbol);
 133            Assert.Equal(symbol1, symbol2);
 134        }
 135
 136        [Fact]
 137        public void LambdaParameterSymbolsAreDifferentAcrossSemanticModelsFromDifferentCompilations()
 138        {
 139            var text = @"using System; public class C { public void M() { Func<int,int> f = (p) => p; } }";
 140            var tree1 = Parse(text);
 141            var tree2 = Parse(text);
 142            var comp1 = CreateCompilationWithMscorlib(tree1);
 143            var comp2 = CreateCompilationWithMscorlib(tree2);
 144
 145            var model1 = comp1.GetSemanticModel(tree1);
 146            var model2 = comp2.GetSemanticModel(tree2);
 147            Assert.NotEqual(model1, model2);
 148
 149            var paramdecl1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
 150            var symbol1 = model1.GetDeclaredSymbol(paramdecl1);
 151            var paramdecl2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
 152            var symbol2 = model2.GetDeclaredSymbol(paramdecl2);
 153
 154            Assert.NotSame(symbol1, symbol2);
 155            Assert.NotEqual(symbol1.ContainingSymbol, symbol2.ContainingSymbol);
 156            Assert.NotEqual(symbol1, symbol2);
 157        }
 158
 159        [WorkItem(539740, "DevDiv")]
 160        [Fact]
 161        public void NamespaceWithoutName()
 162        {
 163            var text = "namespace";
 164            var tree = Parse(text);
 165            var comp = CreateCompilationWithMscorlib(tree);
 166            var model = comp.GetSemanticModel(tree);
 167            var errors = comp.GetDiagnostics().ToArray();
 168            Assert.Equal(3, errors.Length);
 169
 170            var nsArray = tree.GetCompilationUnitRoot().DescendantNodes().Where(node => node.IsKind(SyntaxKind.NamespaceDeclaration)).ToArray();
 171            Assert.Equal(1, nsArray.Length);
 172
 173            var nsSyntax = nsArray[0] as NamespaceDeclarationSyntax;
 174            var symbol = model.GetDeclaredSymbol(nsSyntax);
 175            Assert.Equal(string.Empty, symbol.Name);
 176        }
 177
 178        [Fact]
 179        public void LazyBoundUsings1()
 180        {
 181            var text =
 182@"
 183// Peter Golde[7/19/2010]: I managed to construct the following interesting example today,
 184// which Dev10 does compile. Interestingly, the resolution of one “using” can depend
 185// on the resolution of another “using” later in the same namespace.
 186using K = A.Q;
 187using L = B.R;
 188 
 189class B
 190{
 191    public class R
 192    {
 193        public class Q
 194        {
 195            public class S : K { }
 196        }
 197    }
 198}
 199 
 200class A : L
 201{
 202    public K.S v = null;
 203}
 204";
 205            var comp = CreateCompilationWithMscorlib(text);
 206            var global = comp.GlobalNamespace;
 207            var a = global.GetTypeMembers("A", 0).Single();
 208            var abase = a.BaseType;
 209            Assert.Equal("B.R", abase.ToTestDisplayString());
 210
 211            var b = global.GetTypeMembers("B", 0).Single();
 212            var r = b.GetTypeMembers("R", 0).Single();
 213            var q = r.GetTypeMembers("Q", 0).Single();
 214            var v = a.GetMembers("v").Single() as FieldSymbol;
 215            var s = v.Type;
 216            Assert.Equal("B.R.Q.S", s.ToTestDisplayString());
 217            var sbase = s.BaseType;
 218            Assert.Equal("B.R.Q", sbase.ToTestDisplayString());
 219        }
 220
 221        [Fact]
 222        public void Diagnostics1()
 223        {
 224            var text =
 225@"
 226class A : A {}
 227";
 228            var tree = Parse(text);
 229            var comp = CreateCompilationWithMscorlib(tree);
 230
 231            var errs = comp.GetSemanticModel(tree).GetDeclarationDiagnostics();
 232            Assert.Equal(1, errs.Count());
 233        }
 234
 235        [Fact]
 236        public void DiagnosticsInOneTree()
 237        {
 238            var partial1 =
 239@"
 240partial class A 
 241{ 
 242    void foo() { int x = y; }
 243}
 244
 245class C : B {}
 246";
 247
 248            var partial2 =
 249@"
 250partial class A 
 251{ 
 252    int q;      //an unused field in a partial type
 253    void bar() { int x = z; }
 254}
 255
 256class B : NonExistent {}
 257";
 258
 259            var partial1Tree = Parse(partial1);
 260            var partial2Tree = Parse(partial2);
 261            var comp = CreateCompilationWithMscorlib(new SyntaxTree[] { partial1Tree, partial2Tree });
 262
 263            var errs = comp.GetSemanticModel(partial1Tree).GetDiagnostics();
 264            Assert.Equal(1, errs.Count());
 265        }
 266
 267        [Fact]
 268        public void Bindings1()
 269        {
 270            var text =
 271@"
 272class B : A {}
 273class A {}
 274";
 275            var tree = Parse(text);
 276            var comp = CreateCompilationWithMscorlib(tree);
 277
 278            var bdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 279            var bbase = bdecl.BaseList.Types[0] as TypeSyntax;
 280            var model = comp.GetSemanticModel(tree);
 281
 282            var info = model.GetSymbolInfo(bbase);
 283            Assert.NotNull(info.Symbol);
 284            var a = comp.GlobalNamespace.GetTypeMembers("A", 0).Single();
 285            Assert.Equal(a, info.Symbol);
 286            Assert.Equal(a, model.GetTypeInfo(bbase).Type);
 287        }
 288
 289        [Fact]
 290        public void BaseScope1()
 291        {
 292            // ensure the base clause is not bound in the scope of the class
 293            var text =
 294@"
 295public class C : B {}
 296public class A {
 297    public class B {}
 298}
 299public class B : A {}
 300";
 301            var tree = Parse(text);
 302            var comp = CreateCompilationWithMscorlib(tree);
 303
 304            var cdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 305            var cbase = cdecl.BaseList.Types[0] as TypeSyntax;
 306            var model = comp.GetSemanticModel(tree);
 307
 308            var info = model.GetSymbolInfo(cbase);
 309            Assert.NotNull(info.Symbol);
 310            var b = comp.GlobalNamespace.GetTypeMembers("B", 0).Single();
 311            Assert.Equal(b, info.Symbol);
 312            Assert.Equal(b, model.GetTypeInfo(cbase).Type);
 313        }
 314
 315        [Fact]
 316        public void BaseScope2()
 317        {
 318            // ensure type parameters are in scope in the base clause
 319            var text =
 320@"
 321public class C<T> : A<T> { }
 322public class A<T> : B { }
 323public class B {
 324    public class T { }
 325}
 326";
 327            var tree = Parse(text);
 328            var comp = CreateCompilationWithMscorlib(tree);
 329
 330            var cdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 331            var cbase = cdecl.BaseList.Types[0] as TypeSyntax;
 332            var model = comp.GetSemanticModel(tree);
 333
 334            var info = model.GetSymbolInfo(cbase);
 335            Assert.NotNull(info.Symbol);
 336            var cbasetype = info.Symbol as NamedTypeSymbol;
 337
 338            var c = comp.GlobalNamespace.GetTypeMembers("C", 1).Single();
 339            Assert.Equal(c.BaseType, cbasetype);
 340        }
 341
 342        [Fact]
 343        public void Bindings2()
 344        {
 345            var text =
 346@"
 347class B<T> : A<T> {}
 348class A<T> {}
 349";
 350            var tree = Parse(text);
 351            var comp = CreateCompilationWithMscorlib(tree);
 352
 353            var bdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 354            var bbase = bdecl.BaseList.Types[0] as TypeSyntax; // A<T>
 355            var model = comp.GetSemanticModel(tree);
 356
 357            var info = model.GetSymbolInfo(bbase);
 358            Assert.NotNull(info.Symbol);
 359            var at2 = info.Symbol as NamedTypeSymbol;
 360            Assert.Equal(at2, model.GetTypeInfo(bbase).Type);
 361
 362            var a = comp.GlobalNamespace.GetTypeMembers("A", 1).Single();
 363            var at = a.TypeParameters.First();
 364            var b = comp.GlobalNamespace.GetTypeMembers("B", 1).Single();
 365            var bt = b.TypeParameters.First();
 366
 367            Assert.Equal(a.OriginalDefinition, at2.OriginalDefinition);
 368            Assert.Equal(b.TypeParameters.First(), at2.TypeArguments.First());
 369        }
 370
 371        [Fact]
 372        public void Bindings3()
 373        {
 374            var text =
 375@"using System;
 376using System.Collections.Generic;
 377using System.Linq;
 378
 379class Program
 380{
 381    static Program Field;
 382}";
 383            var tree1 = Parse(text);
 384            var compilation = CreateCompilationWithMscorlib(tree1);
 385
 386            var tree2 = Parse(text);
 387            var classProgram = tree2.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 388            var staticProgramField = classProgram.Members[0] as FieldDeclarationSyntax;
 389            var program = staticProgramField.Declaration.Type;
 390            var model = compilation.GetSemanticModel(tree1);
 391
 392            Assert.Throws<ArgumentException>(() =>
 393            {
 394                // tree2 not in the compilation
 395                var lookup = model.GetSymbolInfo(program);
 396            });
 397        }
 398
 399        [Fact]
 400        public void Bindings4()
 401        {
 402            var text =
 403@"using System;
 404using System.Collections.Generic;
 405using System.Linq;
 406
 407class Program
 408{
 409    Program p;
 410    static void Main(string[] args)
 411    {
 412    }
 413}";
 414
 415            var tree1 = Parse(text);
 416            var compilation = CreateCompilationWithMscorlib(tree1);
 417
 418            var decl = tree1.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 419            var field = decl.Members[0] as FieldDeclarationSyntax;
 420            var type = field.Declaration.Type;
 421            var model = compilation.GetSemanticModel(tree1);
 422
 423            var info = model.GetSymbolInfo(type);
 424            Assert.Equal(compilation.GlobalNamespace.GetTypeMembers("Program", 0).Single(), info.Symbol);
 425        }
 426
 427        [Fact]
 428        public void Bindings5()
 429        {
 430            var text =
 431@"using System;
 432using System.Collections.Generic;
 433using System.Linq;
 434
 435class Program
 436{
 437    static void Main(string[] args)
 438    {
 439    }
 440}";
 441
 442            var tree1 = Parse(text);
 443            var tree2 = Parse(text);
 444            var compilation = CreateCompilationWithMscorlib(new SyntaxTree[] { tree1, tree2 });
 445
 446            var decl = tree1.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 447            var method = decl.Members[0] as MethodDeclarationSyntax;
 448            var type = method.ParameterList.Parameters[0].Type;
 449
 450            var model = compilation.GetSemanticModel(tree1);
 451
 452            var info = model.GetSymbolInfo(type);
 453            Assert.Equal<Symbol>(compilation.GetSpecialType(SpecialType.System_String), (info.Symbol as ArrayTypeSymbol).ElementType);
 454        }
 455
 456        [Fact]
 457        public void Speculative1()
 458        {
 459            var text =
 460@"
 461class B {
 462    object x;
 463}
 464class A {}
 465";
 466            var tree = Parse(text);
 467            var comp = CreateCompilationWithMscorlib(tree);
 468
 469            var bdecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 470            var xdecl = bdecl.Members[0] as FieldDeclarationSyntax;
 471
 472            var model = comp.GetSemanticModel(tree);
 473
 474            TypeSyntax speculate = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("A"));
 475            var symbolInfo = model.GetSpeculativeSymbolInfo(xdecl.SpanStart, speculate, SpeculativeBindingOption.BindAsTypeOrNamespace);
 476            var lookup = symbolInfo.Symbol as TypeSymbol;
 477
 478
 479            Assert.NotNull(lookup);
 480            var a = comp.GlobalNamespace.GetTypeMembers("A", 0).Single();
 481            Assert.Equal(a, lookup);
 482        }
 483
 484        [Fact]
 485        public void GetType1()
 486        {
 487            var text =
 488@"
 489class A {
 490    class B {}
 491}
 492";
 493            var tree = Parse(text);
 494            var comp = CreateCompilationWithMscorlib(tree);
 495
 496            var adecl = tree.GetCompilationUnitRoot().Members[0] as TypeDeclarationSyntax;
 497            var bdecl = adecl.Members[0] as TypeDeclarationSyntax;
 498
 499            var model = comp.GetSemanticModel(tree);
 500            var a1 = model.GetDeclaredSymbol(adecl);
 501            var b1 = model.GetDeclaredSymbol(bdecl);
 502
 503            var global = comp.GlobalNamespace;
 504            var a2 = global.GetTypeMembers("A", 0).Single();
 505            var b2 = a2.GetTypeMembers("B", 0).Single();
 506
 507            Assert.Equal(a2, a1);
 508            Assert.Equal(b2, b1);
 509        }
 510
 511        [Fact]
 512        public void DottedName()
 513        {
 514            var text =
 515@"
 516class Main {
 517  A.B x; // this refers to the B within A.
 518}
 519class A {
 520    public class B {}
 521}
 522class B {}
 523";
 524            var tree = Parse(text);
 525            var comp = CreateCompilationWithMscorlib(tree);
 526            var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
 527
 528            var root = tree.GetCompilationUnitRoot();
 529            var mainDecl = root.Members[0] as TypeDeclarationSyntax;
 530            var mainType = model.GetDeclaredSymbol(mainDecl);
 531
 532            var aDecl = root.Members[1] as TypeDeclarationSyntax;
 533            var aType = model.GetDeclaredSymbol(aDecl);
 534
 535            var abDecl = aDecl.Members[0] as TypeDeclarationSyntax;
 536            var abType = model.GetDeclaredSymbol(abDecl);
 537
 538            var bDecl = root.Members[2] as TypeDeclarationSyntax;
 539            var bType = model.GetDeclaredSymbol(bDecl);
 540
 541            var xDecl = mainDecl.Members[0] as FieldDeclarationSyntax;
 542            var xSym = mainType.GetMembers("x").Single() as FieldSymbol;
 543            Assert.Equal<ISymbol>(abType, xSym.Type);
 544            var info = model.GetSymbolInfo((xDecl.Declaration.Type as QualifiedNameSyntax).Right);
 545            Assert.Equal(abType, info.Symbol);
 546        }
 547
 548        [Fact]
 549        public void AliasQualifiedName()
 550        {
 551            var text =
 552@"
 553class B {}
 554namespace N {
 555  class C : global::B {}
 556  class B {}
 557}
 558";
 559            var tree = Parse(text);
 560            var comp = CreateCompilationWithMscorlib(tree);
 561            var model = comp.GetSemanticModel(tree);
 562
 563            var root = tree.GetCompilationUnitRoot();
 564            var nDecl = root.Members[0] as NamespaceDeclarationSyntax;
 565            var n2Decl = root.Members[1] as NamespaceDeclarationSyntax;
 566            var cDecl = n2Decl.Members[0] as TypeDeclarationSyntax;
 567            var cBase = (cDecl.BaseList.Types[0] as AliasQualifiedNameSyntax).Name;
 568
 569            var cBaseType = model.GetSymbolInfo(cBase).Symbol;
 570            var bOuter = comp.GlobalNamespace.GetTypeMembers("B", 0).Single();
 571            var bInner = (comp.GlobalNamespace.GetMembers("N").Single() as NamespaceSymbol).GetTypeMembers("B", 0).Single();
 572            Assert.Equal(bOuter, cBaseType);
 573        }
 574
 575        [Fact, WorkItem(528655, "DevDiv")]
 576        public void ErrorSymbolForInvalidCode()
 577        {
 578            var text = @"
 579public class A 
 580{
 581	int foo	{	void foo() {}	} // Error
 582	static int Main() {	return 1;    }
 583}
 584";
 585            var tree = Parse(text);
 586            var comp = CreateCompilationWithMscorlib(tree);
 587            var mems = comp.SourceModule.GlobalNamespace.GetMembers();
 588
 589            var typeA = mems.Where(s => s.Name == "A").Select(s => s);
 590            Assert.Equal(1, typeA.Count());
 591            var invalid = mems.Where(s => s.Name == "<invalid-global-code>").Select(s => s);
 592            Assert.Equal(1, invalid.Count());
 593        }
 594
 595        [Fact, WorkItem(543225, "DevDiv"), WorkItem(529057, "DevDiv")]
 596        public void MergePartialMethodAndParameterSymbols()
 597        {
 598            var text = @"
 599using System;
 600
 601partial class PC
 602{
 603    partial void PM(int pp);
 604}
 605
 606partial class PC
 607{
 608    partial void PM(int pp) {}
 609}
 610";
 611            var tree = Parse(text);
 612            var comp = CreateCompilationWithMscorlib(tree);
 613            var pTypeSym = comp.SourceModule.GlobalNamespace.GetTypeMembers("PC").Single();
 614            var pMethodSym = pTypeSym.GetMembers("PM").Single();
 615
 616            var model = (CSharpSemanticModel)comp.GetSemanticModel(tree);
 617            var pType01 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().First();
 618            var pType02 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Last();
 619            Assert.NotEqual(pType01, pType02);
 620            var ptSym01 = model.GetDeclaredSymbol(pType01);
 621            var ptSym02 = model.GetDeclaredSymbol(pType02);
 622            // same partial type symbol
 623            Assert.Same(ptSym01, ptSym02);
 624            Assert.Equal(2, ptSym01.Locations.Length);
 625
 626            var pMethod01 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
 627            var pMethod02 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Last();
 628            Assert.NotEqual(pMethod01, pMethod02);
 629
 630            var pmSym01 = model.GetDeclaredSymbol(pMethod01);
 631            var pmSym02 = model.GetDeclaredSymbol(pMethod02);
 632            // different partial method symbols:(
 633            Assert.NotSame(pmSym01, pmSym02);
 634            // the declaration one is what one can get from GetMembers()
 635            Assert.Same(pMethodSym, pmSym01);
 636
 637            // with decl|impl point to each nother
 638            Assert.Null(pmSym01.PartialDefinitionPart);
 639            Assert.Same(pmSym02, pmSym01.PartialImplementationPart);
 640
 641            Assert.Same(pmSym01, pmSym02.PartialDefinitionPart);
 642            Assert.Null(pmSym02.PartialImplementationPart);
 643
 644            var pParam01 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
 645            var pParam02 = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Last();
 646            Assert.NotEqual(pParam01, pParam02);
 647
 648            var ppSym01 = model.GetDeclaredSymbol(pParam01);
 649            var ppSym02 = model.GetDeclaredSymbol(pParam02);
 650            Assert.NotSame(ppSym01, ppSym02);
 651            Assert.Equal(1, ppSym01.Locations.Length);
 652            Assert.Equal(1, ppSym02.Locations.Length);
 653        }
 654
 655        [Fact, WorkItem(544221, "DevDiv")]
 656        public void GetTypeInfoForOptionalParameterDefaultValueInDelegate()
 657        {
 658            var text = @"
 659using System;
 660
 661class Test
 662{
 663    public delegate void DFoo(byte i = 1);
 664    protected internal void MFoo(sbyte j = 2) { }
 665}
 666";
 667            var tree = Parse(text);
 668            var comp = CreateCompilationWithMscorlib(tree);
 669            var model = comp.GetSemanticModel(tree);
 670            var root = tree.GetCompilationUnitRoot();
 671            var exprs = root.DescendantNodes().OfType<LiteralExpressionSyntax>().ToArray();
 672            Assert.Equal(2, exprs.Length);
 673
 674            var type1 = model.GetTypeInfo(exprs[0]);
 675            var type2 = model.GetTypeInfo(exprs[1]);
 676
 677            Assert.NotNull(type1.Type);
 678            Assert.Equal("System.Int32", type1.Type.ToTestDisplayString());
 679            Assert.NotNull(type2.Type);
 680            Assert.Equal("System.Int32", type2.Type.ToTestDisplayString());
 681        }
 682
 683        [Fact, WorkItem(544231, "DevDiv")]
 684        public void GetDeclSymbolForParameterOfPartialMethod()
 685        {
 686            var text1 = @"
 687using System;
 688
 689partial class Partial001
 690{
 691    static partial void Foo(ulong x);
 692}
 693";
 694
 695            var text2 = @"
 696using System;
 697
 698partial class Partial001
 699{
 700    static partial void Foo(ulong x)  {    }
 701    static int Main()  {    return 1;    }
 702}
 703";
 704            var tree1 = Parse(text1);
 705            var tree2 = Parse(text2);
 706            var comp = CreateCompilationWithMscorlib(new List<SyntaxTree> {tree1, tree2});
 707
 708            var model1 = comp.GetSemanticModel(tree1);
 709            var model2 = comp.GetSemanticModel(tree2);
 710            var root1 = tree1.GetCompilationUnitRoot();
 711            var root2 = tree1.GetCompilationUnitRoot();
 712            var para1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
 713            var para2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().First();
 714            var sym1 = model1.GetDeclaredSymbol(para1);
 715            var sym2 = model2.GetDeclaredSymbol(para2);
 716
 717            Assert.NotNull(sym1);
 718            Assert.NotNull(sym2);
 719            Assert.Equal("System.UInt64 x", sym1.ToTestDisplayString());
 720            Assert.Equal("System.UInt64 x", sym2.ToTestDisplayString());
 721            Assert.NotEqual(sym1.Locations[0], sym2.Locations[0]);
 722        }
 723
 724        [Fact, WorkItem(544473, "DevDiv")]
 725        public void GetDeclSymbolForTypeParameterOfPartialMethod()
 726        {
 727            var text1 = @"
 728using System;
 729
 730partial class Partial001
 731{
 732    static partial void Foo<T>(T x);
 733}
 734";
 735
 736            var text2 = @"
 737using System;
 738
 739partial class Partial001
 740{
 741    static partial void Foo<T>(T x)  {    }
 742    static int Main()  {    return 1;    }
 743}
 744";
 745            var tree1 = Parse(text1);
 746            var tree2 = Parse(text2);
 747            var comp = CreateCompilationWithMscorlib(new List<SyntaxTree> { tree1, tree2 });
 748
 749            var model1 = comp.GetSemanticModel(tree1);
 750            var model2 = comp.GetSemanticModel(tree2);
 751            var root1 = tree1.GetCompilationUnitRoot();
 752            var root2 = tree1.GetCompilationUnitRoot();
 753            var para1 = tree1.GetCompilationUnitRoot().DescendantNodes().OfType<TypeParameterSyntax>().First();
 754            var para2 = tree2.GetCompilationUnitRoot().DescendantNodes().OfType<TypeParameterSyntax>().First();
 755            var sym1 = model1.GetDeclaredSymbol(para1);
 756            var sym2 = model2.GetDeclaredSymbol(para2);
 757
 758            Assert.NotNull(sym1);
 759            Assert.NotNull(sym2);
 760            Assert.Equal("T", sym1.ToTestDisplayString());
 761            Assert.Equal("T", sym2.ToTestDisplayString());
 762            Assert.NotEqual(sym1.Locations[0], sym2.Locations[0]);
 763        }
 764
 765        [Fact]
 766        public void GetDeclaredSymbolForAnonymousTypeProperty01()
 767        {
 768            var text = @"
 769using System;
 770
 771struct AnonTypeTest
 772{
 773    static long Prop
 774    {
 775        get
 776        {
 777            short @short = -1;
 778            var anonType = new { id = 123, @do = ""QC"", @short, Prop };
 779            return anonType.id + anonType.@short;
 780        }
 781    }
 782}
 783";
 784            var tree = Parse(text);
 785            var comp = CreateCompilationWithMscorlib(tree);
 786            var model = comp.GetSemanticModel(tree);
 787            var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
 788            Assert.Equal(4, anonProps.Count());
 789            var symList = from ap in anonProps
 790                          let apsym = model.GetDeclaredSymbol(ap)
 791                          orderby apsym.Name
 792                          select apsym.Name;
 793
 794            var results = string.Join(", ", symList);
 795            Assert.Equal("do, id, Prop, short", results);
 796        }
 797
 798        [Fact]
 799        public void GetDeclaredSymbolForAnonymousTypeProperty02()
 800        {
 801            var text = @"
 802using System;
 803
 804class AnonTypeTest
 805{
 806    long field = 111;
 807    void M(byte p1, ref sbyte p2, out string p3, params string[] ary)
 808    {
 809        ulong local = 12345;
 810        var anonType = new { local, this.field, p1, p2, ary };
 811        p3 = anonType.ary.Length > 0 ? anonType.ary[0] : """";
 812    }
 813}
 814";
 815            var tree = Parse(text);
 816            var comp = CreateCompilationWithMscorlib(tree);
 817            var model = comp.GetSemanticModel(tree);
 818            var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
 819            Assert.Equal(5, anonProps.Count());
 820            var symList = from ap in anonProps
 821                          let apsym = model.GetDeclaredSymbol(ap)
 822                          orderby apsym.Name
 823                          select apsym.Name;
 824
 825            var results = string.Join(", ", symList);
 826            Assert.Equal("ary, field, local, p1, p2", results);
 827        }
 828
 829        [Fact]
 830        public void GetDeclaredSymbolForAnonymousTypeProperty03()
 831        {
 832            var text = @"
 833using System;
 834
 835enum E { a, b, c }
 836class Base
 837{
 838    protected E baseField = E.b;
 839    protected virtual Base BaseProp { get { return this; } }
 840    public Func<string, char> deleField;
 841}
 842
 843class AnonTypeTest : Base
 844{
 845    protected override Base BaseProp { get { return null; } }
 846    char this[string @string]
 847    {
 848        get
 849        {
 850            var anonType = new { id = deleField, base.BaseProp, base.baseField, ret = @string };
 851            return anonType.id(anonType.ret);
 852        }
 853    }
 854}
 855";
 856            var tree = Parse(text);
 857            var comp = CreateCompilationWithMscorlib(tree);
 858            var model = comp.GetSemanticModel(tree);
 859            var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
 860            Assert.Equal(4, anonProps.Count());
 861            var symList = from ap in anonProps
 862                          let apsym = model.GetDeclaredSymbol(ap)
 863                          orderby apsym.Name
 864                          select apsym.Name;
 865
 866            var results = string.Join(", ", symList);
 867            Assert.Equal("baseField, BaseProp, id, ret", results);
 868        }
 869
 870        [Fact]
 871        public void GetDeclaredSymbolForAnonymousTypeProperty04()
 872        {
 873            var text = @"
 874using System;
 875
 876enum E { a, b, c }
 877struct S
 878{
 879    public static E sField;
 880    public interface IFoo {  }
 881    public IFoo GetFoo { get; set; }
 882    public IFoo GetFoo2() { return null; }
 883}
 884
 885class AnonTypeTest
 886{
 887    event Action<ushort> Eve
 888    {
 889        add
 890        {
 891            var anonType = new { a1 = new { S.sField, ifoo = new { new S().GetFoo } } };
 892        }
 893        remove 
 894        {
 895            var anonType = new { a1 = new { a2 = new { a2 = S.sField, a3 = new { a3 = new S().GetFoo2() } } } };
 896        }
 897    }
 898}
 899";
 900            var tree = Parse(text);
 901            var comp = CreateCompilationWithMscorlib(tree);
 902            var model = comp.GetSemanticModel(tree);
 903            var anonProps = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectMemberDeclaratorSyntax>();
 904            Assert.Equal(9, anonProps.Count());
 905            var symList = from ap in anonProps
 906                          let apsym = model.GetDeclaredSymbol(ap)
 907                          orderby apsym.Name
 908                          select apsym.Name;
 909
 910            var results = string.Join(", ", symList);
 911            Assert.Equal("a1, a1, a2, a2, a3, a3, GetFoo, ifoo, sField", results);
 912        }
 913
 914        [Fact(), WorkItem(542861, "DevDiv"), WorkItem(529673, "DevDiv")]
 915        public void GetSymbolInfoForAccessorParameters()
 916        {
 917            var text = @"
 918using System;
 919
 920public class Test
 921{
 922    object[] _Items = new object[3];
 923    public object this[int index]
 924    {
 925        get
 926        {
 927            return _Items[index];
 928        }
 929        set
 930        {
 931            _Items[index] = value;
 932        }
 933    } 
 934}
 935";
 936            var tree = Parse(text);
 937            var comp = CreateCompilationWithMscorlib(tree);
 938            var model = comp.GetSemanticModel(tree);
 939            var descendants = tree.GetCompilationUnitRoot().DescendantNodes();
 940
 941            var paras = descendants.OfType<ParameterSyntax>();
 942            Assert.Equal(1, paras.Count());
 943            var parasym = model.GetDeclaredSymbol(paras.First());
 944            var ploc = parasym.Locations[0];
 945            
 946            var args = descendants.OfType<ArgumentSyntax>().Where(s => s.ToString() == "index").Select(s => s);
 947            Assert.Equal(2, args.Count());
 948            var argsym1 = model.GetSymbolInfo(args.First().Expression).Symbol;
 949            var argsym2 = model.GetSymbolInfo(args.Last().Expression).Symbol;
 950            Assert.NotNull(argsym1);
 951            Assert.NotNull(argsym2);
 952
 953            Assert.Equal(ploc, argsym1.Locations[0]);
 954            Assert.Equal(ploc, argsym2.Locations[0]);
 955
 956            Assert.Equal(parasym.Kind, argsym1.Kind);
 957            Assert.Equal(parasym.Kind, argsym2.Kind);
 958
 959            // SourceSimpleParameterSymbol vs. SourceClonedComplexParameterSymbol
 960            Assert.NotEqual(parasym, argsym1);
 961            Assert.NotEqual(parasym, argsym2);
 962        }
 963
 964        [WorkItem(545648, "DevDiv")]
 965        [Fact]
 966        public void AliasDeclaredSymbolWithConflict()
 967        {
 968            var source = @"
 969using X = System;
 970 
 971class X { }
 972";
 973
 974            var comp = CreateCompilationWithMscorlib(source);
 975            var tree = comp.SyntaxTrees.Single();
 976            var model = comp.GetSemanticModel(tree);
 977
 978            var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingDirectiveSyntax>().Single();
 979
 980            var symbol = model.GetDeclaredSymbol(aliasSyntax);
 981            Assert.Equal(symbol.Target, comp.GlobalNamespace.GetMember<NamespaceSymbol>("System"));
 982
 983            comp.VerifyDiagnostics(
 984                // (2,1): info CS8019: Unnecessary using directive.
 985                // using X = System;
 986                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using X = System;"));
 987        }
 988
 989        [WorkItem(529751, "DevDiv")]
 990        [Fact]
 991        public void ExternAlias()
 992        {
 993            var source = @"
 994extern alias X;
 995
 996class Test
 997{
 998    static void Main()
 999    {
1000        X::C c = null;
1001    }
1002}
1003";
1004            var comp1 = CreateCompilationWithMscorlib("public class C { }");
1005            var ref1 = new MetadataImageReference(CompileAndVerify(comp1).EmittedAssemblyData, aliases: ImmutableArray.Create("X"));
1006
1007            var comp2 = CreateCompilationWithMscorlib(source, new[] { ref1 });
1008            var tree = comp2.SyntaxTrees.Single();
1009            var model = comp2.GetSemanticModel(tree);
1010
1011            var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single();
1012
1013            // Compilation.GetExternAliasTarget defines this behavior: the target is a merged namespace
1014            // with the same name as the alias, contained in the global namespace of the compilation.
1015            var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax);
1016            var aliasTarget = (NamespaceSymbol)aliasSymbol.Target;
1017            Assert.Equal(NamespaceKind.Module, aliasTarget.Extent.Kind);
1018            Assert.Equal("", aliasTarget.Name);
1019            Assert.True(aliasTarget.IsGlobalNamespace);
1020            Assert.Null(aliasTarget.ContainingNamespace);
1021
1022            Assert.Equal(0, comp2.GlobalNamespace.GetMembers("X").Length); //Doesn't contain the alias target namespace as a child.
1023
1024            var aliasQualifiedSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AliasQualifiedNameSyntax>().Single();
1025            Assert.Equal(aliasSymbol, model.GetAliasInfo(aliasQualifiedSyntax.Alias));
1026
1027            comp2.VerifyDiagnostics(
1028                // (8,14): warning CS0219: The variable 'c' is assigned but its value is never used
1029                //         X::C c = null;
1030                Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c"));
1031        }
1032
1033        [Fact, WorkItem(546687, "DevDiv"), WorkItem(529751, "DevDiv")]
1034        public void ExternAliasWithoutTarget()
1035        {
1036            var source = @"
1037extern alias X;
1038
1039class Test
1040{
1041    static void Main()
1042    {
1043        X::C c = null;
1044    }
1045}
1046";
1047
1048            var comp = CreateCompilationWithMscorlib(source);
1049            var tree = comp.SyntaxTrees.Single();
1050            var model = comp.GetSemanticModel(tree);
1051
1052            var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Single();
1053
1054            var aliasSymbol = model.GetDeclaredSymbol(aliasSyntax);
1055            Assert.IsType<MissingNamespaceSymbol>(aliasSymbol.Target);
1056
1057            var aliasQualifiedSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AliasQualifiedNameSyntax>().Single();
1058            Assert.Equal(aliasSymbol, model.GetAliasInfo(aliasQualifiedSyntax.Alias));
1059
1060            comp.VerifyDiagnostics(
1061                // (2,14): error CS0430: The extern alias 'X' was not specified in a /reference option
1062                // extern alias X;
1063                Diagnostic(ErrorCode.ERR_BadExternAlias, "X").WithArguments("X"),
1064                // (8,12): error CS0234: The type or namespace name 'C' does not exist in the namespace 'X' (are you missing an assembly reference?)
1065                //         X::C c = null;
1066                Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C").WithArguments("C", "X"));
1067        }
1068
1069        [WorkItem(545648, "DevDiv")]
1070        [Fact]
1071        public void UsingDirectiveAliasSemanticInfo()
1072        {
1073            var source = "using X = System;";
1074
1075            var comp = CreateCompilationWithMscorlib(source);
1076            comp.VerifyDiagnostics(
1077                // (1,1): info CS8019: Unnecessary using directive.
1078                // using X = System;
1079                Diagnostic(ErrorCode.INF_UnusedUsingDirective, "using X = System;"));
1080
1081            var tree = comp.SyntaxTrees.Single();
1082            var model = comp.GetSemanticModel(tree);
1083
1084            var aliasSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<NameEqualsSyntax>().Single().Name;
1085            Assert.Equal(SymbolInfo.None, model.GetSymbolInfo(aliasSyntax));
1086
1087            var usingSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<UsingDirectiveSyntax>().Single();
1088            Assert.Equal(SymbolKind.Alias, model.GetDeclaredSymbol(usingSyntax).Kind);
1089        }
1090
1091        [WorkItem(545882, "DevDiv")]
1092        [Fact]
1093        public void SpeculativelyBindConstructorInitializerInPlaceOfActual()
1094        {
1095            var source = @"class C
1096{
1097    C(int x) { }
1098    C() : this((int) 1) { }
1099}";
1100
1101            var comp = CreateCompilationWithMscorlib(source);
1102            comp.VerifyDiagnostics();
1103            
1104            var tree = comp.SyntaxTrees.Single();
1105            var model = comp.GetSemanticModel(tree);
1106            
1107            var oldSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
1108
1109            var newSyntax = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer);
1110
1111            var info = model.GetSpeculativeSymbolInfo(oldSyntax.SpanStart, newSyntax);
1112            var symbol = info.Symbol;
1113            Assert.NotNull(symbol);
1114            Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"), symbol.ContainingType);
1115            Assert.Equal(SymbolKind.Method, symbol.Kind);
1116            var method = (MethodSymbol)symbol;
1117            Assert.Equal(MethodKind.Constructor, method.MethodKind);
1118            Assert.Equal(0, method.ParameterCount);
1119        }
1120
1121        [WorkItem(545882, "DevDiv")]
1122        [Fact]
1123        public void SpeculativelyBindConstructorInitializerInNewLocation()
1124        {
1125            var source = @"class C
1126{
1127    C() { }
1128}";
1129
1130            var comp = CreateCompilationWithMscorlib(source);
1131            comp.VerifyDiagnostics();
1132
1133            var tree = comp.SyntaxTrees.Single();
1134            var model = comp.GetSemanticModel(tree);
1135
1136            var oldSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
1137
1138            var newSyntax = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer);
1139
1140            var info = model.GetSpeculativeSymbolInfo(oldSyntax.ParameterList.Span.End, newSyntax);
1141            Assert.Equal(SymbolInfo.None, info);
1142        }
1143
1144        [Fact]
1145        public void TestGetSpeculativeSemanticModelInFieldInitializer()
1146        {
1147            var compilation = CreateCompilationWithMscorlib(@"
1148class C 
1149{
1150  object y = 1;
1151}
1152");
1153            var tree = compilation.SyntaxTrees[0];
1154            var root = tree.GetCompilationUnitRoot();
1155            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1156            var fieldDecl = (FieldDeclarationSyntax)typeDecl.Members[0];
1157            var varDecl = fieldDecl.Declaration.Variables.First();
1158
1159            var model = compilation.GetSemanticModel(tree);
1160            Assert.False(model.IsSpeculativeSemanticModel);
1161            Assert.Null(model.ParentModel);
1162            Assert.Equal(0, model.OriginalPositionForSpeculation);
1163
1164            // Speculate on the equals value syntax (initializer)
1165            // Conversion info available, ConvertedType: Object.
1166            var equalsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression(@"(string)""Hello"""));
1167            var expr = equalsValue.Value;
1168            int position = varDecl.Initializer.SpanStart;
1169
1170            SemanticModel speculativeModel;
1171            bool success = model.TryGetSpeculativeSemanticModel(position, equalsValue, out speculativeModel);
1172            Assert.True(success);
1173            Assert.NotNull(speculativeModel);
1174            Assert.True(speculativeModel.IsSpeculativeSemanticModel);
1175            Assert.Equal(model, speculativeModel.ParentModel);
1176            Assert.Equal(position, speculativeModel.OriginalPositionForSpeculation);
1177
1178            var typeInfo = speculativeModel.GetTypeInfo(expr);
1179            Assert.NotNull(typeInfo.Type);
1180            Assert.Equal("String", typeInfo.Type.Name);
1181            Assert.Equal("Object", typeInfo.ConvertedType.Name);
1182
1183            var constantInfo = speculativeModel.GetConstantValue(expr);
1184            Assert.True(constantInfo.HasValue, "must be a constant");
1185            Assert.Equal("Hello", constantInfo.Value);
1186        }
1187
1188        [Fact]
1189        public void TestGetSpeculativeSemanticModelInEnumMember()
1190        {
1191            var compilation = CreateCompilationWithMscorlib(@"
1192enum C 
1193{
1194  y = 1
1195}
1196");
1197            var tree = compilation.SyntaxTrees[0];
1198            var root = tree.GetCompilationUnitRoot();
1199            var typeDecl = (EnumDeclarationSyntax)root.Members[0];
1200            var enumMemberDecl = (EnumMemberDeclarationSyntax)typeDecl.Members[0];
1201            var equalsValue = enumMemberDecl.EqualsValue;
1202            var initializer = equalsValue.Value;
1203
1204            var model = compilation.GetSemanticModel(tree);
1205
1206            // Speculate on the equals value syntax (initializer)
1207            // Conversion info available, ConvertedType: Int32.
1208            var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("(short)0"));
1209            var expr = newEqualsValue.Value;
1210            SemanticModel speculativeModel;
1211            bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
1212            Assert.True(success);
1213            Assert.NotNull(speculativeModel);
1214
1215            var typeInfo = speculativeModel.GetTypeInfo(expr);
1216            Assert.NotNull(typeInfo.Type);
1217            Assert.Equal("Int16", typeInfo.Type.Name);
1218            Assert.Equal("Int32", typeInfo.ConvertedType.Name);
1219
1220            var constantInfo = speculativeModel.GetConstantValue(expr);
1221            Assert.True(constantInfo.HasValue, "must be a constant");
1222            Assert.Equal((short)0, constantInfo.Value);
1223        }
1224
1225        [Fact]
1226        [WorkItem(648305, "DevDiv")]
1227        public void TestGetSpeculativeSemanticModelInDefaultValueArgument()
1228        {
1229            var compilation = CreateCompilationWithMscorlib(@"
1230class C 
1231{
1232  void M(int x = 1)
1233  {
1234    string y = ""Hello"";     
1235  }
1236}
1237");
1238            var tree = compilation.SyntaxTrees[0];
1239            var root = tree.GetCompilationUnitRoot();
1240            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1241            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1242            var equalsValue = methodDecl.ParameterList.Parameters[0].Default;
1243            var paramDefaultArg = equalsValue.Value;
1244
1245            var model = compilation.GetSemanticModel(tree);
1246
1247            var ti = model.GetTypeInfo(paramDefaultArg);
1248
1249            // Speculate on the equals value syntax (initializer)
1250            // Conversion info available, ConvertedType: Int32.
1251            var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("(short)0"));
1252            var expr = newEqualsValue.Value;
1253
1254            SemanticModel speculativeModel;
1255            bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
1256            Assert.True(success);
1257            Assert.NotNull(speculativeModel);
1258
1259            var typeInfo = speculativeModel.GetTypeInfo(expr);
1260            Assert.NotNull(typeInfo.Type);
1261            Assert.Equal("Int16", typeInfo.Type.Name);
1262            Assert.Equal("Int32", typeInfo.ConvertedType.Name);
1263
1264            var constantInfo = speculativeModel.GetConstantValue(expr);
1265            Assert.True(constantInfo.HasValue, "must be a constant");
1266            Assert.Equal((short)0, constantInfo.Value);
1267        }
1268
1269        [Fact]
1270        [WorkItem(746002, "DevDiv")]
1271        public void TestGetSpeculativeSemanticModelInDefaultValueArgument2()
1272        {
1273            var compilation = CreateCompilationWithMscorlib(@"
1274using System;
1275
1276enum E
1277{
1278   A = 1,
1279   B = 2  
1280}
1281
1282interface I
1283{
1284    void M1(E e = E.A);
1285}
1286");
1287            var tree = compilation.SyntaxTrees[0];
1288            var root = tree.GetCompilationUnitRoot();
1289            var interfaceDecl = (TypeDeclarationSyntax)root.Members[1];
1290            var methodDecl = (MethodDeclarationSyntax)interfaceDecl.Members[0];
1291            var param = methodDecl.ParameterList.Parameters[0];
1292            var equalsValue = param.Default;
1293            var paramDefaultArg = equalsValue.Value;
1294
1295            var model = compilation.GetSemanticModel(tree);
1296
1297            // Speculate on the equals value syntax (initializer) with a non-null parent
1298            var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("E.B | E.A"));
1299            newEqualsValue = param.ReplaceNode(equalsValue, newEqualsValue).Default;
1300            var binaryExpr = newEqualsValue.Value;
1301
1302            SemanticModel speculativeModel;
1303            bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
1304            Assert.True(success);
1305            Assert.NotNull(speculativeModel);
1306
1307            var typeInfo = speculativeModel.GetTypeInfo(binaryExpr);
1308            Assert.NotNull(typeInfo.Type);
1309            Assert.Equal("E", typeInfo.Type.Name);
1310            Assert.Equal("E", typeInfo.ConvertedType.Name);
1311        }
1312
1313        [Fact]
1314        [WorkItem(657701, "DevDiv")]
1315        public void TestGetSpeculativeSemanticModelInConstructorDefaultValueArgument()
1316        {
1317            var compilation = CreateCompilationWithMscorlib(@"
1318class C 
1319{
1320  C(int x = 1)
1321  {
1322    string y = ""Hello"";     
1323  }
1324}
1325");
1326            var tree = compilation.SyntaxTrees[0];
1327            var root = tree.GetCompilationUnitRoot();
1328            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1329            var constructorDecl = (ConstructorDeclarationSyntax)typeDecl.Members[0];
1330            var equalsValue = constructorDecl.ParameterList.Parameters[0].Default;
1331            var paramDefaultArg = equalsValue.Value;
1332
1333            var model = compilation.GetSemanticModel(tree);
1334
1335            var ti = model.GetTypeInfo(paramDefaultArg);
1336
1337            // Speculate on the equals value syntax (initializer)
1338            // Conversion info available, ConvertedType: Int32.
1339            var newEqualsValue = SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("(short)0"));
1340            var expr = newEqualsValue.Value;
1341
1342            SemanticModel speculativeModel;
1343            bool success = model.TryGetSpeculativeSemanticModel(equalsValue.SpanStart, newEqualsValue, out speculativeModel);
1344            Assert.True(success);
1345            Assert.NotNull(speculativeModel);
1346
1347            var typeInfo = speculativeModel.GetTypeInfo(expr);
1348            Assert.NotNull(typeInfo.Type);
1349            Assert.Equal("Int16", typeInfo.Type.Name);
1350            Assert.Equal("Int32", typeInfo.ConvertedType.Name);
1351
1352            var constantInfo = speculativeModel.GetConstantValue(expr);
1353            Assert.True(constantInfo.HasValue, "must be a constant");
1354            Assert.Equal((short)0, constantInfo.Value);
1355        }
1356
1357        [WorkItem(529893, "DevDiv")]
1358        [Fact]
1359        public void AliasCalledVar()
1360        {
1361            var source = @"
1362using var = Q;
1363
1364class Q
1365{
1366    var q;
1367}
1368";
1369
1370            var comp = CreateCompilationWithMscorlib(source);
1371            comp.VerifyDiagnostics(
1372                // (6,9): warning CS0169: The field 'Q.q' is never used
1373                //     var q;
1374                Diagnostic(ErrorCode.WRN_UnreferencedField, "q").WithArguments("Q.q"));
1375
1376            var classQ = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Q");
1377            var fieldQ = classQ.GetMember<FieldSymbol>("q");
1378
1379            Assert.Equal(classQ, fieldQ.Type);
1380
1381            var tree = comp.SyntaxTrees.Single();
1382            var model = comp.GetSemanticModel(tree);
1383
1384            var aliasDecl = tree.GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>().Single();
1385
1386            var aliasSymbol = model.GetDeclaredSymbol(aliasDecl);
1387            Assert.Equal(SymbolKind.Alias, aliasSymbol.Kind);
1388            Assert.Equal(classQ, ((AliasSymbol)aliasSymbol).Target);
1389            Assert.Equal("var", aliasSymbol.Name);
1390
1391            var aliasDeclInfo = model.GetSymbolInfo(aliasDecl.Alias.Name);
1392            Assert.Null(aliasDeclInfo.Symbol);
1393            Assert.Equal(CandidateReason.None, aliasDeclInfo.CandidateReason);
1394
1395            var fieldDecl = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single();
1396
1397            var fieldSymbol = model.GetDeclaredSymbol(fieldDecl.Declaration.Variables.Single());
1398            Assert.Equal(fieldQ, fieldSymbol);
1399
1400            var typeSyntax = (IdentifierNameSyntax)fieldDecl.Declaration.Type;
1401
1402            var fieldTypeInfo = model.GetSymbolInfo(typeSyntax);
1403            Assert.Equal(classQ, fieldTypeInfo.Symbol);
1404
1405            var fieldTypeAliasInfo = model.GetAliasInfo(typeSyntax);
1406            Assert.Equal(aliasSymbol, fieldTypeAliasInfo);
1407        }
1408
1409        [Fact]
1410        public void TestGetSpeculativeSemanticModelForStatement()
1411        {
1412            var compilation = CreateCompilationWithMscorlib(@"
1413class C 
1414{
1415  void M(int x)
1416  {
1417    int y = 1000;     
1418  }
1419}
1420");
1421
1422            var statement = (BlockSyntax)SyntaxFactory.ParseStatement(@"
1423{ 
1424   int z = 0; 
1425   M(z);  
1426   M(y);
1427}
1428");
1429
1430            var tree = compilation.SyntaxTrees[0];
1431            var root = tree.GetCompilationUnitRoot();
1432            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1433            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1434            var model = compilation.GetSemanticModel(tree);
1435
1436            SemanticModel speculativeModel;
1437            bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, statement, out speculativeModel);
1438            Assert.True(success);
1439            Assert.NotNull(speculativeModel);
1440
1441            var localDecl = (LocalDeclarationStatementSyntax)statement.Statements[0];
1442            var declarator = localDecl.Declaration.Variables.First();
1443            var local = speculativeModel.GetDeclaredSymbol(declarator);
1444            Assert.NotNull(local);
1445            Assert.Equal("z", local.Name);
1446            Assert.Equal(SymbolKind.Local, local.Kind);
1447            Assert.Equal("Int32", ((LocalSymbol)local).Type.Name);
1448
1449            var typeInfo = speculativeModel.GetTypeInfo(localDecl.Declaration.Type);
1450            Assert.NotNull(typeInfo.Type);
1451            Assert.Equal("Int32", typeInfo.Type.Name);
1452
1453            var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)statement.Statements[1]).Expression;
1454            var arg = call.ArgumentList.Arguments[0].Expression;
1455            var info = speculativeModel.GetSymbolInfo(arg);
1456            Assert.NotNull(info.Symbol);
1457            Assert.Equal("z", info.Symbol.Name);
1458            Assert.Equal(SymbolKind.Local, info.Symbol.Kind);
1459
1460            var call2 = (InvocationExpressionSyntax)((ExpressionStatementSyntax)((BlockSyntax)statement).Statements[2]).Expression;
1461            var arg2 = call2.ArgumentList.Arguments[0].Expression;
1462            var info2 = speculativeModel.GetSymbolInfo(arg2);
1463            Assert.NotNull(info2.Symbol);
1464            Assert.Equal("y", info2.Symbol.Name);
1465            Assert.Equal(SymbolKind.Local, info2.Symbol.Kind);
1466        }
1467
1468        [Fact]
1469        public void TestGetSpeculativeSemanticModelForStatement_DeclaredLocal()
1470        {
1471            var compilation = CreateCompilationWithMscorlib(@"
1472class C 
1473{
1474  void M(int x)
1475  {
1476    int y = 1000;     
1477  }
1478}
1479");
1480            
1481            var tree = compilation.SyntaxTrees[0];
1482            var root = tree.GetCompilationUnitRoot();
1483            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1484            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1485            var model = compilation.GetSemanticModel(tree);
1486
1487            // different name local
1488            var statement = SyntaxFactory.ParseStatement(@"int z = 0;");
1489
1490            SemanticModel speculativeModel;
1491            bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, statement, out speculativeModel);
1492            Assert.True(success);
1493            Assert.NotNull(speculativeModel);
1494
1495            var declarator = ((LocalDeclarationStatementSyntax)statement).Declaration.Variables.First();
1496            var local = speculativeModel.GetDeclaredSymbol(declarator);
1497            Assert.NotNull(local);
1498            Assert.Equal("z", local.Name);
1499            Assert.Equal(SymbolKind.Local, local.Kind);
1500            Assert.Equal("Int32", ((LocalSymbol)local).Type.Name);
1501
1502            // same name local
1503            statement = SyntaxFactory.ParseStatement(@"string y = null;");
1504            success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, statement, out speculativeModel);
1505            Assert.True(success);
1506            Assert.NotNull(speculativeModel);
1507
1508            declarator = ((LocalDeclarationStatementSyntax)statement).Declaration.Variables.First();
1509            local = speculativeModel.GetDeclaredSymbol(declarator);
1510            Assert.NotNull(local);
1511            Assert.Equal("y", local.Name);
1512            Assert.Equal(SymbolKind.Local, local.Kind);
1513            Assert.Equal("String", ((LocalSymbol)local).Type.Name);
1514        }
1515
1516        [Fact]
1517        public void TestGetSpeculativeSemanticModelForStatement_GetDeclaredLabelSymbol()
1518        {
1519            var compilation = CreateCompilationWithMscorlib(@"
1520class C 
1521{
1522  void M(int x)
1523  {
1524    int y = 1000;     
1525  }
1526}
1527");
1528
1529            var labeledStatement = SyntaxFactory.ParseStatement(@"label: y++;");
1530
1531            var tree = compilation.SyntaxTrees[0];
1532            var root = tree.GetCompilationUnitRoot();
1533            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1534            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1535            var model = compilation.GetSemanticModel(tree);
1536
1537            SemanticModel statModel;
1538            bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, labeledStatement, out statModel);
1539            Assert.True(success);
1540            Assert.NotNull(statModel);
1541
1542            var label = statModel.GetDeclaredSymbol(labeledStatement);
1543            Assert.NotNull(label);
1544            Assert.Equal("label", label.Name);
1545            Assert.Equal(SymbolKind.Label, label.Kind);
1546        }
1547
1548        [Fact]
1549        public void TestGetSpeculativeSemanticModelForStatement_GetDeclaredSwitchLabelSymbol()
1550        {
1551            var compilation = CreateCompilationWithMscorlib(@"
1552class C 
1553{
1554  void M(int x)
1555  {
1556    int y = 0;
1557  }
1558}
1559");
1560
1561            var switchStatement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@"
1562switch (y)
1563{
1564  case 0:
1565    y++;
1566    break;
1567}");
1568            var switchLabel = switchStatement.Sections[0].Labels[0];
1569
1570            var tree = compilation.SyntaxTrees[0];
1571            var root = tree.GetCompilationUnitRoot();
1572            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1573            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1574            var model = compilation.GetSemanticModel(tree);
1575            SemanticModel statModel;
1576            bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].Span.End, switchStatement, out statModel);
1577            Assert.True(success);
1578            Assert.NotNull(statModel);
1579
1580            var symbol = statModel.GetDeclaredSymbol(switchLabel);
1581            Assert.NotNull(symbol);
1582            Assert.IsType<SourceLabelSymbol>(symbol);
1583
1584            var labelSymbol = (SourceLabelSymbol)symbol;
1585            Assert.Equal(ConstantValue.Default(SpecialType.System_Int32), labelSymbol.SwitchCaseLabelConstant);
1586            Assert.Equal(switchLabel, labelSymbol.IdentifierNodeOrToken.AsNode());
1587            Assert.Equal("case 0:", labelSymbol.Name);
1588        }
1589
1590        [Fact]
1591        public void TestGetSpeculativeSemanticModelForStatement_GetDeclaredLambdaParameterSymbol()
1592        {
1593            var compilation = CreateCompilationWithMscorlibAndSystemCore(@"
1594using System.Linq;
1595
1596class C 
1597{
1598  void M(int x)
1599  {
1600    int y = 0;
1601  }
1602}
1603");
1604
1605            var speculatedStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"Func<int, int> var = (z) => x + z;");
1606            
1607            var tree = compilation.SyntaxTrees[0];
1608            var root = tree.GetCompilationUnitRoot();
1609            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1610            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1611            var model = compilation.GetSemanticModel(tree);
1612
1613            SemanticModel speculativeModel;
1614            bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].Span.End, speculatedStatement, out speculativeModel);
1615            Assert.True(success);
1616            Assert.NotNull(speculativeModel);
1617
1618            var lambdaExpression = speculatedStatement.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().FirstOrDefault();
1619            var lambdaParam = lambdaExpression.ParameterList.Parameters[0];
1620            var parameterSymbol = speculativeModel.GetDeclaredSymbol(lambdaParam);
1621            Assert.NotNull(parameterSymbol);
1622            Assert.Equal("z", parameterSymbol.Name);
1623        }
1624
1625        [Fact]
1626        public void TestGetSpeculativeSemanticModelForStatement_ForEach()
1627        {
1628            var compilation = CreateCompilationWithMscorlib(@"
1629class C 
1630{
1631  void M(int x)
1632  {
1633    var a = new [] {1, 2, 3};     
1634  }
1635}
1636");
1637
1638            var statement = (ForEachStatementSyntax)SyntaxFactory.ParseStatement(@"
1639foreach(short ele in a)
1640{
1641} 
1642");
1643
1644            var tree = compilation.SyntaxTrees[0];
1645            var root = tree.GetCompilationUnitRoot();
1646            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1647            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1648            var model = compilation.GetSemanticModel(tree);
1649
1650            SemanticModel speculativeModel;
1651            bool success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].SpanStart, statement, out speculativeModel);
1652            Assert.True(success);
1653            Assert.NotNull(speculativeModel);
1654
1655            ForEachStatementInfo info = speculativeModel.GetForEachStatementInfo(statement);
1656            Assert.NotNull(info);
1657            Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorMethod.ToTestDisplayString());
1658            Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentProperty.GetMethod.ToTestDisplayString());
1659            Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextMethod.ToTestDisplayString());
1660            Assert.Equal("void System.IDisposable.Dispose()", info.DisposeMethod.ToTestDisplayString());
1661        }
1662
1663        [Fact]
1664        public void TestGetSpeculativeSemanticModelInAutoPropInitializer1()
1665        {
1666            var source = @"class C
1667{
1668    int y = 0;
1669    int X { get; } = 1;
1670}";
1671
1672            var comp = CreateCompilationWithMscorlib(source, parseOptions: TestOptions.ExperimentalParseOptions);
1673            var tree = comp.SyntaxTrees.Single();
1674
1675            var model = comp.GetSemanticModel(tree);
1676            Assert.False(model.IsSpeculativeSemanticModel);
1677            Assert.Null(model.ParentModel);
1678            Assert.Equal(0, model.OriginalPositionForSpeculation);
1679
1680            // Speculate on the initializer
1681            var root = tree.GetCompilationUnitRoot();
1682            var oldSyntax = root.DescendantNodes()
1683                .OfType<EqualsValueClauseSyntax>().ElementAt(1);
1684            var position = oldSyntax.SpanStart;
1685            var newSyntax = SyntaxFactory.EqualsValueClause(
1686                SyntaxFactory.ParseExpression("this.y"));
1687            var expr = newSyntax.Value;
1688
1689            SemanticModel speculativeModel;
1690            bool success = model.TryGetSpeculativeSemanticModel(oldSyntax.SpanStart,
1691                newSyntax, out speculativeModel);
1692            Assert.True(success);
1693            Assert.NotNull(speculativeModel);
1694            Assert.True(speculativeModel.IsSpeculativeSemanticModel);
1695            Assert.Equal(model, speculativeModel.ParentModel);
1696            Assert.Equal(position, speculativeModel.OriginalPositionForSpeculation);
1697
1698            var typeInfo = speculativeModel.GetTypeInfo(expr);
1699            Assert.NotNull(typeInfo);
1700            Assert.Equal("Int32", typeInfo.Type.Name);
1701
1702            var thisSyntax = expr.DescendantNodes().OfType<ThisExpressionSyntax>().Single();
1703            var symbolInfo = speculativeModel.GetSpeculativeSymbolInfo(
1704                thisSyntax.SpanStart,
1705                thisSyntax, SpeculativeBindingOption.BindAsExpression);
1706            Assert.NotNull(symbolInfo);
1707            var candidates = symbolInfo.CandidateSymbols;
1708            Assert.Equal(1, candidates.Length);
1709            Assert.IsType<ThisParameterSymbol>(candidates[0]);
1710            Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
1711        }
1712
1713        [Fact]
1714        public void TestGetSpeculativeSemanticModelForConstructorInitializer()
1715        {
1716            var source = @"class C
1717{
1718    C(int x) { }
1719    C() : this((int) 1) { }
1720}";
1721
1722            var comp = CreateCompilationWithMscorlib(source);
1723            comp.VerifyDiagnostics();
1724
1725            var tree = comp.SyntaxTrees.Single();
1726            var parentModel = comp.GetSemanticModel(tree);
1727
1728            var oldSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
1729
1730            var newSyntax = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer);
1731
1732            SemanticModel speculativeModel;
1733            bool success = parentModel.TryGetSpeculativeSemanticModel(oldSyntax.SpanStart, newSyntax, out speculativeModel);
1734            Assert.True(success);
1735            Assert.NotNull(speculativeModel);
1736
1737            var info = speculativeModel.GetSymbolInfo(newSyntax);
1738            var symbol = info.Symbol;
1739            Assert.NotNull(symbol);
1740            Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"), symbol.ContainingType);
1741            Assert.Equal(SymbolKind.Method, symbol.Kind);
1742            var method = (MethodSymbol)symbol;
1743            Assert.Equal(MethodKind.Constructor, method.MethodKind);
1744            Assert.Equal(0, method.ParameterCount);
1745
1746            // test unnecessary cast removal
1747            var newArgument = SyntaxFactory.ParseExpression("1");
1748            newSyntax = oldSyntax.ReplaceNode(oldSyntax.DescendantNodes().OfType<CastExpressionSyntax>().Single(), newArgument);
1749
1750            success = parentModel.TryGetSpeculativeSemanticModel(oldSyntax.SpanStart, newSyntax, out speculativeModel);
1751            Assert.True(success);
1752            Assert.NotNull(speculativeModel);
1753
1754            info = speculativeModel.GetSymbolInfo(newSyntax);
1755            symbol = info.Symbol;
1756            Assert.NotNull(symbol);
1757            Assert.Equal(comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"), symbol.ContainingType);
1758            Assert.Equal(SymbolKind.Method, symbol.Kind);
1759            method = (MethodSymbol)symbol;
1760            Assert.Equal(MethodKind.Constructor, method.MethodKind);
1761            Assert.Equal(1, method.ParameterCount);
1762
1763            // test incorrect cast replacement
1764            newArgument = SyntaxFactory.ParseExpression("(string) 1");
1765            newSyntax = oldSyntax.ReplaceNode(oldSyntax.DescendantNodes().OfType<CastExpressionSyntax>().Single(), newArgument);
1766            success = parentModel.TryGetSpeculativeSemanticModel(oldSyntax.SpanStart, newSyntax, out speculativeModel);
1767            Assert.True(success);
1768            Assert.NotNull(speculativeModel);
1769
1770            info = speculativeModel.GetSymbolInfo(newSyntax);
1771            symbol = info.Symbol;
1772            Assert.Null(symbol);
1773            Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason);
1774            Assert.Equal(2, info.CandidateSymbols.Length);
1775            var sortedCandidates = info.CandidateSymbols.OrderBy(s => s.ToTestDisplayString()).ToArray();
1776            Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString());
1777            Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
1778            Assert.Equal("C..ctor(System.Int32 x)", sortedCandidates[1].ToTestDisplayString());
1779            Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
1780        }
1781
1782        [WorkItem(545882, "DevDiv")]
1783        [Fact]
1784        public void TestGetSpeculativeSemanticModelForConstructorInitializer_UnsupportedLocation()
1785        {
1786            var source = @"class C
1787{
1788    C() { }
1789}";
1790
1791            var comp = CreateCompilationWithMscorlib(source);
1792            comp.VerifyDiagnostics();
1793
1794            var tree = comp.SyntaxTrees.Single();
1795            var parentModel = comp.GetSemanticModel(tree);
1796
1797            var oldSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().Single();
1798
1799            var newSyntax = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer);
1800
1801            SemanticModel speculativeModel;
1802            bool success = parentModel.TryGetSpeculativeSemanticModel(oldSyntax.SpanStart, newSyntax, out speculativeModel);
1803            Assert.False(success);
1804            Assert.Null(speculativeModel);
1805        }
1806
1807        [Fact]
1808        public void TestArgumentsToGetSpeculativeSemanticModelAPI()
1809        {
1810            var compilation = CreateCompilationWithMscorlib(@"
1811class C 
1812{
1813  public C(): this(0) {}
1814  public C(int i) {}
1815
1816  [System.Obsolete]
1817  void M(int x)
1818  {
1819    string y = ""Hello"";     
1820  }
1821}
1822");
1823            var tree = compilation.SyntaxTrees[0];
1824            var root = tree.GetCompilationUnitRoot();
1825            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1826            var ctor1 = (ConstructorDeclarationSyntax)typeDecl.Members[0];
1827            var ctor2 = (ConstructorDeclarationSyntax)typeDecl.Members[1];
1828            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[2];
1829            
1830            var model = compilation.GetSemanticModel(tree);
1831            var statement = (LocalDeclarationStatementSyntax)methodDecl.Body.Statements[0];
1832            var initializer = statement.Declaration.Variables[0].Initializer;
1833            var ctorInitializer = ctor1.Initializer;
1834            var attribute = methodDecl.AttributeLists[0].Attributes[0];
1835
1836            SemanticModel speculativeModel;
1837            Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(statement.SpanStart, statement: null, speculativeModel: out speculativeModel));
1838            Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(statement.SpanStart, constructorInitializer: null, speculativeModel: out speculativeModel));
1839            Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(statement.SpanStart, attribute: null, speculativeModel: out speculativeModel));
1840
1841            // Speculate on a node from the same syntax tree.
1842            Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(statement.SpanStart, statement: statement, speculativeModel: out speculativeModel));
1843            Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(ctorInitializer.SpanStart, constructorInitializer: ctorInitializer, speculativeModel: out speculativeModel));
1844            Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(attribute.SpanStart, attribute: attribute, speculativeModel: out speculativeModel));
1845
1846            // Chaining speculative semantic model is not supported.
1847            var speculatedStatement = statement.ReplaceNode(initializer.Value, SyntaxFactory.ParseExpression("0"));
1848            model.TryGetSpeculativeSemanticModel(statement.SpanStart, speculatedStatement, speculativeModel: out speculativeModel);
1849            Assert.Throws<InvalidOperationException>(() => speculativeModel.TryGetSpeculativeSemanticModel(speculatedStatement.SpanStart, speculatedStatement, speculativeModel: out speculativeModel));
1850        }
1851
1852        [Fact]
1853        public void TestGetSpeculativeSemanticModelOnSpeculativeSemanticModel()
1854        {
1855            var compilation = CreateCompilationWithMscorlib(@"
1856class C 
1857{
1858  public C(): this(0) {}
1859  public C(int i) {}
1860
1861  [System.Obsolete]
1862  void M(int x)
1863  {
1864    string y = ""Hello"";     
1865  }
1866}
1867");
1868            var tree = compilation.SyntaxTrees[0];
1869            var root = tree.GetCompilationUnitRoot();
1870            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1871            var ctor1 = (ConstructorDeclarationSyntax)typeDecl.Members[0];
1872            var ctor2 = (ConstructorDeclarationSyntax)typeDecl.Members[1];
1873            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[2];
1874
1875            var model = compilation.GetSemanticModel(tree);
1876            var statement = (LocalDeclarationStatementSyntax)methodDecl.Body.Statements[0];
1877            var expression = statement.Declaration.Variables[0].Initializer.Value;
1878            var ctorInitializer = ctor1.Initializer;
1879            var attribute = methodDecl.AttributeLists[0].Attributes[0];
1880
1881            var speculatedStatement = statement.ReplaceNode(expression, SyntaxFactory.ParseExpression("0"));
1882            SemanticModel speculativeModel;
1883            var success = model.TryGetSpeculativeSemanticModel(statement.SpanStart, speculatedStatement, out speculativeModel);
1884            Assert.True(success);
1885            Assert.NotNull(speculativeModel);
1886            
1887            // Chaining speculative semantic model is not supported.
1888            // (a) Expression
1889            var newSpeculatedStatement = statement.ReplaceNode(expression, SyntaxFactory.ParseExpression("1.1"));
1890            SemanticModel newModel;
1891            Assert.Throws<InvalidOperationException>(() => speculativeModel.TryGetSpeculativeSemanticModel(speculatedStatement.SpanStart, newSpeculatedStatement, out newModel));
1892
1893            // (b) Statement
1894            newSpeculatedStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"int z = 0;");
1895            Assert.Throws<InvalidOperationException>(() => speculativeModel.TryGetSpeculativeSemanticModel(speculatedStatement.SpanStart, newSpeculatedStatement, out newModel));
1896        }
1897
1898        [Fact]
1899        public void TestGetSpeculativeSemanticModelInsideUnsafeCode()
1900        {
1901            var compilation = CreateCompilationWithMscorlib(@"
1902unsafe class C
1903{
1904    void M()
1905    {
1906        int x;
1907    }
1908}
1909");
1910            var tree = compilation.SyntaxTrees[0];
1911            var root = tree.GetCompilationUnitRoot();
1912            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
1913            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
1914
1915            var model = compilation.GetSemanticModel(tree);
1916
1917            var unsafeStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement("int *p = &x;");
1918
1919            SemanticModel speculativeModel;
1920            var success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.Statements[0].Span.End, unsafeStatement, out speculativeModel);
1921            Assert.True(success);
1922            Assert.NotNull(speculativeModel);
1923
1924            var declarator = unsafeStatement.Declaration.Variables.First();
1925            var initializer = declarator.Initializer.Value;
1926
1927            var binder = ((CSharpSemanticModel)speculativeModel).GetEnclosingBinder(initializer.SpanStart);
1928            Assert.True(binder.InUnsafeRegion, "must be in unsafe code");
1929            Assert.True(binder.IsSemanticModelBinder, "must be speculative");
1930
1931            var typeInfo = speculativeModel.GetTypeInfo(initializer);
1932            Assert.Equal("System.Int32*", typeInfo.Type.ToTestDisplayString());
1933            Assert.Equal(TypeKind.PointerType, typeInfo.Type.TypeKind);
1934            Assert.Equal("System.Int32*", typeInfo.ConvertedType.ToTestDisplayString());
1935            Assert.Equal(TypeKind.PointerType, typeInfo.ConvertedType.TypeKind);
1936
1937            var conv = speculativeModel.GetConversion(initializer);
1938            Assert.Equal(ConversionKind.Identity, conv.Kind);
1939
1940            var symbol = speculativeModel.GetDeclaredSymbol(declarator);
1941            Assert.NotNull(symbol);
1942            Assert.Equal(SymbolKind.Local, symbol.Kind);
1943            Assert.Equal("p", symbol.Name);
1944        }
1945
1946        [WorkItem(663704, "DevDiv")]
1947        [Fact]
1948        public void TestGetSpeculativeSemanticModelInsideUnknownAccessor()
1949        {
1950            var source = @"
1951class C
1952{
1953    C P
1954    {
1955        foo
1956        {
1957            return null;
1958        }
1959    }
1960}
1961";
1962            var comp = CreateCompilationWithMscorlib(source);
1963            var tree = comp.SyntaxTrees.Single();
1964            var model = comp.GetSemanticModel(tree);
1965
1966            var accessorSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single();
1967            Assert.Equal(SyntaxKind.UnknownAccessorDeclaration, accessorSyntax.Kind);
1968
1969            var statementSyntax = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single();
1970            var memberModel = ((CSharpSemanticModel)model).GetMemberModel(statementSyntax);
1971            Assert.Null(memberModel); // No member model since no symbol.
1972
1973            var speculativeSyntax = SyntaxFactory.ParseStatement("return default(C);");
1974
1975            SemanticModel speculativeModel;
1976            var success = model.TryGetSpeculativeSemanticModel(statementSyntax.SpanStart, speculativeSyntax, out speculativeModel);
1977            Assert.False(success);
1978            Assert.Null(speculativeModel);
1979        }
1980
1981        [Fact]
1982        public void TestGetSpeculativeSemanticModelForMethodBody()
1983        {
1984            var compilation = CreateCompilationWithMscorlib(@"
1985class C 
1986{
1987  void M(int x)
1988  {
1989    int y = 1000;     
1990  }
1991}
1992");
1993
1994            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"
1995{ 
1996   int z = 0; 
1997   M(z);  
1998   M(y);    // Should generate error here as we are replacing the method body.
1999}
2000");
2001
2002            var tree = compilation.SyntaxTrees[0];
2003            var root = tree.GetCompilationUnitRoot();
2004            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2005            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
2006            var model = compilation.GetSemanticModel(tree);
2007
2008            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2009            blockStatement = speculatedMethod.Body;
2010
2011            SemanticModel speculativeModel;
2012            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2013            Assert.True(success);
2014            Assert.NotNull(speculativeModel);
2015
2016            VerifySpeculativeSemanticModelForMethodBody(blockStatement, speculativeModel);
2017        }
2018
2019        private static void VerifySpeculativeSemanticModelForMethodBody(BlockSyntax blockStatement, SemanticModel speculativeModel)
2020        {
2021            var localDecl = (LocalDeclarationStatementSyntax)blockStatement.Statements[0];
2022            var declarator = localDecl.Declaration.Variables.First();
2023            var local = speculativeModel.GetDeclaredSymbol(declarator);
2024            Assert.NotNull(local);
2025            Assert.Equal("z", local.Name);
2026            Assert.Equal(SymbolKind.Local, local.Kind);
2027            Assert.Equal("Int32", ((LocalSymbol)local).Type.Name);
2028
2029            var typeInfo = speculativeModel.GetTypeInfo(localDecl.Declaration.Type);
2030            Assert.NotNull(typeInfo.Type);
2031            Assert.Equal("Int32", typeInfo.Type.Name);
2032
2033            var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)blockStatement.Statements[1]).Expression;
2034            var arg = call.ArgumentList.Arguments[0].Expression;
2035            var info = speculativeModel.GetSymbolInfo(arg);
2036            Assert.NotNull(info.Symbol);
2037            Assert.Equal("z", info.Symbol.Name);
2038            Assert.Equal(SymbolKind.Local, info.Symbol.Kind);
2039
2040            // Shouldn't bind to local y in the original method as we are replacing the method body.
2041            var call2 = (InvocationExpressionSyntax)((ExpressionStatementSyntax)((BlockSyntax)blockStatement).Statements[2]).Expression;
2042            var arg2 = call2.ArgumentList.Arguments[0].Expression;
2043            var info2 = speculativeModel.GetSymbolInfo(arg2);
2044            Assert.Null(info2.Symbol);
2045        }
2046
2047        [Fact]
2048        public void TestGetSpeculativeSemanticModelForInexerAccessorBody()
2049        {
2050            var compilation = CreateCompilationWithMscorlib(@"
2051class C 
2052{
2053    private int this[int x]
2054    {
2055        set
2056        {
2057            int y = 1000;
2058        }
2059    }
2060}
2061");
2062
2063            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"
2064{ 
2065   int z = 0; 
2066   M(z);  
2067   M(y);    // Should generate error here as we are replacing the method body.
2068}
2069");
2070
2071            var tree = compilation.SyntaxTrees[0];
2072            var root = tree.GetCompilationUnitRoot();
2073            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2074            var indexerDecl = (IndexerDeclarationSyntax)typeDecl.Members[0];
2075            var methodDecl = indexerDecl.AccessorList.Accessors[0];
2076            var model = compilation.GetSemanticModel(tree);
2077
2078            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2079            blockStatement = speculatedMethod.Body;
2080
2081            SemanticModel speculativeModel;
2082            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2083            Assert.True(success);
2084            Assert.NotNull(speculativeModel);
2085
2086            VerifySpeculativeSemanticModelForMethodBody(blockStatement, speculativeModel);
2087        }
2088
2089        [Fact]
2090        public void TestGetSpeculativeSemanticModelForPropertyAccessorBody()
2091        {
2092            var compilation = CreateCompilationWithMscorlib(@"
2093class C 
2094{
2095    private int M
2096    {
2097        set
2098        {
2099            int y = 1000;
2100        }
2101    }
2102}
2103");
2104
2105            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"
2106{ 
2107   int z = 0; 
2108   M(z);  
2109   M(y);    // Should generate error here as we are replacing the method body.
2110}
2111");
2112
2113            var tree = compilation.SyntaxTrees[0];
2114            var root = tree.GetCompilationUnitRoot();
2115            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2116            var propertyDecl = (PropertyDeclarationSyntax)typeDecl.Members[0];
2117            var methodDecl = propertyDecl.AccessorList.Accessors[0];
2118            var model = compilation.GetSemanticModel(tree);
2119
2120            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2121            blockStatement = speculatedMethod.Body;
2122
2123            SemanticModel speculativeModel;
2124            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2125            Assert.True(success);
2126            Assert.NotNull(speculativeModel);
2127
2128            VerifySpeculativeSemanticModelForMethodBody(blockStatement, speculativeModel);
2129        }
2130
2131        [Fact]
2132        public void TestGetSpeculativeSemanticModelForEventAccessorBody()
2133        {
2134            var compilation = CreateCompilationWithMscorlib(@"
2135class C 
2136{
2137    private event System.Action E
2138    {
2139        add
2140        {
2141            int y = 1000;
2142        }
2143        remove
2144        {
2145        }
2146    }
2147}
2148");
2149
2150            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"
2151{ 
2152   int z = 0; 
2153   M(z);  
2154   M(y);    // Should generate error here as we are replacing the method body.
2155}
2156");
2157
2158            var tree = compilation.SyntaxTrees[0];
2159            var root = tree.GetCompilationUnitRoot();
2160            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2161            var eventDecl = (EventDeclarationSyntax)typeDecl.Members[0];
2162            var methodDecl = eventDecl.AccessorList.Accessors[0];
2163            var model = compilation.GetSemanticModel(tree);
2164
2165            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2166            blockStatement = speculatedMethod.Body;
2167
2168            SemanticModel speculativeModel;
2169            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2170            Assert.True(success);
2171            Assert.NotNull(speculativeModel);
2172
2173            VerifySpeculativeSemanticModelForMethodBody(blockStatement, speculativeModel);
2174        }
2175
2176        [Fact]
2177        public void TestGetSpeculativeSemanticModelForMethodBody_DeclaredLocal()
2178        {
2179            var compilation = CreateCompilationWithMscorlib(@"
2180class C 
2181{
2182  void M(int x)
2183  {
2184    int y = 1000;     
2185  }
2186}
2187");
2188
2189            var tree = compilation.SyntaxTrees[0];
2190            var root = tree.GetCompilationUnitRoot();
2191            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2192            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
2193            var model = compilation.GetSemanticModel(tree);
2194
2195            // different name local
2196            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"{ int z = 0; }");
2197            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2198            blockStatement = speculatedMethod.Body;
2199
2200            SemanticModel speculativeModel;
2201            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2202            Assert.True(success);
2203            Assert.NotNull(speculativeModel);
2204
2205            var declarator = ((LocalDeclarationStatementSyntax)blockStatement.Statements[0]).Declaration.Variables.First();
2206            var local = speculativeModel.GetDeclaredSymbol(declarator);
2207            Assert.NotNull(local);
2208            Assert.Equal("z", local.Name);
2209            Assert.Equal(SymbolKind.Local, local.Kind);
2210            Assert.Equal("Int32", ((LocalSymbol)local).Type.Name);
2211
2212            // same name local
2213            blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"{ string y = null; }");
2214            speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2215            blockStatement = speculatedMethod.Body;
2216            success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2217            Assert.True(success);
2218            Assert.NotNull(speculativeModel);
2219            declarator = ((LocalDeclarationStatementSyntax)blockStatement.Statements[0]).Declaration.Variables.First();
2220            local = speculativeModel.GetDeclaredSymbol(declarator);
2221            Assert.NotNull(local);
2222            Assert.Equal("y", local.Name);
2223            Assert.Equal(SymbolKind.Local, local.Kind);
2224            Assert.Equal("String", ((LocalSymbol)local).Type.Name);
2225
2226            // parameter symbol
2227            blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"{ var y = x; }");
2228            speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2229            blockStatement = speculatedMethod.Body;
2230            success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2231            Assert.True(success);
2232            Assert.NotNull(speculativeModel);
2233            declarator = ((LocalDeclarationStatementSyntax)blockStatement.Statements[0]).Declaration.Variables.First();
2234            local = speculativeModel.GetDeclaredSymbol(declarator);
2235            Assert.NotNull(local);
2236            Assert.Equal("y", local.Name);
2237            Assert.Equal(SymbolKind.Local, local.Kind);
2238            Assert.Equal("Int32", ((LocalSymbol)local).Type.Name);
2239
2240            var param = speculativeModel.GetSymbolInfo(declarator.Initializer.Value).Symbol;
2241            Assert.NotNull(param);
2242            Assert.Equal(SymbolKind.Parameter, param.Kind);
2243            var paramSymbol = (ParameterSymbol)param;
2244            Assert.Equal("x", paramSymbol.Name);
2245            Assert.Equal("Int32", paramSymbol.Type.Name);
2246        }
2247
2248        [Fact]
2249        public void TestGetSpeculativeSemanticModelForMethodBody_GetDeclaredLabelSymbol()
2250        {
2251            var compilation = CreateCompilationWithMscorlib(@"
2252class C 
2253{
2254  void M(int x)
2255  {
2256    int y = 1000;     
2257  }
2258}
2259");
2260
2261            var tree = compilation.SyntaxTrees[0];
2262            var root = tree.GetCompilationUnitRoot();
2263            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2264            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
2265            var model = compilation.GetSemanticModel(tree);
2266            
2267            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"{ label: y++; }");
2268            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2269            blockStatement = speculatedMethod.Body;
2270            var labeledStatement = blockStatement.Statements[0];
2271
2272            SemanticModel speculativeModel;
2273            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2274            Assert.True(success);
2275            Assert.NotNull(speculativeModel);
2276
2277            var label = speculativeModel.GetDeclaredSymbol(labeledStatement);
2278            Assert.NotNull(label);
2279            Assert.Equal("label", label.Name);
2280            Assert.Equal(SymbolKind.Label, label.Kind);
2281        }
2282
2283        [Fact]
2284        public void TestGetSpeculativeSemanticModelForMethodBody_GetDeclaredLambdaParameterSymbol()
2285        {
2286            var compilation = CreateCompilationWithMscorlibAndSystemCore(@"
2287using System.Linq;
2288
2289class C 
2290{
2291  void M(int x)
2292  {
2293    int z = 0;
2294  }
2295}
2296");
2297
2298            var tree = compilation.SyntaxTrees[0];
2299            var root = tree.GetCompilationUnitRoot();
2300            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2301            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
2302            var model = compilation.GetSemanticModel(tree);
2303
2304            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"{ Func<int, int> var = (z) => x + z; }");
2305            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2306            blockStatement = speculatedMethod.Body;
2307
2308            SemanticModel speculativeModel;
2309            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].Span.End, speculatedMethod, out speculativeModel);
2310            Assert.True(success);
2311            Assert.NotNull(speculativeModel);
2312
2313            var lambdaExpression = blockStatement.Statements[0].DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().FirstOrDefault();
2314            var lambdaParam = lambdaExpression.ParameterList.Parameters[0];
2315            var parameterSymbol = speculativeModel.GetDeclaredSymbol(lambdaParam);
2316            Assert.NotNull(parameterSymbol);
2317            Assert.Equal("z", parameterSymbol.Name);
2318        }
2319
2320        private static void TestGetSpeculativeSemanticModelForTypeSyntax_Common(
2321            SemanticModel model,
2322            int position,
2323            TypeSyntax speculatedTypeSyntax,
2324            SpeculativeBindingOption bindingOption,
2325            SymbolKind expectedSymbolKind,
2326            string expectedTypeDislayString)
2327        {
2328            Assert.False(model.IsSpeculativeSemanticModel);
2329            Assert.Null(model.ParentModel);
2330            Assert.Equal(0, model.OriginalPositionForSpeculation);
2331
2332            SemanticModel speculativeModel;
2333            var success = model.TryGetSpeculativeSemanticModel(position, speculatedTypeSyntax, out speculativeModel, bindingOption);
2334            Assert.True(success);
2335            Assert.NotNull(speculativeModel);
2336
2337            Assert.True(speculativeModel.IsSpeculativeSemanticModel);
2338            Assert.Equal(model, speculativeModel.ParentModel);
2339            Assert.NotNull(speculativeModel);
2340            Assert.Equal(position, speculativeModel.OriginalPositionForSpeculation);
2341
2342            var symbol = speculativeModel.GetSymbolInfo(speculatedTypeSyntax).Symbol;
2343            Assert.NotNull(symbol);
2344            Assert.Equal(expectedSymbolKind, symbol.Kind);
2345            Assert.Equal(expectedTypeDislayString, symbol.ToDisplayString());
2346
2347            var typeSymbol = speculativeModel.GetTypeInfo(speculatedTypeSyntax).Type;
2348            Assert.NotNull(symbol);
2349            Assert.Equal(expectedSymbolKind, symbol.Kind);
2350            Assert.Equal(expectedTypeDislayString, symbol.ToDisplayString());
2351
2352            if (speculatedTypeSyntax.Kind == SyntaxKind.QualifiedName)
2353            {
2354                var right = ((QualifiedNameSyntax)speculatedTypeSyntax).Right;
2355
2356                symbol = speculativeModel.GetSymbolInfo(right).Symbol;
2357                Assert.NotNull(symbol);
2358                Assert.Equal(expectedSymbolKind, symbol.Kind);
2359                Assert.Equal(expectedTypeDislayString, symbol.ToDisplayString());
2360
2361                typeSymbol = speculativeModel.GetTypeInfo(right).Type;
2362                Assert.NotNull(symbol);
2363                Assert.Equal(expectedSymbolKind, symbol.Kind);
2364                Assert.Equal(expectedTypeDislayString, symbol.ToDisplayString());
2365            }
2366        }
2367
2368        [Fact]
2369        public void TestGetSpeculativeSemanticModelForMethodBody_SwitchStatement()
2370        {
2371            var compilation = CreateCompilationWithMscorlib(@"
2372using System;
2373
2374class C 
2375{
2376  void M(int x)
2377  {
2378    switch(x)
2379    {
2380        case 0:
2381            Console.WriteLine(x);
2382            break;
2383    }
2384  }
2385}
2386");
2387
2388            var tree = compilation.SyntaxTrees[0];
2389            var root = tree.GetCompilationUnitRoot();
2390            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2391            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
2392            var model = compilation.GetSemanticModel(tree);
2393
2394            var blockStatement = (BlockSyntax)SyntaxFactory.ParseStatement(@"{
2395    switch(x)
2396    {
2397        case 1:
2398            Console.WriteLine(x);
2399            break;
2400    }
2401}");
2402
2403            var speculatedMethod = methodDecl.ReplaceNode(methodDecl.Body, blockStatement);
2404            blockStatement = speculatedMethod.Body;
2405            var switchStatement = (SwitchStatementSyntax)blockStatement.Statements[0];
2406
2407            SemanticModel speculativeModel;
2408            var success = model.TryGetSpeculativeSemanticModelForMethodBody(methodDecl.Body.Statements[0].SpanStart, speculatedMethod, out speculativeModel);
2409            Assert.True(success);
2410            Assert.NotNull(speculativeModel);
2411
2412            var switchLabel = switchStatement.Sections[0].Labels[0];
2413            var constantVal = speculativeModel.GetConstantValue(switchLabel.Value);
2414            Assert.True(constantVal.HasValue);
2415            Assert.Equal(1, constantVal.Value);
2416        }
2417
2418        [Fact]
2419        public void TestGetSpeculativeSemanticModelForTypeSyntax_InGlobalUsing()
2420        {
2421            var compilation = CreateCompilationWithMscorlib(@"using System.Runtime;");
2422
2423            var tree = compilation.SyntaxTrees[0];
2424            var root = tree.GetCompilationUnitRoot();
2425            var usingStatement = root.Usings[0];
2426            var model = compilation.GetSemanticModel(tree);
2427
2428            var speculatedUsingExpression = SyntaxFactory.ParseName("System.Collections");
2429            TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, usingStatement.Name.Position,
2430                speculatedUsingExpression, SpeculativeBindingOption.BindAsTypeOrNamespace, SymbolKind.Namespace, "System.Collections");
2431        }
2432
2433        [Fact]
2434        public void TestGetSpeculativeSemanticModelForTypeSyntax_InGlobalAlias()
2435        {
2436            var compilation = CreateCompilationWithMscorlib(@"using A = System.Exception;");
2437
2438            var tree = compilation.SyntaxTrees[0];
2439            var root = tree.GetCompilationUnitRoot();
2440            var usingStatement = root.Usings[0];
2441            var model = compilation.GetSemanticModel(tree);
2442
2443            var speculatedUsingExpression = SyntaxFactory.ParseName("System.ArgumentException");
2444            TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, usingStatement.Name.Position,
2445                speculatedUsingExpression, SpeculativeBindingOption.BindAsExpression, SymbolKind.NamedType, "System.ArgumentException");
2446        }
2447
2448        [Fact]
2449        public void TestGetSpeculativeSemanticModelForTypeSyntax_InBaseList()
2450        {
2451            var compilation = CreateCompilationWithMscorlib(@"
2452class MyException : System.Exception
2453{
2454}
2455");
2456
2457            var tree = compilation.SyntaxTrees[0];
2458            var root = tree.GetCompilationUnitRoot();
2459            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2460            var baseList = typeDecl.BaseList;
2461            var model = compilation.GetSemanticModel(tree);
2462
2463            var speculatedTypeExpression = SyntaxFactory.ParseName("System.ArgumentException");
2464            TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, baseList.SpanStart,
2465                speculatedTypeExpression, SpeculativeBindingOption.BindAsTypeOrNamespace, SymbolKind.NamedType, "System.ArgumentException");
2466        }
2467
2468        [Fact]
2469        public void TestGetSpeculativeSemanticModelForTypeSyntax_InMemberDeclaration()
2470        {
2471            var compilation = CreateCompilationWithMscorlib(@"
2472class Program
2473{
2474    System.Exception field = null;
2475    System.Exception Method(System.Exception param)
2476    {
2477        return field;
2478    }
2479}
2480");
2481
2482            var tree = compilation.SyntaxTrees[0];
2483            var root = tree.GetCompilationUnitRoot();
2484            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2485            var fieldDecl = (FieldDeclarationSyntax)typeDecl.Members[0];
2486            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[1];
2487            var model = compilation.GetSemanticModel(tree);
2488
2489            var speculatedTypeExpression = SyntaxFactory.ParseName("System.ArgumentException");
2490            TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, fieldDecl.SpanStart,
2491                speculatedTypeExpression, SpeculativeBindingOption.BindAsTypeOrNamespace, SymbolKind.NamedType, "System.ArgumentException");
2492
2493            TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, methodDecl.ReturnType.SpanStart,
2494                speculatedTypeExpression, SpeculativeBindingOption.BindAsTypeOrNamespace, SymbolKind.NamedType, "System.ArgumentException");
2495
2496            TestGetSpeculativeSemanticModelForTypeSyntax_Common(model, methodDecl.ParameterList.Parameters.First().SpanStart,
2497                speculatedTypeExpression, SpeculativeBindingOption.BindAsTypeOrNamespace, SymbolKind.NamedType, "System.ArgumentException");
2498        }
2499
2500        [Fact]
2501        public void TestGetSpeculativeSemanticModelForTypeSyntax_AliasName()
2502        {
2503            var compilation = CreateCompilationWithMscorlib(@"
2504using A = System.ArgumentException;
2505
2506class Program
2507{
2508    System.Exception field = null;
2509}
2510");
2511
2512            var tree = compilation.SyntaxTrees[0];
2513            var root = tree.GetCompilationUnitRoot();
2514            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2515            var fieldDecl = (FieldDeclarationSyntax)typeDecl.Members[0];
2516            var model = compilation.GetSemanticModel(tree);
2517
2518            var speculatedAliasName = SyntaxFactory.ParseName("A");
2519
2520            SemanticModel speculativeModel;
2521            var success = model.TryGetSpeculativeSemanticModel(fieldDecl.SpanStart, speculatedAliasName, out speculativeModel);
2522            Assert.True(success);
2523            Assert.NotNull(speculativeModel);
2524
2525            var symbol = (AliasSymbol)speculativeModel.GetAliasInfo(speculatedAliasName);
2526            Assert.NotNull(symbol);
2527            Assert.Equal("A", symbol.ToDisplayString());
2528            Assert.Equal("System.ArgumentException", symbol.Target.ToDisplayString());
2529        }
2530
2531        [Fact]
2532        public void TestGetSpeculativeSemanticModelForTypeCrefSyntax()
2533        {
2534            var compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"
2535/// <summary>
2536/// <see cref=""int""/>
2537/// </summary>
2538class A { }
2539");
2540
2541            var tree = compilation.SyntaxTrees[0];
2542            var root = tree.GetCompilationUnitRoot();
2543            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2544            var cref = typeDecl.DescendantNodes(descendIntoTrivia: true).OfType<TypeCrefSyntax>().Single();
2545
2546            var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
2547            var symbol = model.GetSymbolInfo(cref.Type).Symbol;
2548            Assert.NotNull(symbol);
2549            Assert.Equal("int", symbol.ToDisplayString());
2550
2551            var speculatedCref = (TypeCrefSyntax)SyntaxFactory.ParseCref("object");
2552
2553            // TryGetSpeculativeSemanticModel
2554            SemanticModel speculativeModel;
2555            var success = model.TryGetSpeculativeSemanticModel(cref.SpanStart, speculatedCref, out speculativeModel);
2556            Assert.True(success);
2557            Assert.NotNull(speculativeModel);
2558
2559            symbol = speculativeModel.GetSymbolInfo(speculatedCref.Type).Symbol;
2560            Assert.NotNull(symbol);
2561            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2562            Assert.Equal("object", symbol.ToDisplayString());
2563
2564            // GetSpeculativeSymbolInfo
2565            symbol = model.GetSpeculativeSymbolInfo(cref.SpanStart, speculatedCref).Symbol;
2566            Assert.NotNull(symbol);
2567            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2568            Assert.Equal("object", symbol.ToDisplayString());
2569        }
2570
2571        [Fact]
2572        public void TestGetSpeculativeSemanticModelForNameMemberCrefSyntax()
2573        {
2574            var compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"
2575/// <summary>
2576/// <see cref=""int""/>
2577/// </summary>
2578class A { }
2579");
2580
2581            var tree = compilation.SyntaxTrees[0];
2582            var root = tree.GetCompilationUnitRoot();
2583            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2584            var cref = typeDecl.DescendantNodes(descendIntoTrivia: true).OfType<TypeCrefSyntax>().Single();
2585
2586            var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
2587            var symbol = model.GetSymbolInfo(cref.Type).Symbol;
2588            Assert.NotNull(symbol);
2589            Assert.Equal("int", symbol.ToDisplayString());
2590
2591            var speculatedCref = (NameMemberCrefSyntax)SyntaxFactory.ParseCref("A");
2592
2593            // TryGetSpeculativeSemanticModel
2594            SemanticModel speculativeModel;
2595            var success = model.TryGetSpeculativeSemanticModel(cref.SpanStart, speculatedCref, out speculativeModel);
2596            Assert.True(success);
2597            Assert.NotNull(speculativeModel);
2598
2599            symbol = speculativeModel.GetSymbolInfo(speculatedCref.Name).Symbol;
2600            Assert.NotNull(symbol);
2601            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2602            Assert.Equal("A", symbol.ToDisplayString());
2603
2604            // GetSpeculativeSymbolInfo
2605            symbol = model.GetSpeculativeSymbolInfo(cref.SpanStart, speculatedCref).Symbol;
2606            Assert.NotNull(symbol);
2607            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2608            Assert.Equal("A", symbol.ToDisplayString());
2609        }
2610
2611        [Fact]
2612        public void TestGetSpeculativeSemanticModelForQualifiedCrefSyntax()
2613        {
2614            var compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"
2615/// <summary>
2616/// <see cref=""int""/>
2617/// </summary>
2618class A
2619{
2620    class B { }
2621
2622    static void M() { }
2623}
2624");
2625
2626            var tree = compilation.SyntaxTrees[0];
2627            var root = tree.GetCompilationUnitRoot();
2628            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2629            var cref = typeDecl.DescendantNodes(descendIntoTrivia: true).OfType<TypeCrefSyntax>().Single();
2630
2631            var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
2632            var symbol = model.GetSymbolInfo(cref.Type).Symbol;
2633            Assert.NotNull(symbol);
2634            Assert.Equal("int", symbol.ToDisplayString());
2635
2636            var speculatedCref = (QualifiedCrefSyntax)SyntaxFactory.ParseCref("A.B");
2637
2638            // Type member: TryGetSpeculativeSemanticModel
2639            SemanticModel speculativeModel;
2640            var success = model.TryGetSpeculativeSemanticModel(cref.SpanStart, speculatedCref, out speculativeModel);
2641            Assert.True(success);
2642            Assert.NotNull(speculativeModel);
2643
2644            symbol = speculativeModel.GetSymbolInfo(speculatedCref).Symbol;
2645            Assert.NotNull(symbol);
2646            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2647            Assert.Equal("A.B", symbol.ToDisplayString());
2648
2649            symbol = speculativeModel.GetSymbolInfo(speculatedCref.Member).Symbol;
2650            Assert.NotNull(symbol);
2651            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2652            Assert.Equal("A.B", symbol.ToDisplayString());
2653
2654            symbol = speculativeModel.GetTypeInfo(speculatedCref.Container).Type;
2655            Assert.NotNull(symbol);
2656            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2657            Assert.Equal("A", symbol.ToDisplayString());
2658
2659            // Type member: GetSpeculativeSymbolInfo
2660            symbol = model.GetSpeculativeSymbolInfo(cref.SpanStart, speculatedCref).Symbol;
2661            Assert.NotNull(symbol);
2662            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2663            Assert.Equal("A.B", symbol.ToDisplayString());
2664
2665            // Method member: TryGetSpeculativeSemanticModel
2666            speculatedCref = (QualifiedCrefSyntax)SyntaxFactory.ParseCref("A.M");
2667
2668            success = model.TryGetSpeculativeSemanticModel(cref.SpanStart, speculatedCref, out speculativeModel);
2669            Assert.True(success);
2670            Assert.NotNull(speculativeModel);
2671
2672            symbol = speculativeModel.GetSymbolInfo(speculatedCref).Symbol;
2673            Assert.NotNull(symbol);
2674            Assert.Equal(SymbolKind.Method, symbol.Kind);
2675            Assert.Equal("A.M()", symbol.ToDisplayString());
2676
2677            symbol = speculativeModel.GetSymbolInfo(speculatedCref.Member).Symbol;
2678            Assert.NotNull(symbol);
2679            Assert.Equal(SymbolKind.Method, symbol.Kind);
2680            Assert.Equal("A.M()", symbol.ToDisplayString());
2681
2682            symbol = speculativeModel.GetTypeInfo(speculatedCref.Container).Type;
2683            Assert.NotNull(symbol);
2684            Assert.Equal(SymbolKind.NamedType, symbol.Kind);
2685            Assert.Equal("A", symbol.ToDisplayString());
2686
2687            // Method member: GetSpeculativeSymbolInfo
2688            symbol = model.GetSpeculativeSymbolInfo(cref.SpanStart, speculatedCref).Symbol;
2689            Assert.NotNull(symbol);
2690            Assert.Equal(SymbolKind.Method, symbol.Kind);
2691            Assert.Equal("A.M()", symbol.ToDisplayString());
2692        }
2693
2694        [Fact]
2695        public void TestGetSpeculativeSemanticModelForCrefSyntax_InvalidPosition()
2696        {
2697            var compilation = CreateCompilationWithMscorlibAndDocumentationComments(@"
2698/// <summary>
2699/// <see cref=""int""/>
2700/// </summary>
2701class A
2702{
2703    static void M() { }
2704}
2705");
2706
2707            var tree = compilation.SyntaxTrees[0];
2708            var root = tree.GetCompilationUnitRoot();
2709            var typeDecl = (TypeDeclarationSyntax)root.Members[0];
2710            var methodDecl = (MethodDeclarationSyntax)typeDecl.Members[0];
2711            var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
2712
2713            var speculatedCref = (TypeCrefSyntax)SyntaxFactory.ParseCref("object");
2714
2715            // TryGetSpeculativeSemanticModel
2716            SemanticModel speculativeModel;
2717            var success = model.TryGetSpeculativeSemanticModel(typeDecl.SpanStart, speculatedCref, out speculativeModel);
2718            Assert.False(success);
2719
2720            success = model.TryGetSpeculativeSemanticModel(methodDecl.Body.SpanStart, speculatedCref, out speculativeModel);
2721            Assert.False(success);
2722
2723            // GetSpeculativeSymbolInfo
2724            var symbolInfo = model.GetSpeculativeSymbolInfo(methodDecl.Body.SpanStart, speculatedCref);
2725            Assert.Null(symbolInfo.Symbol);
2726        }
2727
2728        [WorkItem(731108, "DevDiv")]
2729        [Fact]
2730        public void Repro731108()
2731        {
2732            var source = @"
2733public class C
2734{
2735    static void Main()
2736    {
2737        M(async x => x);
2738    }
2739
2740    static void M(C c)
2741    {
2742    }
2743}
2744";
2745
2746            var comp = CreateCompilationWithMscorlib(source);
2747            var tree = comp.SyntaxTrees.Single();
2748            var model = comp.GetSemanticModel(tree);
2749
2750            var syntax = tree.GetRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single().
2751                Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().Single();
2752            Assert.Equal("x", syntax.Identifier.ValueText);
2753
2754            var symbol = model.GetSymbolInfo(syntax).Symbol;
2755            Assert.Equal(SymbolKind.Parameter, symbol.Kind);
2756            Assert.Equal("x", symbol.Name);
2757            Assert.Equal(TypeKind.Error, ((ParameterSymbol)symbol).Type.TypeKind);
2758        }
2759
2760        [WorkItem(783566, "DevDiv")]
2761        [Fact]
2762        public void SpeculateAboutYieldStatement1()
2763        {
2764            var source = @"
2765class C
2766{
2767    void M() // No way to infer iterator element type.
2768    {
2769        return;
2770    }
2771}
2772";
2773
2774            var comp = CreateCompilationWithMscorlib(source);
2775            comp.VerifyDiagnostics();
2776
2777            var tree = comp.SyntaxTrees.Single();
2778            var model = comp.GetSemanticModel(tree);
2779
2780            var position = source.IndexOf("return");
2781            var yieldStatement = (YieldStatementSyntax)SyntaxFactory.ParseStatement("yield return 1;");
2782
2783            SemanticModel speculativeModel;
2784            var success = model.TryGetSpeculativeSemanticModel(position, yieldStatement, out speculativeModel);
2785            Assert.True(success);
2786            Assert.NotNull(speculativeModel);
2787
2788            var info = speculativeModel.GetTypeInfo(yieldStatement.Expression);
2789            Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
2790            Assert.Equal(TypeKind.Error, info.ConvertedType.TypeKind);
2791        }
2792
2793        [WorkItem(783566, "DevDiv")]
2794        [Fact]
2795        public void SpeculateAboutYieldStatement2()
2796        {
2797            var source = @"
2798using System.Collections.Generic;
2799
2800class C
2801{
2802    IEnumerable<long> M() // Can infer iterator element type.
2803    {
2804        return null;
2805    }
2806}
2807";
2808
2809            var comp = CreateCompilationWithMscorlib(source);
2810            comp.VerifyDiagnostics();
2811
2812            var tree = comp.SyntaxTrees.Single();
2813            var model = comp.GetSemanticModel(tree);
2814
2815            var position = source.IndexOf("return");
2816            var yieldStatement = (YieldStatementSyntax)SyntaxFactory.ParseStatement("yield return 1;");
2817
2818            SemanticModel speculativeModel;
2819            var success = model.TryGetSpeculativeSemanticModel(position, yieldStatement, out speculativeModel);
2820            Assert.True(success);
2821            Assert.NotNull(speculativeModel);
2822
2823            var info = speculativeModel.GetTypeInfo(yieldStatement.Expression);
2824            Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
2825            Assert.Equal(SpecialType.System_Int64, info.ConvertedType.SpecialType);
2826        }
2827
2828        [WorkItem(791794, "DevDiv")]
2829        [Fact]
2830        public void SpeculateAboutOmittedArraySizeInCref()
2831        {
2832            var source = @"
2833/// <see cref=""int""/>
2834class C
2835{
2836}
2837";
2838
2839            var comp = CreateCompilationWithMscorlibAndDocumentationComments(source);
2840            comp.VerifyDiagnostics();
2841
2842            var tree = comp.SyntaxTrees.Single();
2843            var model = comp.GetSemanticModel(tree);
2844
2845            var position = source.IndexOf("int");
2846            var typeSyntax = SyntaxFactory.ParseTypeName("System.Collections.Generic.IEnumerable<C[]>");
2847
2848            SemanticModel speculativeModel;
2849            var success = model.TryGetSpeculativeSemanticModel(position, typeSyntax, out speculativeModel);
2850            Assert.True(success);
2851            Assert.NotNull(speculativeModel);
2852
2853            var omittedArraySize = typeSyntax.DescendantNodes().OfType<OmittedArraySizeExpressionSyntax>().Single();
2854            var info = speculativeModel.GetSymbolInfo(omittedArraySize); // Used to throw NRE.
2855            Assert.Null(info.Symbol);
2856            Assert.Equal(CandidateReason.None, info.CandidateReason);
2857            Assert.Equal(0, info.CandidateSymbols.Length);
2858        }
2859
2860        [WorkItem(784255, "DevDiv")]
2861        [Fact]
2862        public void Repro784255()
2863        {
2864            var source = @"
2865using System;
2866
2867public class CategoryAttribute : Attribute
2868{
2869    public CategoryAttribute(string s) { }
2870    private CategoryAttribute() { }
2871}
2872
2873struct S
2874{
2875}
2876";
2877
2878            var comp = CreateCompilationWithMscorlib(source);
2879            comp.VerifyDiagnostics();
2880
2881            var tree = comp.SyntaxTrees.Single();
2882            var model = comp.GetSemanticModel(tree);
2883
2884            var position = source.IndexOf("struct");
2885            var attributeSyntax = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Category"));
2886
2887            SemanticModel speculativeModel;
2888            var success = model.TryGetSpeculativeSemanticModel(position, attributeSyntax, out speculativeModel);
2889            Assert.True(success);
2890            Assert.NotNull(speculativeModel);
2891
2892            var info = speculativeModel.GetSymbolInfo(attributeSyntax.Name);
2893        }
2894
2895        [WorkItem(823791, "DevDiv")]
2896        [Fact]
2897        public void LambdaArgumentInBadCall_Constructor()
2898        {
2899            var source = @"
2900using System;
2901
2902class Test
2903{
2904    void M()
2905    {
2906        new Test(s => s.
2907    }
2908
2909    Test(Action<string> a, int i) { }
2910}
2911";
2912            CheckLambdaArgumentInBadCall(source);
2913        }
2914
2915        [WorkItem(823791, "DevDiv")]
2916        [Fact]
2917        public void LambdaArgumentInBadCall_Method()
2918        {
2919            var source = @"
2920using System;
2921
2922class Test
2923{
2924    void M()
2925    {
2926        Method(s => s.
2927    }
2928
2929    void Method(Action<string> a, int i) { }
2930}
2931";
2932            CheckLambdaArgumentInBadCall(source);
2933        }
2934
2935        [WorkItem(823791, "DevDiv")]
2936        [Fact]
2937        public void LambdaArgumentInBadCall_Indexer()
2938        {
2939            var source = @"
2940using System;
2941
2942class Test
2943{
2944    void M()
2945    {
2946        var t = this[s => s.
2947    }
2948
2949    int this[Action<string> a, int i] { get { return 0; } }
2950}
2951";
2952            CheckLambdaArgumentInBadCall(source);
2953        }
2954
2955        [WorkItem(823791, "DevDiv")]
2956        [Fact]
2957        public void LambdaArgumentInBadCall_Delegate()
2958        {
2959            var source = @"
2960using System;
2961
2962class Test
2963{
2964    void M()
2965    {
2966        d(s => s.
2967    }
2968
2969    Action<Action<string>, int> d = null;
2970}
2971";
2972            CheckLambdaArgumentInBadCall(source);
2973        }
2974
2975        [WorkItem(823791, "DevDiv")]
2976        [Fact]
2977        public void LambdaArgumentInBadCall_ConstructorInitializer()
2978        {
2979            var source = @"
2980using System;
2981
2982class Test
2983{
2984    protected Test(Action<string> a, int i) { }
2985}
2986
2987class Derived : Test
2988{
2989    Derived()
2990        : base(s => s.
2991    {
2992    }
2993}
2994";
2995            CheckLambdaArgumentInBadCall(source);
2996        }
2997
2998        private static void CheckLambdaArgumentInBadCall(string source)
2999        {
3000            var comp = CreateCompilationWithMscorlib(source);
3001
3002            var tree = comp.SyntaxTrees.Single();
3003            Assert.NotEmpty(tree.GetDiagnostics());
3004
3005            var memberAccess = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single();
3006            var identifier = (IdentifierNameSyntax)memberAccess.Expression;
3007            Assert.Equal("s", identifier.Identifier.ValueText);
3008
3009            var stringType = comp.GetSpecialType(SpecialType.System_String);
3010            var actionType = comp.GetWellKnownType(WellKnownType.System_Action_T).Construct(stringType);
3011
3012            var model = comp.GetSemanticModel(tree);
3013
3014            // Can't walk up to ArgumentListSyntax because indexers use BracketedArgumentListSyntax.
3015            var expr = identifier.FirstAncestorOrSelf<ArgumentSyntax>().Parent.Parent;
3016
3017            var exprInfo = model.GetSymbolInfo(expr);
3018            var firstParamType = ((Symbol)exprInfo.CandidateSymbols.Single()).GetParameterTypes().First();
3019            Assert.Equal(actionType, firstParamType);
3020
3021            var identifierInfo = model.GetTypeInfo(identifier);
3022            Assert.Equal(stringType, identifierInfo.Type);
3023            Assert.Equal(stringType, identifierInfo.ConvertedType);
3024        }
3025
3026        [WorkItem(850907, "DevDiv")]
3027        [Fact]
3028        public void ExtensionMethodViability()
3029        {
3030            var source = @"
3031static class Extensions
3032{
3033    private static void ToString(this object o, int x)
3034    {
3035        o.ToString(1);
3036    }
3037}
3038";
3039
3040            var comp = CreateCompilationWithMscorlibAndSystemCore(source);
3041            comp.VerifyDiagnostics();
3042
3043            var extensionMethod = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Extensions").GetMember<MethodSymbol>("ToString");
3044
3045            var tree = comp.SyntaxTrees.Single();
3046            var model = comp.GetSemanticModel(tree);
3047
3048            var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single();
3049
3050            var memberGroup = model.GetMemberGroup(callSyntax.Expression);
3051            Assert.Contains(extensionMethod.ReduceExtensionMethod(), memberGroup);
3052        }
3053
3054        [WorkItem(849698, "DevDiv")]
3055        [Fact]
3056        public void LookupExternAlias()
3057        {
3058            var source = @"
3059extern alias Alias;
3060
3061class C
3062{
3063    static void Main()
3064    {
3065        Alias::C.M(); 
3066    }
3067
3068";
3069
3070            var libBytes = CreateCompilationWithMscorlib("", assemblyName: "lib").EmitToArray();
3071            var comp = CreateCompilationWithMscorlib(source, new[] { new MetadataImageReference(libBytes, aliases: ImmutableArray.Create("Alias")) });
3072            var tree = comp.SyntaxTrees.Single();
3073            var model = comp.GetSemanticModel(tree);
3074
3075            var syntax = tree.GetRoot().DescendantNodes().OfType<AliasQualifiedNameSyntax>().Single();
3076
3077            var symbol = model.LookupSymbols(syntax.SpanStart, name: "Alias").Single();
3078            Assert.Equal("Alias", symbol.Name);
3079            Assert.Equal(SymbolKind.Alias, symbol.Kind);
3080
3081            var target = (NamespaceSymbol)((AliasSymbol)symbol).Target;
3082            Assert.True(target.IsGlobalNamespace);
3083            Assert.Equal("lib", target.ContainingAssembly.Name);
3084        }
3085
3086        [Fact]
3087        public void Regression01()
3088        {
3089            Regression(@"
3090using System;
3091
3092class MyClass {
3093
3094	public protected int intI = 1;
3095
3096	public static int Main() {
3097		return 1;
3098	}
3099}"
3100                );
3101        }
3102
3103        [Fact]
3104        public void Regression02()
3105        {
3106            Regression(@"
3107using System;
3108
3109class Convert
3110{
3111	public static void Main()
3112	{
3113		S s = new S();
3114	}
3115}
3116"
3117                );
3118        }
3119
3120        [Fact]
3121        public void Regression03()
3122        {
3123            Regression(@"
3124using System;
3125
3126namespace Microsoft.Conformance.Expressions
3127{
3128    using basic097LevelOne.basic097LevelTwo;
3129
3130    public class basic097I<A1>
3131    {
3132        public static int Method()
3133        {
3134            return 0;
3135        }
3136    }
3137
3138    namespace basic097LevelOne
3139    {
3140        namespace basic097LevelTwo
3141        {
3142            public class basic097I<A1>
3143            {
3144            }
3145        }
3146    } 
3147}"
3148                );
3149        }
3150
3151        #region "regression helper"
3152        private void Regression(string text)
3153        {
3154            var tree = Parse(text);
3155            var compilation = CreateCompilationWithMscorlib(tree);
3156            var model = compilation.GetSemanticModel(tree);
3157            var exprSynList = new List<ExpressionSyntax>();
3158            GetExpressionSyntax(tree.GetCompilationUnitRoot(), exprSynList);
3159
3160            // Console.WriteLine("Roslyn Symbol Info: ");
3161            foreach (var exprSyn in exprSynList)
3162            {
3163                var expr = exprSyn.ToString();
3164                // Console.WriteLine("Expression: " + expr);
3165                var type = model.GetTypeInfo(exprSyn).Type;
3166                // Console.WriteLine("Type: " + type);
3167                // Console.WriteLine();
3168            }
3169        }
3170        private static void GetExpressionSyntax(SyntaxNode node, List<ExpressionSyntax> exprSynList)
3171        {
3172            if (node is ExpressionSyntax)
3173                exprSynList.Add(node as ExpressionSyntax);
3174
3175            foreach (var child in node.ChildNodesAndTokens())
3176                if (child.IsNode)
3177                    GetExpressionSyntax(child.AsNode(), exprSynList);
3178        }
3179        #endregion
3180
3181    }
3182}