SymbolKeyTests.cs 30.8 KB
Newer Older
J
Jonathon Marolf 已提交
1 2 3
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
M
Matt Warren 已提交
4 5 6 7 8 9 10 11

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
12
using Microsoft.CodeAnalysis.Test.Utilities;
M
Matt Warren 已提交
13 14 15 16 17 18
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.UnitTests
{
19
    [UseExportProvider]
20
    public class SymbolKeyTests : TestBase
M
Matt Warren 已提交
21
    {
C
Cyrus Najmabadi 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        [Fact]
        public void TestVersionMismatch()
        {
            var source = @"

public class C
{
    public class B { };
    public delegate int D(int v);

    public int F;
    public B F2;
    public int P { get; set;}
    public B P2 { get; set; }
    public void M() { };
    public void M(int a) { };
    public void M(int a, string b) { };
    public void M(string a, int b) { };
    public void M(B b) { };
    public int M2() { return 0; }
    public int M2(int a) { return 0; }
    public int M2(int a, string b) { return 0; }
    public int M2(string a, int b) { return 0; }
    public B M3() { return default(B); }
    public int this[int index] { get { return 0; } }
    public int this[int a, int b] { get { return 0; } }
    public B this[B b] { get { return b; } }
    public event D E;
    public event D E2 { add; remove; }
}
";
            var compilation = GetCompilation(source, LanguageNames.CSharp);
            foreach (var symbol in GetDeclaredSymbols(compilation))
            {
                Test(symbol, compilation);
            }

            return;

            static void Test(ISymbol symbol, Compilation compilation)
            {
                TestVersion(symbol, compilation, SymbolKey.FormatVersion - 1);
                TestVersion(symbol, compilation, SymbolKey.FormatVersion + 1);
                TestVersion(symbol, compilation, int.MaxValue);
            }

            static void TestVersion(ISymbol symbol, Compilation compilation, int version)
            {
                var id = SymbolKey.CreateStringWorker(version, symbol);
                Assert.NotNull(id);
                var found = SymbolKey.ResolveString(id, compilation).GetAnySymbol();
                Assert.Null(found);
            }
        }

M
Matt Warren 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        [Fact]
        public void TestMemberDeclarations()
        {
            var source = @"

public class C
{
    public class B { };
    public delegate int D(int v);

    public int F;
    public B F2;
    public int P { get; set;}
    public B P2 { get; set; }
    public void M() { };
    public void M(int a) { };
    public void M(int a, string b) { };
    public void M(string a, int b) { };
    public void M(B b) { };
    public int M2() { return 0; }
    public int M2(int a) { return 0; }
    public int M2(int a, string b) { return 0; }
    public int M2(string a, int b) { return 0; }
    public B M3() { return default(B); }
    public int this[int index] { get { return 0; } }
    public int this[int a, int b] { get { return 0; } }
    public B this[B b] { get { return b; } }
    public event D E;
    public event D E2 { add; remove; }
}
";
108
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
109 110 111
            TestRoundTrip(GetDeclaredSymbols(compilation), compilation);
        }

112 113
        [Fact]
        [WorkItem(14364, "https://github.com/dotnet/roslyn/issues/14364")]
114 115 116 117 118 119 120 121 122 123 124
        public void TestVBParameterizedEvent()
        {
            var source = @"
Module M
    Event E(x As Object)
End Module
";
            var compilation = GetCompilation(source, LanguageNames.VisualBasic);
            TestRoundTrip(GetAllSymbols(compilation.GetSemanticModel(compilation.SyntaxTrees.Single())), compilation);
        }

M
Matt Warren 已提交
125 126 127 128 129 130 131 132 133 134
        [Fact]
        public void TestNamespaceDeclarations()
        {
            var source = @"
namespace N { }
namespace A.B { }
namespace A { namespace B.C { } }
namespace A { namespace B { namespace C { } } }
namespace A { namespace N { } }
";
135
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
136
            var symbols = GetDeclaredSymbols(compilation);
137 138
            Assert.Equal(5, symbols.Count());
            Assert.Equal(new[] { "N", "A", "A.B", "A.B.C", "A.N" },
139
                symbols.Select(s => s.ToDisplayString()));
M
Matt Warren 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            TestRoundTrip(symbols, compilation);
        }

        [Fact]
        public void TestConstructedTypeReferences()
        {
            var source = @"
using System.Collections.Generic;

public class C
{
    public List<int> G1;
    public List<List<int>> G2;
    public Dictionary<string, int> G3;
    public int[] A1;
    public int[,] A2;
    public int[,,] A3;
    public List<int>[] A4;
    public int* P1;
    public int** p2;
}
";
162
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
            TestRoundTrip(GetDeclaredSymbols(compilation).OfType<IFieldSymbol>().Select(fs => fs.Type), compilation);
        }

        [Fact]
        public void TestErrorTypeReferences()
        {
            var source = @"
using System.Collections.Generic;

public class C
{
    public T E1;
    public List<T> E2;
    public T<int> E3;
    public T<A> E4;
}
";
180
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            TestRoundTrip(GetDeclaredSymbols(compilation).OfType<IFieldSymbol>().Select(fs => fs.Type), compilation, s => s.ToDisplayString());
        }

        [Fact]
        public void TestParameterDeclarations()
        {
            var source = @"
using System.Collections.Generic;

public class C
{
    public void M(int p) { }
    public void M(int p1, int p2) { }
    public void M<T>(T p) { }
    public void M<T>(T[] p) { }
    public void M<T>(List<T> p) { }
    public void M<T>(T* p) { }
    public void M(ref int p)  { }
}
";
201
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
            TestRoundTrip(GetDeclaredSymbols(compilation).OfType<IMethodSymbol>().SelectMany(ms => ms.Parameters), compilation);
        }

        [Fact]
        public void TestTypeParameters()
        {
            var source = @"
public class C
{
    public void M() { }
    public void M<A>(A a) { }
    public void M<A>(int i) { }
    public void M<A, B>(A a, B b) { }
    public void M<A, B>(A a, int i) { }
    public void M<A, B>(int i, B b) { }
    public void M<A, B>(B b, A a) { }
    public void M<A, B>(B b, int i) { }
    public void M<A, B>(int i, A a) { }
    public void M<A, B>(int i, int j) { }
    public void M(C c) { }
    public int GetInt() { return 0 ; }
    public A GetA<A>(A a) { return a; }
    public A GetA<A, B>(A a, B b) { return a; }
    public B GetB<A, B>(A a, B b) { return b; }
C
Fix  
Cyrus Najmabadi 已提交
226
    public C GetC() { return default(C); }
M
Matt Warren 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
}

public class C<T>
{
    public void M() { }
    public void M(T t) { }
    public void M<A>(A a) { }
    public void M<A>(T t, A a) { }
    public void M<A, B>(A a, B b) { }
    public void M<A, B>(B b, A a) { }
    public void M(C<T> c) { }
    public void M(C<int> c) { }
    public T GetT() { return default(T); }
    public C<T> GetCT() { return default(C<T>); }
    public C<int> GetCInt() { return default(C<int>); }
    public C<A> GetCA<A>() { return default(C<A>); }
}

public class C<S, T>
{
    public void M() { }
    public void M(T t, S s) { }
    public void M<A>(A a) { }
    public void M<A>(T t, S s, A a) { }
    public void M<A>(A a, T t, S s) { }
    public void M<A, B>(A a, B b) { }
    public void M<A, B>(T t, S s, A a, B b) { }
    public void M<A, B>(A a, B b, T t, S s) { }
    public T GetT() { return default(T); } 
    public S GetS() { return default(S); }
    public C<S, T> GetCST() { return default(C<S,T>); }
    public C<T, S> GetCTS() { return default(C<T, S>); }
    public C<T, A> GetCTA<A>() { return default(C<T, A>); }
}
";

263
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
            TestRoundTrip(GetDeclaredSymbols(compilation), compilation);
        }

        [Fact]
        public void TestLocals()
        {
            var source = @"
using System.Collections.Generic;

public class C
{
    public void M() {
        int a, b;
        if (a > b) {
           int c = a + b;
        }

        {
            string d = "";
        }

        {
            double d = 0.0;
        }

        {
            bool d = false;
        }

        var q = new { };
    }
}
";
297
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
            var symbols = GetDeclaredSymbols(compilation).OfType<IMethodSymbol>().SelectMany(ms => GetInteriorSymbols(ms, compilation).OfType<ILocalSymbol>()).ToList();
            Assert.Equal(7, symbols.Count);
            TestRoundTrip(symbols, compilation);
        }

        [Fact]
        public void TestLabels()
        {
            var source = @"
using System.Collections.Generic;

public class C
{
    public void M() {
        start: goto end;
        end: goto start;
        end: ; // duplicate label
        }
    }
}
";
319
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            var symbols = GetDeclaredSymbols(compilation).OfType<IMethodSymbol>().SelectMany(ms => GetInteriorSymbols(ms, compilation).OfType<ILabelSymbol>()).ToList();
            Assert.Equal(3, symbols.Count);
            TestRoundTrip(symbols, compilation);
        }

        [Fact]
        public void TestRangeVariables()
        {
            var source = @"
using System.Collections.Generic;

public class C
{
    public void M() {
        int[] xs = new int[] { 1, 2, 3, 4 };
        
        {
            var q = from x in xs where x > 2 select x;
        }

        {
            var q2 = from x in xs where x < 4 select x;
        }
    }
}
";
346
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
            var symbols = GetDeclaredSymbols(compilation).OfType<IMethodSymbol>().SelectMany(ms => GetInteriorSymbols(ms, compilation).OfType<IRangeVariableSymbol>()).ToList();
            Assert.Equal(2, symbols.Count);
            TestRoundTrip(symbols, compilation);
        }

        [Fact]
        public void TestMethodReferences()
        {
            var source = @"
public class C
{
    public void M() { }
    public void M(int x) { }
    public void M2<T>() { }
    public void M2<T>(T t) { }
    public T M3<T>(T t) { return default(T); }
   
    public void Test() {
        M():
        M(0);
        M2<string>();
        M2(0);
        var tmp = M3(0);
    }
}
";
373
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
374 375
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);
376
            var symbols = tree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.InvocationExpressionSyntax>().Select(s => model.GetSymbolInfo(s).Symbol).ToList();
M
Matt Warren 已提交
377 378 379 380 381 382 383
            Assert.True(symbols.Count > 0);
            TestRoundTrip(symbols, compilation);
        }
        [Fact]
        public void TestExtensionMethodReferences()
        {
            var source = @"
384
using System;
M
Matt Warren 已提交
385 386 387 388 389 390 391 392 393
using System.Collections.Generic;

public static class E 
{
    public static void Z(this C c) { }
    public static void Z(this C c, int x) { }
    public static void Z<T>(this T t, string y) { }
    public static void Z<T>(this T t, T t2) { }
    public static void Y<T, S>(this T t, S other) { }
394
    public static TResult Select<TSource, TResult>(this IEnumerable<TSource> collection, Func<TSource, TResult> selector) { return null;}
M
Matt Warren 已提交
395 396 397 398 399 400 401 402 403 404
}

public class C
{
    public void M() {
        this.Z();
        this.Z(1);
        this.Z(""test"");
        this.Z(this);
        this.Y(1.0);
405
        new[] { 1, 2, 3 }.Select(
M
Matt Warren 已提交
406 407 408
    }
}
";
409
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
410 411
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);
412
            var symbols = tree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.InvocationExpressionSyntax>().Select(s => model.GetSymbolInfo(s).GetAnySymbol()).ToList();
M
Matt Warren 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
            Assert.True(symbols.Count > 0);
            Assert.True(symbols.All(s => s.IsReducedExtension()));
            TestRoundTrip(symbols, compilation);
        }

        [Fact]
        public void TestAliasSymbols()
        {
            var source = @"
using G=System.Collections.Generic;
using GL=System.Collections.Generic.List<int>;

public class C
{
    public G.List<int> F;
    public GL F2;
}
";
431
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
432 433 434
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);

435
            var symbols = tree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.UsingDirectiveSyntax>().Select(s => model.GetDeclaredSymbol(s)).ToList();
M
Matt Warren 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
            Assert.Equal(2, symbols.Count);
            Assert.NotNull(symbols[0]);
            Assert.True(symbols[0] is IAliasSymbol);
            TestRoundTrip(symbols, compilation);

            var refSymbols = GetDeclaredSymbols(compilation).OfType<IFieldSymbol>().Select(f => f.Type).ToList();
            Assert.Equal(2, refSymbols.Count);
            TestRoundTrip(refSymbols, compilation);
        }

        [Fact]
        public void TestDynamicSymbols()
        {
            var source = @"
public class C
{
    public dynamic F;
    public dynamic[] F2;
}
";
456
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);

            var symbols = GetDeclaredSymbols(compilation).OfType<IFieldSymbol>().Select(f => f.Type).ToList();
            Assert.Equal(2, symbols.Count);
            TestRoundTrip(symbols, compilation);
        }

        [Fact]
        public void TestSelfReferentialGenericMethod()
        {
            var source = @"
public class C
{
    public void M<S, T>() { }
}
";
474
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);

            var method = GetDeclaredSymbols(compilation).OfType<IMethodSymbol>().First();
            var constructed = method.Construct(compilation.GetSpecialType(SpecialType.System_Int32), method.TypeParameters[1]);

            TestRoundTrip(constructed, compilation);
        }

        [Fact]
        public void TestSelfReferentialGenericType()
        {
            var source = @"
public class C<S, T>
{
}
";
492
            var compilation = GetCompilation(source, LanguageNames.CSharp);
M
Matt Warren 已提交
493 494 495 496 497 498 499 500 501
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);

            var type = GetDeclaredSymbols(compilation).OfType<INamedTypeSymbol>().First();
            var constructed = type.Construct(compilation.GetSpecialType(SpecialType.System_Int32), type.TypeParameters[1]);

            TestRoundTrip(constructed, compilation);
        }

502 503 504 505 506 507 508 509 510 511
        [Fact, WorkItem(235912, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=235912&_a=edit")]
        public void TestNestedGenericType()
        {
            var source = @"
public class A<TOuter>
{
    public class B<TInner>
    {
    }
}";
512
            var compilation = GetCompilation(source, LanguageNames.CSharp);
513 514 515 516 517 518
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);

            var outer = GetDeclaredSymbols(compilation).OfType<INamedTypeSymbol>().First(s => s.Name == "A");
            var constructed = outer.Construct(compilation.GetSpecialType(SpecialType.System_String));
            var inner = constructed.GetTypeMembers().Single();
519
            TestRoundTrip(inner, compilation);
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
        }

        [Fact, WorkItem(235912, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=235912&_a=edit")]
        public void TestNestedGenericType1()
        {
            var source = @"
using System.Collections.Generic;

public class A<T1>
{
    public class B<T2>
    {
        void M<T3>(T1 t1, T2, T3 t3, List<int> l1, List<T3> l2) { }
    }
}";
535
            var compilation = GetCompilation(source, LanguageNames.CSharp);
536 537 538 539 540 541 542
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);

            var a = GetDeclaredSymbols(compilation).OfType<INamedTypeSymbol>().Single(s => s.Name == "A");
            var a_b = a.GetTypeMembers().Single();
            var a_b_m = a_b.GetMembers().Single(s => s.Name == "M");

543 544 545
            TestRoundTrip(a, compilation);
            TestRoundTrip(a_b, compilation);
            TestRoundTrip(a_b_m, compilation);
546 547 548 549

            var a_string = a.Construct(compilation.GetSpecialType(SpecialType.System_String));
            var a_string_b = a_string.GetTypeMembers().Single();
            var a_string_b_m = a_string_b.GetMembers().Single(s => s.Name == "M");
550 551 552
            TestRoundTrip(a_string, compilation);
            TestRoundTrip(a_string_b, compilation);
            TestRoundTrip(a_string_b_m, compilation);
553 554 555

            var a_string_b_int = a_string_b.Construct(compilation.GetSpecialType(SpecialType.System_Int32));
            var a_string_b_int_m = a_string_b_int.GetMembers().Single(s => s.Name == "M");
556 557
            TestRoundTrip(a_string_b_int, compilation);
            TestRoundTrip(a_string_b_int_m, compilation);
558 559

            var a_string_b_int_m_datetime = ((IMethodSymbol)a_string_b_int_m).Construct(compilation.GetSpecialType(SpecialType.System_DateTime));
560
            TestRoundTrip(a_string_b_int_m_datetime, compilation);
561 562 563 564

            var a_b_int = a_b.Construct(compilation.GetSpecialType(SpecialType.System_Int32));
            var a_b_int_m = a_b_int.GetMembers().Single(s => s.Name == "M");
            var a_b_int_m_datetime = ((IMethodSymbol)a_b_int_m).Construct(compilation.GetSpecialType(SpecialType.System_DateTime));
565 566 567
            TestRoundTrip(a_b_int, compilation);
            TestRoundTrip(a_b_int_m, compilation);
            TestRoundTrip(a_b_int_m_datetime, compilation);
568 569

            var a_b_m_datetime = ((IMethodSymbol)a_b_m).Construct(compilation.GetSpecialType(SpecialType.System_DateTime));
570
            TestRoundTrip(a_b_m_datetime, compilation);
571 572
        }

573 574 575 576 577
        [Fact, WorkItem(235912, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=235912&_a=edit")]
        public void TestGenericTypeTypeParameter()
        {
            var source = @"class C<T> { }";

578
            var compilation = GetCompilation(source, LanguageNames.CSharp);
579 580 581
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);

582
            var typeParameter = GetDeclaredSymbols(compilation).OfType<INamedTypeSymbol>().Where(n => !n.IsImplicitlyDeclared).Single().TypeParameters.Single();
583

584
            TestRoundTrip(typeParameter, compilation);
585 586 587 588 589 590 591
        }

        [Fact, WorkItem(235912, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=235912&_a=edit")]
        public void TestGenericMethodTypeParameter()
        {
            var source = @"class C { void M<T>() { } }";

592
            var compilation = GetCompilation(source, LanguageNames.CSharp);
593 594
            var tree = compilation.SyntaxTrees.First();
            var model = compilation.GetSemanticModel(tree);
595 596
            var typeParameter = GetDeclaredSymbols(compilation).OfType<INamedTypeSymbol>()
                .Where(n => !n.IsImplicitlyDeclared).Single().GetMembers("M").OfType<IMethodSymbol>().Single().TypeParameters.Single();
597

598
            TestRoundTrip(typeParameter, compilation);
599 600
        }

R
Ravi Chande 已提交
601 602 603 604 605 606
        [Fact, WorkItem(11193, "https://github.com/dotnet/roslyn/issues/11193")]
        public async Task TestGetInteriorSymbolsDoesNotCrashOnSpeculativeSemanticModel()
        {
            var markup = @"
class C
{
607
    void goo()
R
Ravi Chande 已提交
608 609 610 611 612 613 614 615
    {
        System.Func<int> lambda = () => 
        {
        int x;
        $$
        }
    }
}";
C
CyrusNajmabadi 已提交
616
            MarkupTestFile.GetPosition(markup, out var text, out int position);
R
Ravi Chande 已提交
617 618 619 620 621 622 623 624

            var sourceText = SourceText.From(text);
            var workspace = new AdhocWorkspace();
            var project = workspace.AddProject("Test", LanguageNames.CSharp);
            var document = workspace.AddDocument(project.Id, "testdocument", sourceText);

            var firstModel = await document.GetSemanticModelAsync();
            var tree1 = await document.GetSyntaxTreeAsync();
625
            var basemethod1 = tree1.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor<CSharp.Syntax.BaseMethodDeclarationSyntax>();
R
Ravi Chande 已提交
626 627 628 629 630 631 632

            // Modify the document so we can use the old semantic model as a base.
            var updated = sourceText.WithChanges(new TextChange(new TextSpan(position, 0), "insertion"));
            workspace.TryApplyChanges(document.WithText(updated).Project.Solution);

            document = workspace.CurrentSolution.GetDocument(document.Id);
            var tree2 = await document.GetSyntaxTreeAsync();
633
            var basemethod2 = tree2.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor<CSharp.Syntax.BaseMethodDeclarationSyntax>();
R
Ravi Chande 已提交
634

C
CyrusNajmabadi 已提交
635
            var service = CSharp.CSharpSemanticFactsService.Instance;
C
CyrusNajmabadi 已提交
636
            var m = service.TryGetSpeculativeSemanticModel(firstModel, basemethod1, basemethod2, out var testModel);
R
Ravi Chande 已提交
637 638 639 640

            var xSymbol = testModel.LookupSymbols(position).First(s => s.Name == "x");

            // This should not throw an exception.
J
Jared Parsons 已提交
641
            Assert.NotEqual(default, SymbolKey.Create(xSymbol));
R
Ravi Chande 已提交
642 643
        }

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        [Fact]
        public void TestGenericMethodTypeParameterMissing1()
        {
            var source1 = @"
public class C
{
    void M<T>(T t) { }
}
";

            var source2 = @"
public class C
{
}
";

            var compilation1 = GetCompilation(source1, LanguageNames.CSharp);
            var compilation2 = GetCompilation(source2, LanguageNames.CSharp);

            var methods = GetDeclaredSymbols(compilation1).OfType<IMethodSymbol>();
            foreach (var method in methods)
            {
                var key = SymbolKey.Create(method);
                key.Resolve(compilation2);
            }
        }

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
        [Fact, WorkItem(377839, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=377839")]
        public void TestConstructedMethodInsideLocalFunctionWithTypeParameters()
        {
            var source = @"
using System.Linq;

class C
{
    void Method()
    {
        object LocalFunction<T>()
        {
            return Enumerable.Empty<T>();
        }
    }
}";
            var compilation = GetCompilation(source, LanguageNames.CSharp);
            var symbols = GetAllSymbols(
                compilation.GetSemanticModel(compilation.SyntaxTrees.Single()),
                n => n is CSharp.Syntax.MemberAccessExpressionSyntax || n is CSharp.Syntax.InvocationExpressionSyntax);

            var tested = false;
            foreach (var symbol in symbols)
            {
                // Ensure we don't crash getting these symbol keys.
696
                var id = SymbolKey.CreateString(symbol);
697
                Assert.NotNull(id);
698
                var found = SymbolKey.ResolveString(id, compilation).GetAnySymbol();
699 700 701
                Assert.NotNull(found);

                // note: we don't check that the symbols are equal.  That's because the compiler
C
Fix  
Cyrus Najmabadi 已提交
702
                // doesn't guarantee that the TypeParameters will be the same across successive
703 704 705 706 707 708 709 710 711
                // invocations. 
                Assert.Equal(symbol.OriginalDefinition, found.OriginalDefinition);

                tested = true;
            }

            Assert.True(tested);
        }

C
CyrusNajmabadi 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
        [Fact, WorkItem(17702, "https://github.com/dotnet/roslyn/issues/17702")]
        public void TestTupleWithLocalTypeReferences1()
        {
            var source = @"
using System.Linq;

class C
{
    void Method((C, int) t)
    {
    }
}";
            // Tuples store locations along with them.  But we can only recover those locations
            // if we're re-resolving into a compilation with the same files.
            var compilation1 = GetCompilation(source, LanguageNames.CSharp, "File1.cs");
            var compilation2 = GetCompilation(source, LanguageNames.CSharp, "File2.cs");

            var symbol = GetAllSymbols(
                compilation1.GetSemanticModel(compilation1.SyntaxTrees.Single()),
                n => n is CSharp.Syntax.MethodDeclarationSyntax).Single();

            // Ensure we don't crash getting these symbol keys.
734
            var id = SymbolKey.CreateString(symbol);
C
CyrusNajmabadi 已提交
735
            Assert.NotNull(id);
C
CyrusNajmabadi 已提交
736 737 738

            // Validate that if the client does ask to resolve locations that we
            // do not crash if those locations cannot be found.
C
Fix  
Cyrus Najmabadi 已提交
739
            var found = SymbolKey.ResolveString(id, compilation2).GetAnySymbol();
C
CyrusNajmabadi 已提交
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
            Assert.NotNull(found);

            Assert.Equal(symbol.Name, found.Name);
            Assert.Equal(symbol.Kind, found.Kind);

            var method = found as IMethodSymbol;
            Assert.True(method.Parameters[0].Type.IsTupleType);
        }

        [Fact, WorkItem(17702, "https://github.com/dotnet/roslyn/issues/17702")]
        public void TestTupleWithLocalTypeReferences2()
        {
            var source = @"
using System.Linq;

class C
{
    void Method((C a, int b) t)
    {
    }
}";
            // Tuples store locations along with them.  But we can only recover those locations
            // if we're re-resolving into a compilation with the same files.
            var compilation1 = GetCompilation(source, LanguageNames.CSharp, "File1.cs");
            var compilation2 = GetCompilation(source, LanguageNames.CSharp, "File2.cs");

            var symbol = GetAllSymbols(
                compilation1.GetSemanticModel(compilation1.SyntaxTrees.Single()),
                n => n is CSharp.Syntax.MethodDeclarationSyntax).Single();

            // Ensure we don't crash getting these symbol keys.
771
            var id = SymbolKey.CreateString(symbol);
C
CyrusNajmabadi 已提交
772
            Assert.NotNull(id);
C
CyrusNajmabadi 已提交
773 774 775

            // Validate that if the client does ask to resolve locations that we
            // do not crash if those locations cannot be found.
C
Fix  
Cyrus Najmabadi 已提交
776
            var found = SymbolKey.ResolveString(id, compilation2).GetAnySymbol();
C
CyrusNajmabadi 已提交
777 778 779 780 781 782 783 784 785
            Assert.NotNull(found);

            Assert.Equal(symbol.Name, found.Name);
            Assert.Equal(symbol.Kind, found.Kind);

            var method = found as IMethodSymbol;
            Assert.True(method.Parameters[0].Type.IsTupleType);
        }

M
Matt Warren 已提交
786 787 788 789
        private void TestRoundTrip(IEnumerable<ISymbol> symbols, Compilation compilation, Func<ISymbol, object> fnId = null)
        {
            foreach (var symbol in symbols)
            {
790
                TestRoundTrip(symbol, compilation, fnId: fnId);
M
Matt Warren 已提交
791 792 793 794 795
            }
        }

        private void TestRoundTrip(ISymbol symbol, Compilation compilation, Func<ISymbol, object> fnId = null)
        {
796
            var id = SymbolKey.CreateString(symbol);
M
Matt Warren 已提交
797
            Assert.NotNull(id);
798
            var found = SymbolKey.ResolveString(id, compilation).GetAnySymbol();
M
Matt Warren 已提交
799 800 801 802 803 804 805 806 807 808 809 810 811 812
            Assert.NotNull(found);

            if (fnId != null)
            {
                var expected = fnId(symbol);
                var actual = fnId(found);
                Assert.Equal(expected, actual);
            }
            else
            {
                Assert.Equal(symbol, found);
            }
        }

C
CyrusNajmabadi 已提交
813
        private Compilation GetCompilation(string source, string language, string path = "")
814
        {
815 816 817 818 819 820
            var references = new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

821 822
            if (language == LanguageNames.CSharp)
            {
C
CyrusNajmabadi 已提交
823
                var tree = CSharp.SyntaxFactory.ParseSyntaxTree(source, path: path);
824
                return CSharp.CSharpCompilation.Create("Test", syntaxTrees: new[] { tree }, references: references);
825 826 827
            }
            else if (language == LanguageNames.VisualBasic)
            {
C
CyrusNajmabadi 已提交
828
                var tree = VisualBasic.SyntaxFactory.ParseSyntaxTree(source, path: path);
829
                return VisualBasic.VisualBasicCompilation.Create("Test", syntaxTrees: new[] { tree }, references: references);
830 831 832 833 834
            }

            throw new NotSupportedException();
        }

835 836
        private List<ISymbol> GetAllSymbols(
            SemanticModel model, Func<SyntaxNode, bool> predicate = null)
837 838
        {
            var list = new List<ISymbol>();
839
            GetAllSymbols(model, model.SyntaxTree.GetRoot(), list, predicate);
840 841 842
            return list;
        }

843 844 845
        private void GetAllSymbols(
            SemanticModel model, SyntaxNode node,
            List<ISymbol> list, Func<SyntaxNode, bool> predicate)
M
Matt Warren 已提交
846
        {
847
            if (predicate == null || predicate(node))
848
            {
849 850 851 852 853
                var symbol = model.GetDeclaredSymbol(node);
                if (symbol != null)
                {
                    list.Add(symbol);
                }
854

855 856 857 858 859
                symbol = model.GetSymbolInfo(node).GetAnySymbol();
                if (symbol != null)
                {
                    list.Add(symbol);
                }
860 861 862 863 864 865
            }

            foreach (var child in node.ChildNodesAndTokens())
            {
                if (child.IsNode)
                {
866
                    GetAllSymbols(model, child.AsNode(), list, predicate);
867 868
                }
            }
M
Matt Warren 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        }

        private List<ISymbol> GetDeclaredSymbols(Compilation compilation)
        {
            var list = new List<ISymbol>();
            GetDeclaredSymbols(compilation.Assembly.GlobalNamespace, list);
            return list;
        }

        private void GetDeclaredSymbols(INamespaceOrTypeSymbol container, List<ISymbol> symbols)
        {
            foreach (var member in container.GetMembers())
            {
                symbols.Add(member);

C
CyrusNajmabadi 已提交
884
                if (member is INamespaceOrTypeSymbol nsOrType)
M
Matt Warren 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
                {
                    GetDeclaredSymbols(nsOrType, symbols);
                }
            }
        }

        private static IEnumerable<ISymbol> GetInteriorSymbols(ISymbol containingSymbol, Compilation compilation)
        {
            var results = new List<ISymbol>();

            foreach (var declaringLocation in containingSymbol.DeclaringSyntaxReferences)
            {
                var node = declaringLocation.GetSyntax();
                if (node.Language == LanguageNames.VisualBasic)
                {
                    node = node.Parent;
                }

                var semanticModel = compilation.GetSemanticModel(node.SyntaxTree);

                GetInteriorSymbols(semanticModel, node, results);
            }

            return results;
        }

        private static void GetInteriorSymbols(SemanticModel model, SyntaxNode root, List<ISymbol> symbols)
        {
            foreach (var token in root.DescendantNodes())
            {
                var symbol = model.GetDeclaredSymbol(token);
                if (symbol != null)
                {
                    symbols.Add(symbol);
                }
            }
        }
    }
}