SolutionTests.cs 56.1 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3

using System;
4
using System.Collections.Immutable;
5
using System.Composition;
P
Pilchie 已提交
6 7
using System.Linq;
using System.Runtime.CompilerServices;
8
using System.Text;
P
Pilchie 已提交
9 10 11 12 13
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
14
using Microsoft.CodeAnalysis.Diagnostics;
P
Pilchie 已提交
15
using Microsoft.CodeAnalysis.Formatting;
16 17 18
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Host.UnitTests;
P
Pilchie 已提交
19 20 21
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
22
using Microsoft.CodeAnalysis.VisualBasic;
P
Pilchie 已提交
23 24
using Roslyn.Test.Utilities;
using Xunit;
25
using CS = Microsoft.CodeAnalysis.CSharp;
P
Pilchie 已提交
26 27 28 29 30

namespace Microsoft.CodeAnalysis.UnitTests
{
    public partial class SolutionTests : TestBase
    {
31
        private static readonly MetadataReference s_mscorlib = TestReferences.NetFx.v4_0_30319.mscorlib;
P
Pilchie 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

        public static byte[] GetResourceBytes(string fileName)
        {
            var fullName = @"Microsoft.CodeAnalysis.UnitTests.TestFiles." + fileName;
            var resourceStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(fullName);
            if (resourceStream != null)
            {
                using (resourceStream)
                {
                    var bytes = new byte[resourceStream.Length];
                    resourceStream.Read(bytes, 0, (int)resourceStream.Length);
                    return bytes;
                }
            }

            return null;
        }

        private Solution CreateSolution()
        {
52
            return new AdhocWorkspace().CurrentSolution;
P
Pilchie 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestCreateSolution()
        {
            var sol = CreateSolution();
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestAddProject()
        {
            var sol = CreateSolution();
            var pid = ProjectId.CreateNewId();
            sol = sol.AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp);
            Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects");
            Assert.NotNull(pid);
            var project = sol.GetProject(pid);
            Assert.False(project.HasDocuments);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestUpdateAssemblyName()
        {
            var solution = CreateSolution();
            var project1 = ProjectId.CreateNewId();
            solution = solution.AddProject(project1, "foo", "foo.dll", LanguageNames.CSharp);
            solution = solution.WithProjectAssemblyName(project1, "bar");
            var project = solution.GetProject(project1);
            Assert.Equal("bar", project.AssemblyName);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
85
        [WorkItem(543964, "DevDiv")]
P
Pilchie 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        public void MultipleProjectsWithSameDisplayName()
        {
            var solution = CreateSolution();
            var project1 = ProjectId.CreateNewId();
            var project2 = ProjectId.CreateNewId();
            solution = solution.AddProject(project1, "name", "assemblyName", LanguageNames.CSharp);
            solution = solution.AddProject(project2, "name", "assemblyName", LanguageNames.CSharp);
            Assert.Equal(2, solution.GetProjectsByName("name").Count());
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public Solution TestAddFirstDocument()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);
            var sol = CreateSolution()
                .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                .AddDocument(did, "foo.cs", "public class Foo { }");

            // verify project & document
            Assert.NotNull(pid);
            var project = sol.GetProject(pid);
            Assert.NotNull(project);
            Assert.True(sol.ContainsProject(pid), "Solution was expected to have project " + pid);
            Assert.True(project.HasDocuments, "Project was expected to have documents");
            Assert.Equal(project, sol.GetProject(pid));
            Assert.NotNull(did);
            var document = sol.GetDocument(did);
            Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did);
            Assert.Equal(document, project.GetDocument(did));
            Assert.Equal(document, sol.GetDocument(did));
            var semantics = document.GetSemanticModelAsync().Result;
            Assert.NotNull(semantics);

            ValidateSolutionAndCompilations(sol);

            return sol;
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestAddSecondDocument()
        {
            var sol = TestAddFirstDocument();
            var pid = sol.Projects.Single().Id;
            var did = DocumentId.CreateNewId(pid);
            sol = sol.AddDocument(did, "bar.cs", "public class Bar { }");

            // verify project & document
            var project = sol.GetProject(pid);
            Assert.NotNull(project);
            Assert.NotNull(did);
            var document = sol.GetDocument(did);
            Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did);
            Assert.Equal(document, project.GetDocument(did));
            Assert.Equal(document, sol.GetDocument(did));

            ValidateSolutionAndCompilations(sol);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestOneCSharpProject()
        {
            var sol = CreateSolutionWithOneCSharpProject();
            ValidateSolutionAndCompilations(sol);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestTwoCSharpProjects()
        {
            var sol = CreateSolutionWithTwoCSharpProjects();
            ValidateSolutionAndCompilations(sol);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestCrossLanguageProjects()
        {
            var sol = CreateCrossLanguageSolution();
            ValidateSolutionAndCompilations(sol);
        }

        private Solution CreateSolutionWithOneCSharpProject()
        {
            return this.CreateSolution()
                       .AddProject("foo", "foo.dll", LanguageNames.CSharp)
170
                       .AddMetadataReference(s_mscorlib)
P
Pilchie 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
                       .AddDocument("foo.cs", "public class Foo { }")
                       .Project.Solution;
        }

        private Solution CreateSolutionWithTwoCSharpProjects()
        {
            var pm1 = ProjectId.CreateNewId();
            var pm2 = ProjectId.CreateNewId();
            var doc1 = DocumentId.CreateNewId(pm1);
            var doc2 = DocumentId.CreateNewId(pm2);
            return this.CreateSolution()
                       .AddProject(pm1, "foo", "foo.dll", LanguageNames.CSharp)
                       .AddProject(pm2, "bar", "bar.dll", LanguageNames.CSharp)
                       .AddProjectReference(pm2, new ProjectReference(pm1))
                       .AddDocument(doc1, "foo.cs", "public class Foo { }")
                       .AddDocument(doc2, "bar.cs", "public class Bar : Foo { }");
        }

        private Solution CreateCrossLanguageSolution()
        {
            var pm1 = ProjectId.CreateNewId();
            var pm2 = ProjectId.CreateNewId();
            return this.CreateSolution()
                       .AddProject(pm1, "foo", "foo.dll", LanguageNames.CSharp)
195
                       .AddMetadataReference(pm1, s_mscorlib)
P
Pilchie 已提交
196
                       .AddProject(pm2, "bar", "bar.dll", LanguageNames.VisualBasic)
197
                       .AddMetadataReference(pm2, s_mscorlib)
P
Pilchie 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 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 263 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 297 298 299 300 301 302 303
                       .AddProjectReference(pm2, new ProjectReference(pm1))
                       .AddDocument(DocumentId.CreateNewId(pm1), "foo.cs", "public class X { }")
                       .AddDocument(DocumentId.CreateNewId(pm2), "bar.vb", "Public Class Y\r\nInherits X\r\nEnd Class");
        }

        private void ValidateSolutionAndCompilations(Solution solution)
        {
            foreach (var project in solution.Projects)
            {
                Assert.True(solution.ContainsProject(project.Id), "Solution was expected to have project " + project.Id);
                Assert.Equal(project, solution.GetProject(project.Id));

                // these won't always be unique in real-world but should be for these tests
                Assert.Equal(project, solution.GetProjectsByName(project.Name).FirstOrDefault());

                var compilation = project.GetCompilationAsync().Result;
                Assert.NotNull(compilation);

                // check that the options are the same
                Assert.Equal(project.CompilationOptions, compilation.Options);

                // check that all known metadata references are present in the compilation
                foreach (var meta in project.MetadataReferences)
                {
                    Assert.True(compilation.References.Contains(meta), "Compilation references were expected to contain " + meta);
                }

                // check that all project-to-project reference metadata is present in the compilation
                foreach (var referenced in project.ProjectReferences)
                {
                    if (solution.ContainsProject(referenced.ProjectId))
                    {
                        var referencedMetadata = solution.GetMetadataReferenceAsync(referenced, solution.GetProjectState(project.Id), CancellationToken.None).Result;
                        Assert.NotNull(referencedMetadata);
                        var compilationReference = referencedMetadata as CompilationReference;
                        if (compilationReference != null)
                        {
                            compilation.References.Single(r =>
                            {
                                var cr = r as CompilationReference;
                                return cr != null && cr.Compilation == compilationReference.Compilation;
                            });
                        }
                    }
                }

                // check that the syntax trees are the same
                var docs = project.Documents.ToList();
                var trees = compilation.SyntaxTrees.ToList();
                Assert.Equal(docs.Count, trees.Count);

                foreach (var doc in docs)
                {
                    Assert.True(trees.Contains(doc.GetSyntaxTreeAsync().Result), "trees list was expected to contain the syntax tree of doc");
                }
            }
        }

#if false
        [Fact(Skip = "641963"), Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestDeepProjectReferenceTree()
        {
            int projectCount = 5;
            var solution = CreateSolutionWithProjectDependencyChain(projectCount);
            ProjectId[] projectIds = solution.ProjectIds.ToArray();

            Compilation compilation;
            for (int i = 0; i < projectCount; i++)
            {
                Assert.False(solution.GetProject(projectIds[i]).TryGetCompilation(out compilation));
            }

            var top = solution.GetCompilationAsync(projectIds.Last(), CancellationToken.None).Result;
            var partialSolution = solution.GetPartialSolution();
            for (int i = 0; i < projectCount; i++)
            {
                // While holding a compilation, we also hold its references, plus one further level
                // of references alive.  However, the references are only partial Declaration 
                // compilations
                var isPartialAvailable = i >= projectCount - 3;
                var isFinalAvailable = i == projectCount - 1;

                var projectId = projectIds[i];
                Assert.Equal(isFinalAvailable, solution.GetProject(projectId).TryGetCompilation(out compilation));
                Assert.Equal(isPartialAvailable, partialSolution.ProjectIds.Contains(projectId) && partialSolution.GetProject(projectId).TryGetCompilation(out compilation));
            }
        }
#endif

        private Solution CreateSolutionWithProjectDependencyChain(int projectCount)
        {
            Solution solution = this.CreateNotKeptAliveSolution();
            projectCount = 5;
            var projectIds = Enumerable.Range(0, projectCount).Select(i => ProjectId.CreateNewId()).ToArray();
            for (int i = 0; i < projectCount; i++)
            {
                solution = solution.AddProject(projectIds[i], i.ToString(), i.ToString(), LanguageNames.CSharp);
                if (i >= 1)
                {
                    solution = solution.AddProjectReference(projectIds[i], new ProjectReference(projectIds[i - 1]));
                }
            }

            return solution;
        }

304
        [WorkItem(636431, "DevDiv")]
P
Pilchie 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestProjectDependencyLoading()
        {
            int projectCount = 3;
            var solution = CreateSolutionWithProjectDependencyChain(projectCount);
            ProjectId[] projectIds = solution.ProjectIds.ToArray();

            var compilation0 = solution.GetCompilationAsync(projectIds[0], CancellationToken.None).Result;
            var compilation2 = solution.GetCompilationAsync(projectIds[2], CancellationToken.None).Result;
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestAddMetadataReferences()
        {
319
            var csharpReference = MetadataReference.CreateFromImage(GetResourceBytes(@"CSharpProject.dll"));
P
Pilchie 已提交
320 321 322
            var solution = CreateSolution();
            var project1 = ProjectId.CreateNewId();
            solution = solution.AddProject(project1, "foo", "foo.dll", LanguageNames.CSharp);
323
            solution = solution.AddMetadataReference(project1, s_mscorlib);
P
Pilchie 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339

            // For CSharp Reference
            solution = solution.AddMetadataReference(project1, csharpReference);
            var assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(csharpReference);
            var namespacesAndTypes = assemblyReference.GlobalNamespace.GetAllNamespacesAndTypes(CancellationToken.None);
            var foundSymbol = from symbol in namespacesAndTypes
                              where symbol.Name.Equals("CSharpClass")
                              select symbol;
            Assert.Equal(1, foundSymbol.Count());
            solution = solution.RemoveMetadataReference(project1, csharpReference);
            assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(csharpReference);
            Assert.Null(assemblyReference);

            ValidateSolutionAndCompilations(solution);
        }

340
        private class MockDiagnosticAnalyzer : DiagnosticAnalyzer
341
        {
342
            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
343 344 345 346 347 348
            {
                get
                {
                    throw new NotImplementedException();
                }
            }
349 350 351 352

            public override void Initialize(AnalysisContext analysisContext)
            {
            }
353 354 355 356 357 358 359 360
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestProjectDiagnosticAnalyzers()
        {
            var solution = CreateSolution();
            var project1 = ProjectId.CreateNewId();
            solution = solution.AddProject(project1, "foo", "foo.dll", LanguageNames.CSharp);
361
            Assert.Empty(solution.Projects.Single().AnalyzerReferences);
362

363
            DiagnosticAnalyzer analyzer = new MockDiagnosticAnalyzer();
364
            var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer));
365

366
            // Test AddAnalyzer
367 368 369 370
            var newSolution = solution.AddAnalyzerReference(project1, analyzerReference);
            var actualAnalyzerReferences = newSolution.Projects.Single().AnalyzerReferences;
            Assert.Equal(1, actualAnalyzerReferences.Count);
            Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
371
            var actualAnalyzers = actualAnalyzerReferences[0].GetAnalyzersForAllLanguages();
372
            Assert.Equal(1, actualAnalyzers.Length);
373
            Assert.Equal(analyzer, actualAnalyzers[0]);
374

375 376
            // Test ProjectChanges
            var changes = newSolution.GetChanges(solution).GetProjectChanges().Single();
377 378 379 380
            var addedAnalyzerReference = changes.GetAddedAnalyzerReferences().Single();
            Assert.Equal(analyzerReference, addedAnalyzerReference);
            var removedAnalyzerReferences = changes.GetRemovedAnalyzerReferences();
            Assert.Empty(removedAnalyzerReferences);
381 382 383
            solution = newSolution;

            // Test RemoveAnalyzer
384 385 386
            solution = solution.RemoveAnalyzerReference(project1, analyzerReference);
            actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
            Assert.Empty(actualAnalyzerReferences);
387

388
            // Test AddAnalyzers
389
            analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer));
390
            DiagnosticAnalyzer secondAnalyzer = new MockDiagnosticAnalyzer();
391 392 393 394 395 396 397
            var secondAnalyzerReference = new AnalyzerImageReference(ImmutableArray.Create(secondAnalyzer));
            var analyzerReferences = new[] { analyzerReference, secondAnalyzerReference };
            solution = solution.AddAnalyzerReferences(project1, analyzerReferences);
            actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
            Assert.Equal(2, actualAnalyzerReferences.Count);
            Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
            Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]);
398

399 400 401 402
            solution = solution.RemoveAnalyzerReference(project1, analyzerReference);
            actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
            Assert.Equal(1, actualAnalyzerReferences.Count);
            Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[0]);
403 404

            // Test WithAnalyzers
405 406 407 408 409
            solution = solution.WithProjectAnalyzerReferences(project1, analyzerReferences);
            actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences;
            Assert.Equal(2, actualAnalyzerReferences.Count);
            Assert.Equal(analyzerReference, actualAnalyzerReferences[0]);
            Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]);
410 411
        }

P
Pilchie 已提交
412 413 414 415 416 417
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestProjectCompilationOptions()
        {
            var solution = CreateSolution();
            var project1 = ProjectId.CreateNewId();
            solution = solution.AddProject(project1, "foo", "foo.dll", LanguageNames.CSharp);
418
            solution = solution.AddMetadataReference(project1, s_mscorlib);
P
Pilchie 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

            // Compilation Options
            var oldCompOptions = solution.GetProject(project1).CompilationOptions;
            var newCompOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "After");
            solution = solution.WithProjectCompilationOptions(project1, newCompOptions);
            var newUpdatedCompOptions = solution.GetProject(project1).CompilationOptions;
            Assert.NotEqual(oldCompOptions, newUpdatedCompOptions);
            Assert.Same(newCompOptions, newUpdatedCompOptions);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestProjectParseOptions()
        {
            var solution = CreateSolution();
            var project1 = ProjectId.CreateNewId();
            solution = solution.AddProject(project1, "foo", "foo.dll", LanguageNames.CSharp);
435
            solution = solution.AddMetadataReference(project1, s_mscorlib);
P
Pilchie 已提交
436 437 438

            // Parse Options
            var oldParseOptions = solution.GetProject(project1).ParseOptions;
439
            var newParseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "AFTER" });
P
Pilchie 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
            solution = solution.WithProjectParseOptions(project1, newParseOptions);
            var newUpdatedParseOptions = solution.GetProject(project1).ParseOptions;
            Assert.NotEqual(oldParseOptions, newUpdatedParseOptions);
            Assert.Same(newParseOptions, newUpdatedParseOptions);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestRemoveProject()
        {
            var sol = CreateSolution();

            var pid = ProjectId.CreateNewId();
            sol = sol.AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp);
            Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects");
            Assert.NotNull(pid);
            var project = sol.GetProject(pid);
            Assert.False(project.HasDocuments);

            var sol2 = sol.RemoveProject(pid);
            Assert.False(sol2.ProjectIds.Any());

            ValidateSolutionAndCompilations(sol);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestRemoveProjectWithReferences()
        {
            var sol = CreateSolution();

            var pid = ProjectId.CreateNewId();
            var pid2 = ProjectId.CreateNewId();
            sol = sol.AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                   .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp)
                   .AddProjectReference(pid2, new ProjectReference(pid));

            Assert.Equal(2, sol.Projects.Count());

            // remove the project that is being referenced
            // this should leave a dangling reference
            var sol2 = sol.RemoveProject(pid);

            Assert.False(sol2.ContainsProject(pid));
            Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2);
            Assert.Equal(1, sol2.Projects.Count());
            Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 project pid2 was expected to contain project reference " + pid);

            ValidateSolutionAndCompilations(sol2);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestRemoveProjectWithReferencesAndAddItBack()
        {
            var sol = CreateSolution();

            var pid = ProjectId.CreateNewId();
            var pid2 = ProjectId.CreateNewId();
            sol = sol.AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                   .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp)
                   .AddProjectReference(pid2, new ProjectReference(pid));

            Assert.Equal(2, sol.Projects.Count());

            // remove the project that is being referenced
            var sol2 = sol.RemoveProject(pid);

            Assert.False(sol2.ContainsProject(pid));
            Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2);
            Assert.Equal(1, sol2.Projects.Count());
            Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 pid2 was expected to contain " + pid);

            var sol3 = sol2.AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp);

            Assert.True(sol3.ContainsProject(pid), "sol3 was expected to contain " + pid);
            Assert.True(sol3.ContainsProject(pid2), "sol3 was expected to contain " + pid2);
            Assert.Equal(2, sol3.Projects.Count());

            ValidateSolutionAndCompilations(sol3);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSyntaxRoot()
        {
            var text = "public class Foo { }";

            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var sol = CreateSolution()
                .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                .AddDocument(did, "foo.cs", text);

            var document = sol.GetDocument(did);

            SyntaxNode root;
            Assert.Equal(false, document.TryGetSyntaxRoot(out root));

            root = document.GetSyntaxRootAsync().Result;
            Assert.NotNull(root);
            Assert.Equal(text, root.ToString());

            Assert.Equal(true, document.TryGetSyntaxRoot(out root));
            Assert.NotNull(root);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestUpdateDocument()
        {
            var projectId = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            var solution1 = CreateSolution()
                .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp)
                .AddDocument(documentId, "DocumentName", SourceText.From("class Class{}"));

            var document = solution1.GetDocument(documentId);
            var newRoot = Formatter.FormatAsync(document).Result.GetSyntaxRootAsync().Result;
            var solution2 = solution1.WithDocumentSyntaxRoot(documentId, newRoot);

            Assert.NotEqual(solution1, solution2);

            var newText = solution2.GetDocument(documentId).GetTextAsync().Result.ToString();
            Assert.Equal("class Class { }", newText);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestUpdateSyntaxTreeWithAnnotations()
        {
            var text = "public class Foo { }";

            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var sol = CreateSolution()
                .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                .AddDocument(did, "foo.cs", text);

            var document = sol.GetDocument(did);
            var tree = document.GetSyntaxTreeAsync().Result;
            var root = tree.GetRoot();

            var annotation = new SyntaxAnnotation();
            var annotatedRoot = root.WithAdditionalAnnotations(annotation);

            var sol2 = sol.WithDocumentSyntaxRoot(did, annotatedRoot);
            var doc2 = sol2.GetDocument(did);
            var tree2 = doc2.GetSyntaxTreeAsync().Result;
            var root2 = tree2.GetRoot();

            // text should not be available yet (it should be defer created from the node)
            // and getting the document or root should not cause it to be created.
            SourceText text2;
            Assert.Equal(false, tree2.TryGetText(out text2));

            text2 = tree2.GetText();
            Assert.NotNull(text2);

            Assert.NotSame(tree, tree2);
            Assert.NotSame(annotatedRoot, root2);

            Assert.Equal(true, annotatedRoot.IsEquivalentTo(root2));
            Assert.Equal(true, root2.HasAnnotation(annotation));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestSyntaxRootNotKeptAlive()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var sol = CreateNotKeptAliveSolution()
                .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                .AddDocument(did, "foo.cs", "public class Foo { }");

            var observedRoot = GetObservedSyntaxTreeRoot(sol, did);
            StopObservingAndWaitForReferenceToGo(observedRoot);

            // re-get the tree (should recover from storage, not reparse)
            var root = sol.GetDocument(did).GetSyntaxRootAsync().Result;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
622
        [WorkItem(542736, "DevDiv")]
P
Pilchie 已提交
623 624 625 626 627
        public void TestDocumentChangedOnDiskIsNotObserved()
        {
            var text1 = "public class A {}";
            var text2 = "public class B {}";

628
            var file = Temp.CreateFile().WriteAllText(text1, Encoding.UTF8);
P
Pilchie 已提交
629 630 631 632 633 634 635 636

            // create a solution that evicts from the cache immediately.
            var sol = CreateNotKeptAliveSolution();

            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            sol = sol.AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
637
                     .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
P
Pilchie 已提交
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655

            var observedText = GetObservedText(sol, did, text1);

            // change text on disk & verify it is changed
            file.WriteAllText(text2);
            var textOnDisk = file.ReadAllText();
            Assert.Equal(text2, textOnDisk);

            // stop observing it and let GC reclaim it
            StopObservingAndWaitForReferenceToGo(observedText);

            // if we ask for the same text again we should get the original content
            var observedText2 = sol.GetDocument(did).GetTextAsync().Result;
            Assert.Equal(text1, observedText2.ToString());
        }

        private Solution CreateNotKeptAliveSolution()
        {
656
            var workspace = new AdhocWorkspace(TestHost.Services, "NotKeptAlive");
657
            workspace.Options = workspace.Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0);
P
Pilchie 已提交
658 659 660
            return workspace.CurrentSolution;
        }

661
        private void StopObservingAndWaitForReferenceToGo(ObjectReference observed, int delay = 0)
P
Pilchie 已提交
662 663 664 665 666 667 668 669 670 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 696 697 698 699 700 701 702 703 704 705 706 707
        {
            // stop observing it and let GC reclaim it
            observed.Strong = null;

            DateTime start = DateTime.UtcNow;
            TimeSpan maximumTimeToWait = TimeSpan.FromSeconds(120);

            while (observed.Weak.IsAlive && (DateTime.UtcNow - start) < maximumTimeToWait)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            const int TimerPrecision = 30;
            var actualTimePassed = DateTime.UtcNow - start + TimeSpan.FromMilliseconds(TimerPrecision);

            Assert.True(observed.Weak.Target == null,
                string.Format("Target object ({0}) was not collected after {1} ms", observed.Weak.Target, actualTimePassed));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetTextAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            var doc = sol.GetDocument(did);

            var docText = doc.GetTextAsync().Result;

            Assert.NotNull(docText);
            Assert.Equal(text, docText.ToString());
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetLoadedTextAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
708
            var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8);
P
Pilchie 已提交
709 710 711

            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
712
                        .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
P
Pilchie 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

            var doc = sol.GetDocument(did);

            var docText = doc.GetTextAsync().Result;

            Assert.NotNull(docText);
            Assert.Equal(text, docText.ToString());
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetRecoveredTextAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // observe the text and then wait for the references to be GC'd
            var observed = GetObservedText(sol, did, text);
            StopObservingAndWaitForReferenceToGo(observed);

            // get it async and force it to recover from temporary storage
            var doc = sol.GetDocument(did);
            var docText = doc.GetTextAsync().Result;

            Assert.NotNull(docText);
743
            Assert.Equal(text, docText.ToString());            
P
Pilchie 已提交
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 771
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSyntaxTreeAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            var doc = sol.GetDocument(did);

            var docTree = doc.GetSyntaxTreeAsync().Result;

            Assert.NotNull(docTree);
            Assert.Equal(text, docTree.GetRoot().ToString());
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSyntaxTreeFromLoadedTextAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
772
            var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8);
P
Pilchie 已提交
773 774 775

            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
776
                        .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8));
P
Pilchie 已提交
777 778 779 780 781 782 783 784

            var doc = sol.GetDocument(did);
            var docTree = doc.GetSyntaxTreeAsync().Result;

            Assert.NotNull(docTree);
            Assert.Equal(text, docTree.GetRoot().ToString());
        }

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSyntaxTreeFromAddedTree()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var tree = CSharp.SyntaxFactory.ParseSyntaxTree("public class C {}").GetRoot(CancellationToken.None);
            tree = tree.WithAdditionalAnnotations(new SyntaxAnnotation("test"));

            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "x", tree);

            var doc = sol.GetDocument(did);
            var docTree = doc.GetSyntaxRootAsync().Result;

            Assert.NotNull(docTree);
            Assert.True(tree.IsEquivalentTo(docTree));
            Assert.NotNull(docTree.GetAnnotatedNodes("test").Single());
        }

P
Pilchie 已提交
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 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 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSyntaxRootAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            var doc = sol.GetDocument(did);

            var docRoot = doc.GetSyntaxRootAsync().Result;

            Assert.NotNull(docRoot);
            Assert.Equal(text, docRoot.ToString());
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetRecoveredSyntaxRootAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";

            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // observe the syntax tree root and wait for the references to be GC'd
            var observed = GetObservedSyntaxTreeRoot(sol, did);
            StopObservingAndWaitForReferenceToGo(observed);

            // get it async and force it to be recovered from storage
            var doc = sol.GetDocument(did);
            var docRoot = doc.GetSyntaxRootAsync().Result;

            Assert.NotNull(docRoot);
            Assert.Equal(text, docRoot.ToString());
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetCompilationAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            var proj = sol.GetProject(pid);

            var compilation = proj.GetCompilationAsync().Result;

            Assert.NotNull(compilation);
            Assert.Equal(1, compilation.SyntaxTrees.Count());
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSemanticModelAsync()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            var doc = sol.GetDocument(did);

            var docModel = doc.GetSemanticModelAsync().Result;
            Assert.NotNull(docModel);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetTextDoesNotKeepTextAlive()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // observe the text and then wait for the references to be GC'd
            var observed = GetObservedText(sol, did, text);
            StopObservingAndWaitForReferenceToGo(observed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private ObjectReference GetObservedText(Solution solution, DocumentId documentId, string expectedText = null)
        {
            var observedText = solution.GetDocument(documentId).GetTextAsync().Result;

            if (expectedText != null)
            {
                Assert.Equal(expectedText, observedText.ToString());
            }

            return new ObjectReference(observedText);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetTextAsyncDoesNotKeepTextAlive()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // observe the text and then wait for the references to be GC'd
            var observed = GetObservedTextAsync(sol, did, text);
            StopObservingAndWaitForReferenceToGo(observed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private ObjectReference GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null)
        {
            var observedText = solution.GetDocument(documentId).GetTextAsync().Result;

            if (expectedText != null)
            {
                Assert.Equal(expectedText, observedText.ToString());
            }

            return new ObjectReference(observedText);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSyntaxRootDoesNotKeepRootAlive()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";

            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // get it async and wait for it to get GC'd
            var observed = GetObservedSyntaxTreeRoot(sol, did);
            StopObservingAndWaitForReferenceToGo(observed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private ObjectReference GetObservedSyntaxTreeRoot(Solution solution, DocumentId documentId)
        {
            var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result;
            return new ObjectReference(observedTree);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetSyntaxRootAsyncDoesNotKeepRootAlive()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";

            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // get it async and wait for it to get GC'd
            var observed = GetObservedSyntaxTreeRootAsync(sol, did);
            StopObservingAndWaitForReferenceToGo(observed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private ObjectReference GetObservedSyntaxTreeRootAsync(Solution solution, DocumentId documentId)
        {
            var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result;
            return new ObjectReference(observedTree);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestRecoverableSyntaxTreeCSharp()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

1002 1003 1004 1005 1006 1007 1008 1009
            var text = @"public class C {
    public void Method1() {}
    public void Method2() {}
    public void Method3() {}
    public void Method4() {}
    public void Method5() {}
    public void Method6() {}
}";
P
Pilchie 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            TestRecoverableSyntaxTree(sol, did);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestRecoverableSyntaxTreeVisualBasic()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
            var text = @"Public Class C
    Sub Method1()
    End Sub
    Sub Method2()
    End Sub
    Sub Method3()
    End Sub
    Sub Method4()
    End Sub
    Sub Method5()
    End Sub
    Sub Method6()
    End Sub
End Class";
P
Pilchie 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.VisualBasic)
                        .AddDocument(did, "foo.vb", text);

            TestRecoverableSyntaxTree(sol, did);
        }

        private void TestRecoverableSyntaxTree(Solution sol, DocumentId did)
        {
            // get it async and wait for it to get GC'd
            var observed = GetObservedSyntaxTreeRootAsync(sol, did);
            StopObservingAndWaitForReferenceToGo(observed);

            var doc = sol.GetDocument(did);

            // access the tree & root again (recover it)
            var tree = doc.GetSyntaxTreeAsync().Result;

            // this should cause reparsing
            var root = tree.GetRoot();

            // prove that the new root is correctly associated with the tree
            Assert.Equal(tree, root.SyntaxTree);

            // reset the syntax root, to make it 'refactored' by adding an attribute
            var newRoot = doc.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation);
            var doc2 = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot, PreservationMode.PreserveValue).GetDocument(doc.Id);

            // get it async and wait for it to get GC'd
            var observed2 = GetObservedSyntaxTreeRootAsync(doc2.Project.Solution, did);
            StopObservingAndWaitForReferenceToGo(observed2);

P
Paul Harrington 已提交
1072
            // access the tree & root again (recover it)
P
Pilchie 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
            var tree2 = doc2.GetSyntaxTreeAsync().Result;

            // this should cause deserialization
            var root2 = tree2.GetRoot();

            // prove that the new root is correctly associated with the tree
            Assert.Equal(tree2, root2.SyntaxTree);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetCompilationAsyncDoesNotKeepCompilationAlive()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // get it async and wait for it to get GC'd
            var observed = GetObservedCompilationAsync(sol, pid);
            StopObservingAndWaitForReferenceToGo(observed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private ObjectReference GetObservedCompilationAsync(Solution solution, ProjectId projectId)
        {
            var observed = solution.GetProject(projectId).GetCompilationAsync().Result;
            return new ObjectReference(observed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestGetCompilationDoesNotKeepCompilationAlive()
        {
            var pid = ProjectId.CreateNewId();
            var did = DocumentId.CreateNewId(pid);

            var text = "public class C {}";
            var sol = CreateNotKeptAliveSolution()
                        .AddProject(pid, "foo", "foo.dll", LanguageNames.CSharp)
                        .AddDocument(did, "foo.cs", text);

            // get it async and wait for it to get GC'd
            var observed = GetObservedCompilation(sol, pid);
            StopObservingAndWaitForReferenceToGo(observed);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private ObjectReference GetObservedCompilation(Solution solution, ProjectId projectId)
        {
            var observed = solution.GetProject(projectId).GetCompilationAsync().Result;
            return new ObjectReference(observed);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestLoadProjectFromCommandLine()
        {
            string commandLine = @"foo.cs subdir\bar.cs /out:foo.dll /target:library";
1134
            var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
1135
            var ws = new AdhocWorkspace();
P
Pilchie 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
            ws.AddProject(info);
            var project = ws.CurrentSolution.GetProject(info.Id);

            Assert.Equal("TestProject", project.Name);
            Assert.Equal("foo", project.AssemblyName);
            Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind);

            Assert.Equal(2, project.Documents.Count());

            var fooDoc = project.Documents.First(d => d.Name == "foo.cs");
            Assert.Equal(0, fooDoc.Folders.Count);
            Assert.Equal(@"C:\ProjectDirectory\foo.cs", fooDoc.FilePath);

            var barDoc = project.Documents.First(d => d.Name == "bar.cs");
            Assert.Equal(1, barDoc.Folders.Count);
            Assert.Equal("subdir", barDoc.Folders[0]);
            Assert.Equal(@"C:\ProjectDirectory\subdir\bar.cs", barDoc.FilePath);
        }

        public void TestCommandLineProjectWithRelativePathOutsideProjectCone()
        {
            string commandLine = @"..\foo.cs";
1158
            var ws = new AdhocWorkspace();
1159
            var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory");
P
Pilchie 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168

            var docInfo = info.Documents.First();
            Assert.Equal(0, docInfo.Folders.Count);
            Assert.Equal("foo.cs", docInfo.Name);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestWorkspaceLanguageServiceOverride()
        {
1169
            var ws = new AdhocWorkspace(TestHost.Services, ServiceLayer.Host);
1170
            var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
P
Pilchie 已提交
1171 1172
            Assert.NotNull(service as TestLanguageServiceA);

1173
            var ws2 = new AdhocWorkspace(TestHost.Services, "Quasimodo");
1174
            var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>();
P
Pilchie 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
            Assert.NotNull(service2 as TestLanguageServiceB);
        }

#if false
        [Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
        public void TestSolutionInfo()
        {
            var oldSolutionId = SolutionId.CreateNewId("oldId");
            var oldVersion = VersionStamp.Create();
            var solutionInfo = SolutionInfo.Create(oldSolutionId, oldVersion, null, null);

            var newSolutionId = SolutionId.CreateNewId("newId");
            solutionInfo = solutionInfo.WithId(newSolutionId);
            Assert.NotEqual(oldSolutionId, solutionInfo.Id);
            Assert.Equal(newSolutionId, solutionInfo.Id);
            
            var newVersion = oldVersion.GetNewerVersion();
            solutionInfo = solutionInfo.WithVersion(newVersion);
            Assert.NotEqual(oldVersion, solutionInfo.Version);
            Assert.Equal(newVersion, solutionInfo.Version);

            Assert.Equal(null, solutionInfo.FilePath);
            var newFilePath = @"C:\test\fake.sln";
            solutionInfo = solutionInfo.WithFilePath(newFilePath);
            Assert.Equal(newFilePath, solutionInfo.FilePath);

            Assert.Equal(0, solutionInfo.Projects.Count());
        }
#endif

        private interface ITestLanguageService : ILanguageService
        {
        }

1209
        [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, ServiceLayer.Default), Shared]
P
Pilchie 已提交
1210 1211 1212 1213
        private class TestLanguageServiceA : ITestLanguageService
        {
        }

1214
        [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, "Quasimodo"), Shared]
P
Pilchie 已提交
1215 1216 1217 1218 1219 1220 1221
        private class TestLanguageServiceB : ITestLanguageService
        {
        }

        [Fact]
        public void TestDocumentFileAccessFailureMissingFile()
        {
1222
            var solution = new AdhocWorkspace().CurrentSolution;
P
Pilchie 已提交
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

            WorkspaceDiagnostic diagnostic = null;

            solution.Workspace.WorkspaceFailed += (sender, args) =>
            {
                diagnostic = args.Diagnostic;
            };

            ProjectId pid = ProjectId.CreateNewId();
            DocumentId did = DocumentId.CreateNewId(pid);

            solution = solution.AddProject(pid, "foo", "foo", LanguageNames.CSharp)
1235
                               .AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8));
P
Pilchie 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245

            var doc = solution.GetDocument(did);
            var text = doc.GetTextAsync().Result;

            WaitFor(() => diagnostic != null, TimeSpan.FromSeconds(5));

            Assert.NotNull(diagnostic);
            var dd = diagnostic as DocumentDiagnostic;
            Assert.NotNull(dd);
            Assert.Equal(did, dd.DocumentId);
1246
            Assert.Equal(WorkspaceDiagnosticKind.Failure, dd.Kind);
P
Pilchie 已提交
1247 1248 1249
        }

        [Fact]
1250
        [WorkItem(666263, "DevDiv")]
P
Pilchie 已提交
1251 1252
        public void TestWorkspaceDiagnosticHasDebuggerText()
        {
1253
            var solution = new AdhocWorkspace().CurrentSolution;
P
Pilchie 已提交
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

            WorkspaceDiagnostic diagnostic = null;

            solution.Workspace.WorkspaceFailed += (sender, args) =>
            {
                diagnostic = args.Diagnostic;
            };

            ProjectId pid = ProjectId.CreateNewId();
            DocumentId did = DocumentId.CreateNewId(pid);

            solution = solution.AddProject(pid, "foo", "foo", LanguageNames.CSharp)
1266
                               .AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8));
P
Pilchie 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275

            var doc = solution.GetDocument(did);
            var text = doc.GetTextAsync().Result;

            WaitFor(() => diagnostic != null, TimeSpan.FromSeconds(5));

            Assert.NotNull(diagnostic);
            var dd = diagnostic as DocumentDiagnostic;
            Assert.NotNull(dd);
1276
            Assert.Equal(dd.GetDebuggerDisplay(), string.Format("[{0}] {1}", dd.Kind.ToString(), dd.Message));
P
Pilchie 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
        }

        private bool WaitFor(Func<bool> condition, TimeSpan timeout)
        {
            DateTime start = DateTime.UtcNow;

            while ((DateTime.UtcNow - start) < timeout && !condition())
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(10));
            }

            return condition();
        }

        [Fact]
        public void TestGetProjectForAssemblySymbol()
        {
            var pid1 = ProjectId.CreateNewId("p1");
            var pid2 = ProjectId.CreateNewId("p2");
            var pid3 = ProjectId.CreateNewId("p3");
            var did1 = DocumentId.CreateNewId(pid1);
            var did2 = DocumentId.CreateNewId(pid2);
            var did3 = DocumentId.CreateNewId(pid3);

            var text1 = @"
Public Class A
End Class";

            var text2 = @"
Public Class B
End Class
";

            var text3 = @"
public class C : B {
}
";

            var text4 = @"
public class C : A {
}
";

1320
            var solution = new AdhocWorkspace().CurrentSolution
P
Pilchie 已提交
1321 1322
                .AddProject(pid1, "FooA", "Foo.dll", LanguageNames.VisualBasic)
                .AddDocument(did1, "A.vb", text1)
1323
                .AddMetadataReference(pid1, s_mscorlib)
P
Pilchie 已提交
1324 1325
                .AddProject(pid2, "FooB", "Foo2.dll", LanguageNames.VisualBasic)
                .AddDocument(did2, "B.vb", text2)
1326
                .AddMetadataReference(pid2, s_mscorlib)
P
Pilchie 已提交
1327 1328
                .AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp)
                .AddDocument(did3, "C.cs", text3)
1329
                .AddMetadataReference(pid3, s_mscorlib)
P
Pilchie 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
                .AddProjectReference(pid3, new ProjectReference(pid1))
                .AddProjectReference(pid3, new ProjectReference(pid2));

            var project3 = solution.GetProject(pid3);
            var comp3 = project3.GetCompilationAsync().Result;
            var classC = comp3.GetTypeByMetadataName("C");
            var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly);
            Assert.Equal(pid2, projectForBaseType.Id);

            // switch base type to A then try again
            var solution2 = solution.WithDocumentText(did3, SourceText.From(text4));
            project3 = solution2.GetProject(pid3);
            comp3 = project3.GetCompilationAsync().Result;
            classC = comp3.GetTypeByMetadataName("C");
            projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly);
            Assert.Equal(pid1, projectForBaseType.Id);
        }
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364

        [WorkItem(1088127, "DevDiv")]
        [Fact]
        public void TestEncodingRetainedAfterTreeChanged()
        {
            var ws = new AdhocWorkspace();
            var proj = ws.AddProject("proj", LanguageNames.CSharp);
            var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32));

            Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding);

            // updating root doesn't change original encoding
            var root = doc.GetSyntaxRootAsync().Result;
            var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace("    ")));
            var newDoc = doc.WithSyntaxRoot(newRoot);

            Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding);
        }
P
Pilchie 已提交
1365
    }
1366
}