VisualStudioProject.cs 59.3 KB
Newer Older
1 2 3 4 5 6 7
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
8 9
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
10 11 12 13 14 15 16 17 18 19 20 21
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
    internal sealed class VisualStudioProject
    {
        private readonly VisualStudioWorkspaceImpl _workspace;
        private readonly HostDiagnosticUpdateSource _hostDiagnosticUpdateSource;
        private readonly string _projectUniqueName;

22
        /// <summary>
23
        /// Provides dynamic source files for files added through <see cref="AddDynamicSourceFile" />.
24 25 26
        /// </summary>
        private readonly ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> _dynamicFileInfoProviders;

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
        /// <summary>
        /// A gate taken for all mutation of any mutable field in this type.
        /// </summary>
        /// <remarks>This is, for now, intentionally pessimistic. There are no doubt ways that we could allow more to run in parallel,
        /// but the current tradeoff is for simplicity of code and "obvious correctness" than something that is subtle, fast, and wrong.</remarks>
        private readonly object _gate = new object();

        /// <summary>
        /// The number of active batch scopes. If this is zero, we are not batching, non-zero means we are batching.
        /// </summary>
        private int _activeBatchScopes = 0;

        private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesAddedInBatch = new List<(string path, MetadataReferenceProperties properties)>();
        private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesRemovedInBatch = new List<(string path, MetadataReferenceProperties properties)>();
        private readonly List<ProjectReference> _projectReferencesAddedInBatch = new List<ProjectReference>();
        private readonly List<ProjectReference> _projectReferencesRemovedInBatch = new List<ProjectReference>();

        private readonly Dictionary<string, VisualStudioAnalyzer> _analyzerPathsToAnalyzers = new Dictionary<string, VisualStudioAnalyzer>();
        private readonly List<VisualStudioAnalyzer> _analyzersAddedInBatch = new List<VisualStudioAnalyzer>();
        private readonly List<VisualStudioAnalyzer> _analyzersRemovedInBatch = new List<VisualStudioAnalyzer>();

        private readonly List<Func<Solution, Solution>> _projectPropertyModificationsInBatch = new List<Func<Solution, Solution>>();

        private string _assemblyName;
        private string _displayName;
        private string _filePath;
        private CompilationOptions _compilationOptions;
        private ParseOptions _parseOptions;
55
        private bool _hasAllInformation = true;
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
        private string _intermediateOutputFilePath;
        private string _outputFilePath;
        private string _outputRefFilePath;

        private readonly Dictionary<string, List<MetadataReferenceProperties>> _allMetadataReferences = new Dictionary<string, List<MetadataReferenceProperties>>();

        /// <summary>
        /// The file watching tokens for the documents in this project. We get the tokens even when we're in a batch, so the files here
        /// may not be in the actual workspace yet.
        /// </summary>
        private readonly Dictionary<DocumentId, FileChangeWatcher.IFileWatchingToken> _fileWatchingTokens = new Dictionary<DocumentId, FileChangeWatcher.IFileWatchingToken>();

        /// <summary>
        /// A file change context used to watch source files and additional files for this project. It's automatically set to watch the user's project
        /// directory so we avoid file-by-file watching.
        /// </summary>
        private readonly FileChangeWatcher.IContext _documentFileChangeContext;

        /// <summary>
        /// A file change context used to watch metadata and analyzer references.
        /// </summary>
        private readonly FileChangeWatcher.IContext _fileReferenceChangeContext;

79 80 81 82 83
        /// <summary>
        /// track whether we have been subscribed to <see cref="IDynamicFileInfoProvider.Updated"/> event
        /// </summary>
        private readonly HashSet<IDynamicFileInfoProvider> _eventSubscriptionTracker = new HashSet<IDynamicFileInfoProvider>();

84 85
        /// <summary>
        /// map original dynamic file path to <see cref="DynamicFileInfo.FilePath"/>
H
HeeJae Chang 已提交
86 87 88 89 90 91
        /// 
        /// original dyanmic file path points to something like xxx.cshtml that are given to project system
        /// and <see cref="DynamicFileInfo.FilePath"/> points to a mapped file path provided by <see cref="IDynamicFileInfoProvider"/>
        /// and how and what it got mapped to is up to the provider. 
        /// 
        /// Workspace will only knows about <see cref="DynamicFileInfo.FilePath"/> but not the original dynamic file path
92 93 94
        /// </summary>
        private readonly Dictionary<string, string> _dynamicFilePathMaps = new Dictionary<string, string>();

95 96 97 98 99 100
        private readonly BatchingDocumentCollection _sourceFiles;
        private readonly BatchingDocumentCollection _additionalFiles;

        public ProjectId Id { get; }
        public string Language { get; }

101 102
        internal VisualStudioProject(
            VisualStudioWorkspaceImpl workspace,
103
            ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> dynamicFileInfoProviders,
104 105 106 107 108
            HostDiagnosticUpdateSource hostDiagnosticUpdateSource,
            ProjectId id,
            string projectUniqueName,
            string language,
            string directoryNameOpt)
109 110
        {
            _workspace = workspace;
111
            _dynamicFileInfoProviders = dynamicFileInfoProviders;
112 113 114 115 116 117 118 119 120
            _hostDiagnosticUpdateSource = hostDiagnosticUpdateSource;

            Id = id;
            Language = language;
            _displayName = projectUniqueName;
            _projectUniqueName = projectUniqueName;

            if (directoryNameOpt != null)
            {
121 122 123
                // TODO: use directoryNameOpt to create a directory watcher. For now, there's perf hits due to the flood of events we'll need to sort out later.
                // _documentFileChangeContext = _workspace.FileChangeWatcher.CreateContextForDirectory(directoryNameOpt);
                _documentFileChangeContext = workspace.FileChangeWatcher.CreateContext();
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
            }
            else
            {
                _documentFileChangeContext = workspace.FileChangeWatcher.CreateContext();
            }

            _documentFileChangeContext.FileChanged += FileChangeContext_FileChanged;

            // TODO: set this to watch the NuGet directory or the reference assemblies directory; since those change rarely and most references
            // will come from them, we can avoid creating a bunch of explicit file watchers.
            _fileReferenceChangeContext = workspace.FileChangeWatcher.CreateContext();

            _sourceFiles = new BatchingDocumentCollection(this, (s, d) => s.ContainsDocument(d), (w, d) => w.OnDocumentAdded(d), (w, documentId) => w.OnDocumentRemoved(documentId));
            _additionalFiles = new BatchingDocumentCollection(this, (s, d) => s.ContainsAdditionalDocument(d), (w, d) => w.OnAdditionalDocumentAdded(d), (w, documentId) => w.OnAdditionalDocumentRemoved(documentId));
        }

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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 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
        private void ChangeProjectProperty<T>(ref T field, T newValue, Func<Solution, Solution> withNewValue, Action<Workspace> changeValue)
        {
            lock (_gate)
            {
                // If nothing is changing, we can skip entirely
                if (object.Equals(field, newValue))
                {
                    return;
                }

                field = newValue;

                if (_activeBatchScopes > 0)
                {
                    _projectPropertyModificationsInBatch.Add(withNewValue);
                }
                else
                {
                    _workspace.ApplyChangeToWorkspace(changeValue);
                }
            }
        }

        private void ChangeProjectOutputPath(ref string field, string newValue, Func<Solution, Solution> withNewValue, Action<Workspace> changeValue)
        {
            lock (_gate)
            {
                // Skip if nothing changing
                if (field == newValue)
                {
                    return;
                }

                if (field != null)
                {
                    _workspace.RemoveProjectOutputPath(Id, field);
                }

                if (newValue != null)
                {
                    _workspace.AddProjectOutputPath(Id, newValue);
                }

                ChangeProjectProperty(ref field, newValue, withNewValue, changeValue);
            }
        }
        public string AssemblyName
        {
            get => _assemblyName;
            set => ChangeProjectProperty(
                      ref _assemblyName,
                      value,
                       s => s.WithProjectAssemblyName(Id, value),
                       w => w.OnAssemblyNameChanged(Id, value));
        }

        public CompilationOptions CompilationOptions
        {
            get => _compilationOptions;
            set => ChangeProjectProperty(
                       ref _compilationOptions,
                       value,
                       s => s.WithProjectCompilationOptions(Id, value),
                       w => w.OnCompilationOptionsChanged(Id, value));
        }

        public ParseOptions ParseOptions
        {
            get => _parseOptions;
            set => ChangeProjectProperty(
                       ref _parseOptions,
                       value,
                       s => s.WithProjectParseOptions(Id, value),
                       w => w.OnParseOptionsChanged(Id, value));
        }

        /// <summary>
        /// The path to the output in obj.
        /// </summary>
        /// <remarks>This is internal for now, as it's only consumed by <see cref="EditAndContinue.VsENCRebuildableProjectImpl"/>
        /// which directly takes a <see cref="VisualStudioProject"/>.</remarks>
        internal string IntermediateOutputFilePath
        {
            get => _intermediateOutputFilePath;
            set
            {
                // Unlike OutputFilePath and OutputRefFilePath, the intermediate output path isn't represented in the workspace anywhere;
                // thus, we won't mutate the solution. We'll still call ChangeProjectOutputPath so we have the rest of the output path tracking
                // for any P2P reference conversion.
                ChangeProjectOutputPath(ref _intermediateOutputFilePath, value, s => s, w => { });
            }
        }

        public string OutputFilePath
        {
            get => _outputFilePath;
            set => ChangeProjectOutputPath(ref _outputFilePath,
                       value,
                       s => s.WithProjectOutputFilePath(Id, value),
                       w => w.OnOutputFilePathChanged(Id, value));
        }

        public string OutputRefFilePath
        {
            get => _outputRefFilePath;
            set => ChangeProjectOutputPath(ref _outputRefFilePath,
                       value,
                       s => s.WithProjectOutputRefFilePath(Id, value),
                       w => w.OnOutputRefFilePathChanged(Id, value));
        }

        public string FilePath
        {
            get => _filePath;
            set => ChangeProjectProperty(ref _filePath,
                       value,
                       s => s.WithProjectFilePath(Id, value),
                       w => w.OnProjectNameChanged(Id, _displayName, value));
        }

        public string DisplayName
        {
            get => _displayName;
            set => ChangeProjectProperty(ref _displayName,
                       value,
                       s => s.WithProjectName(Id, value),
                       w => w.OnProjectNameChanged(Id, value, _filePath));
        }
269

270 271 272 273 274 275 276 277 278 279 280
        // internal to match the visibility of the Workspace-level API -- this is something
        // we use but we haven't made officially public yet.
        internal bool HasAllInformation
        {
            get => _hasAllInformation;
            set => ChangeProjectProperty(ref _hasAllInformation,
                       value,
                       s => s.WithHasAllInformation(Id, value),
                       w => w.OnHasAllInformationChanged(Id, value));
        }

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

        #region Batching

        public BatchScope CreateBatchScope()
        {
            lock (_gate)
            {
                _activeBatchScopes++;
                return new BatchScope(this);
            }
        }

        public sealed class BatchScope : IDisposable
        {
            private readonly VisualStudioProject _project;

            /// <summary>
            /// Flag to control if this has already been disposed. Not a boolean only so it can be used with Interlocked.CompareExchange.
            /// </summary>
            private volatile int _disposed = 0;

            internal BatchScope(VisualStudioProject visualStudioProject)
            {
                _project = visualStudioProject;
            }

            public void Dispose()
            {
                if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 0)
                {
                    _project.OnBatchScopeDisposed();
                }
            }
        }

        private void OnBatchScopeDisposed()
        {
            lock (_gate)
            {
                _activeBatchScopes--;

                if (_activeBatchScopes > 0)
                {
                    return;
                }

                var documentFileNamesAdded = ImmutableArray.CreateBuilder<string>();
                var documentsToOpen = new List<(DocumentId, SourceTextContainer)>();

                _workspace.ApplyBatchChangeToProject(Id, solution =>
                {
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
                    solution = _sourceFiles.UpdateSolutionForBatch(
                        solution,
                        documentFileNamesAdded,
                        documentsToOpen,
                        (s, documents) => solution.AddDocuments(documents),
                        (s, id) =>
                        {
                            // Clear any document-specific data now (like open file trackers, etc.)
                            _workspace.ClearDocumentData(id);
                            return s.RemoveDocument(id);
                        });

                    solution = _additionalFiles.UpdateSolutionForBatch(
                        solution,
                        documentFileNamesAdded,
                        documentsToOpen,
                        (s, documents) =>
                        {
                            foreach (var document in documents)
                            {
                                s = s.AddAdditionalDocument(document);
                            }

                            return s;
                        },
                        (s, id) =>
                        {
                            // Clear any document-specific data now (like open file trackers, etc.)
                            _workspace.ClearDocumentData(id);
                            return s.RemoveAdditionalDocument(id);
                        });
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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

                    // Metadata reference adding...
                    if (_metadataReferencesAddedInBatch.Count > 0)
                    {
                        var projectReferencesCreated = new List<ProjectReference>();
                        var metadataReferencesCreated = new List<MetadataReference>();

                        foreach (var metadataReferenceAddedInBatch in _metadataReferencesAddedInBatch)
                        {
                            var projectReference = _workspace.TryCreateConvertedProjectReference(Id, metadataReferenceAddedInBatch.path, metadataReferenceAddedInBatch.properties);

                            if (projectReference != null)
                            {
                                projectReferencesCreated.Add(projectReference);
                            }
                            else
                            {
                                metadataReferencesCreated.Add(_workspace.CreateMetadataReference(metadataReferenceAddedInBatch.path, metadataReferenceAddedInBatch.properties));
                            }
                        }

                        solution = solution.AddProjectReferences(Id, projectReferencesCreated)
                                           .AddMetadataReferences(Id, metadataReferencesCreated);

                        ClearAndZeroCapacity(_metadataReferencesAddedInBatch);
                    }

                    // Metadata reference removing...
                    foreach (var metadataReferenceRemovedInBatch in _metadataReferencesRemovedInBatch)
                    {
                        var projectReference = _workspace.TryRemoveConvertedProjectReference(Id, metadataReferenceRemovedInBatch.path, metadataReferenceRemovedInBatch.properties);

                        if (projectReference != null)
                        {
                            solution = solution.RemoveProjectReference(Id, projectReference);
                        }
                        else
                        {
                            // TODO: find a cleaner way to fetch this
                            var metadataReference = _workspace.CurrentSolution.GetProject(Id).MetadataReferences.Cast<PortableExecutableReference>()
                                                                                    .Single(m => m.FilePath == metadataReferenceRemovedInBatch.path && m.Properties == metadataReferenceRemovedInBatch.properties);

                            solution = solution.RemoveMetadataReference(Id, metadataReference);
                        }
                    }

                    ClearAndZeroCapacity(_metadataReferencesRemovedInBatch);

                    // Project reference adding...
                    solution = solution.AddProjectReferences(Id, _projectReferencesAddedInBatch);
                    ClearAndZeroCapacity(_projectReferencesAddedInBatch);

                    // Project reference removing...
                    foreach (var projectReference in _projectReferencesRemovedInBatch)
                    {
                        solution = solution.RemoveProjectReference(Id, projectReference);
                    }

                    ClearAndZeroCapacity(_projectReferencesRemovedInBatch);

                    // Analyzer reference adding...
                    solution = solution.AddAnalyzerReferences(Id, _analyzersAddedInBatch.Select(a => a.GetReference()));
                    ClearAndZeroCapacity(_analyzersAddedInBatch);

                    // Analyzer reference removing...
                    foreach (var analyzerReference in _analyzersRemovedInBatch)
                    {
                        solution = solution.RemoveAnalyzerReference(Id, analyzerReference.GetReference());
                    }

                    ClearAndZeroCapacity(_analyzersRemovedInBatch);

                    // Other property modifications...
                    foreach (var propertyModification in _projectPropertyModificationsInBatch)
                    {
                        solution = propertyModification(solution);
                    }

                    ClearAndZeroCapacity(_projectPropertyModificationsInBatch);

                    return solution;
                });

                foreach (var (documentId, textContainer) in documentsToOpen)
                {
                    _workspace.ApplyChangeToWorkspace(w => w.OnDocumentOpened(documentId, textContainer));
                }

                // Check for those files being opened to start wire-up if necessary
                _workspace.CheckForOpenDocuments(documentFileNamesAdded.ToImmutable());
            }
        }

        #endregion

        #region Source File Addition/Removal

        public void AddSourceFile(string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular, ImmutableArray<string> folders = default)
        {
            _sourceFiles.AddFile(fullPath, sourceCodeKind, folders);
        }

465 466 467 468 469 470
        public DocumentId AddSourceTextContainer(
            SourceTextContainer textContainer,
            string fullPath,
            SourceCodeKind sourceCodeKind = SourceCodeKind.Regular,
            ImmutableArray<string> folders = default,
            IDocumentServiceProvider documentServiceProvider = null)
471
        {
472
            return _sourceFiles.AddTextContainer(textContainer, fullPath, sourceCodeKind, folders, documentServiceProvider);
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
        }

        public bool ContainsSourceFile(string fullPath)
        {
            return _sourceFiles.ContainsFile(fullPath);
        }

        public void RemoveSourceFile(string fullPath)
        {
            _sourceFiles.RemoveFile(fullPath);
        }

        public void RemoveSourceTextContainer(SourceTextContainer textContainer)
        {
            _sourceFiles.RemoveTextContainer(textContainer);
        }

        #endregion

        #region Additional File Addition/Removal

        // TODO: should AdditionalFiles have source code kinds?
        public void AddAdditionalFile(string fullPath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            _additionalFiles.AddFile(fullPath, sourceCodeKind, folders: default);
        }

        public bool ContainsAdditionalFile(string fullPath)
        {
            return _additionalFiles.ContainsFile(fullPath);
        }

        public void RemoveAdditionalFile(string fullPath)
        {
            _additionalFiles.RemoveFile(fullPath);
        }

        #endregion

512
        #region Non Source File Addition/Removal
H
HeeJae Chang 已提交
513

514
        public void AddDynamicSourceFile(string dynamicFilePath, ImmutableArray<string> folders)
515
        {
516
            var extension = FileNameUtilities.GetExtension(dynamicFilePath)?.TrimStart('.');
517 518 519 520 521 522 523 524 525 526 527 528 529
            if (extension?.Length == 0)
            {
                return;
            }

            foreach (var provider in _dynamicFileInfoProviders)
            {
                // skip unrelated providers
                if (!provider.Metadata.Extensions.Any(e => string.Equals(e, extension, StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

530 531 532 533
                // don't get confused by _filePath and filePath
                // VisualStudioProject._filePath points to csproj/vbproj of the project
                // and the parameter filePath points to dynamic file such as cshtml and etc
                // 
534
                // also, provider is free-threaded. so fine to call Wait rather than JTF
535
                var fileInfo = provider.Value.GetDynamicFileInfoAsync(
536
                    projectId: Id, projectFilePath: _filePath, filePath: dynamicFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
537

538 539 540 541 542
                if (fileInfo == null)
                {
                    continue;
                }

543 544 545 546 547
                fileInfo = FixUpDynamicFileInfo(fileInfo, dynamicFilePath);

                // remember map between original dynamic file path to DynamicFileInfo.FilePath
                _dynamicFilePathMaps.Add(dynamicFilePath, fileInfo.FilePath);
                _sourceFiles.AddDynamicFile(provider.Value, fileInfo, folders);
548 549 550 551
                return;
            }
        }

552
        private DynamicFileInfo FixUpDynamicFileInfo(DynamicFileInfo fileInfo, string filePath)
553
        {
554 555 556 557 558 559 560 561 562 563 564
            // we might change contract and just throw here. but for now, we keep existing contract where one can return null for DynamicFileInfo.FilePath
            if (string.IsNullOrEmpty(fileInfo.FilePath))
            {
                return new DynamicFileInfo(filePath, fileInfo.SourceCodeKind, fileInfo.TextLoader, fileInfo.DocumentServiceProvider);
            }

            return fileInfo;
        }

        public void RemoveDynamicSourceFile(string dynamicFilePath)
        {
565
            var provider = _sourceFiles.RemoveDynamicFile(_dynamicFilePathMaps[dynamicFilePath]);
566

567
            // provider is free-threaded. so fine to call Wait rather than JTF
568
            provider.RemoveDynamicFileInfoAsync(
569
                projectId: Id, projectFilePath: _filePath, filePath: dynamicFilePath, CancellationToken.None).Wait(CancellationToken.None);
570 571
        }

572
        private void OnDynamicFileInfoUpdated(object sender, string dynamicFilePath)
573
        {
574 575 576 577 578 579
            if (!_dynamicFilePathMaps.TryGetValue(dynamicFilePath, out var fileInfoPath))
            {
                // given file doesn't belong to this project. 
                // this happen since the event this is handling is shared between all projects
                return;
            }
580

581
            _sourceFiles.ProcessFileChange(dynamicFilePath, fileInfoPath);
582 583 584 585
        }

        #endregion

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 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 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 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 708 709 710 711 712 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 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 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 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
        #region Analyzer Addition/Removal

        public void AddAnalyzerReference(string fullPath)
        {
            if (string.IsNullOrEmpty(fullPath))
            {
                throw new ArgumentException("message", nameof(fullPath));
            }

            var visualStudioAnalyzer = new VisualStudioAnalyzer(
                fullPath,
                _hostDiagnosticUpdateSource,
                Id,
                _workspace,
                Language);

            lock (_gate)
            {
                if (_analyzerPathsToAnalyzers.ContainsKey(fullPath))
                {
                    throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath));
                }

                _analyzerPathsToAnalyzers.Add(fullPath, visualStudioAnalyzer);

                if (_activeBatchScopes > 0)
                {
                    _analyzersAddedInBatch.Add(visualStudioAnalyzer);
                }
                else
                {
                    _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerReferenceAdded(Id, visualStudioAnalyzer.GetReference()));
                }
            }
        }

        public void RemoveAnalyzerReference(string fullPath)
        {
            if (string.IsNullOrEmpty(fullPath))
            {
                throw new ArgumentException("message", nameof(fullPath));
            }

            lock (_gate)
            {
                if (!_analyzerPathsToAnalyzers.TryGetValue(fullPath, out var visualStudioAnalyzer))
                {
                    throw new ArgumentException($"'{fullPath}' is not an analyzer of this project.", nameof(fullPath));
                }

                _analyzerPathsToAnalyzers.Remove(fullPath);

                if (_activeBatchScopes > 0)
                {
                    _analyzersRemovedInBatch.Add(visualStudioAnalyzer);
                }
                else
                {
                    _workspace.ApplyChangeToWorkspace(w => w.OnAnalyzerReferenceRemoved(Id, visualStudioAnalyzer.GetReference()));
                }
            }
        }

        #endregion

        private void FileChangeContext_FileChanged(object sender, string fullFilePath)
        {
            _sourceFiles.ProcessFileChange(fullFilePath);
            _additionalFiles.ProcessFileChange(fullFilePath);
        }

        #region Metadata Reference Addition/Removal

        public void AddMetadataReference(string fullPath, MetadataReferenceProperties properties)
        {
            if (string.IsNullOrEmpty(fullPath))
            {
                throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath));
            }

            lock (_gate)
            {
                if (ContainsMetadataReference(fullPath, properties))
                {
                    throw new InvalidOperationException("The metadata reference has already been added to the project.");
                }

                _allMetadataReferences.MultiAdd(fullPath, properties);

                if (_activeBatchScopes > 0)
                {
                    if (!_metadataReferencesRemovedInBatch.Remove((fullPath, properties)))
                    {
                        _metadataReferencesAddedInBatch.Add((fullPath, properties));
                    }
                }
                else
                {
                    _workspace.ApplyChangeToWorkspace(w =>
                    {
                        var projectReference = _workspace.TryCreateConvertedProjectReference(Id, fullPath, properties);

                        if (projectReference != null)
                        {
                            w.OnProjectReferenceAdded(Id, projectReference);
                        }
                        else
                        {
                            w.OnMetadataReferenceAdded(Id, _workspace.CreateMetadataReference(fullPath, properties));
                        }
                    });
                }

            }
        }

        public bool ContainsMetadataReference(string fullPath, MetadataReferenceProperties properties)
        {
            lock (_gate)
            {
                return GetPropertiesForMetadataReference(fullPath).Contains(properties);
            }
        }

        /// <summary>
        /// Returns the properties being used for the current metadata reference added to this project. May return multiple properties if
        /// the reference has been added multiple times with different properties.
        /// </summary>
        public ImmutableArray<MetadataReferenceProperties> GetPropertiesForMetadataReference(string fullPath)
        {
            lock (_gate)
            {
                _allMetadataReferences.TryGetValue(fullPath, out var list);

                // Note: AsImmutableOrEmpty accepts null recievers and treats that as an empty array
                return list.AsImmutableOrEmpty();
            }
        }

        public void RemoveMetadataReference(string fullPath, MetadataReferenceProperties properties)
        {
            if (string.IsNullOrEmpty(fullPath))
            {
                throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath));
            }

            lock (_gate)
            {
                if (!ContainsMetadataReference(fullPath, properties))
                {
                    throw new InvalidOperationException("The metadata reference does not exist in this project.");
                }

                _allMetadataReferences.MultiRemove(fullPath, properties);

                if (_activeBatchScopes > 0)
                {
                    if (!_metadataReferencesAddedInBatch.Remove((fullPath, properties)))
                    {
                        _metadataReferencesRemovedInBatch.Add((fullPath, properties));
                    }
                }
                else
                {
                    _workspace.ApplyChangeToWorkspace(w =>
                    {
                        var projectReference = _workspace.TryRemoveConvertedProjectReference(Id, fullPath, properties);

                        // If this was converted to a project reference, we have now recorded the removal -- let's remove it here too
                        if (projectReference != null)
                        {
                            w.OnProjectReferenceRemoved(Id, projectReference);
                        }
                        else
                        {
                            // TODO: find a cleaner way to fetch this
                            var metadataReference = w.CurrentSolution.GetProject(Id).MetadataReferences.Cast<PortableExecutableReference>()
                                                                                    .Single(m => m.FilePath == fullPath && m.Properties == properties);

                            w.OnMetadataReferenceRemoved(Id, metadataReference);
                        }
                    });
                }
            }
        }

        #endregion

        #region Project Reference Addition/Removal

        public void AddProjectReference(ProjectReference projectReference)
        {
            if (projectReference == null)
            {
                throw new ArgumentNullException(nameof(projectReference));
            }

            lock (_gate)
            {
                if (ContainsProjectReference(projectReference))
                {
                    throw new ArgumentException("The project reference has already been added to the project.");
                }

                if (_activeBatchScopes > 0)
                {
                    if (!_projectReferencesRemovedInBatch.Remove(projectReference))
                    {
                        _projectReferencesAddedInBatch.Add(projectReference);
                    }
                }
                else
                {
                    _workspace.ApplyChangeToWorkspace(w => w.OnProjectReferenceAdded(Id, projectReference));
                }
            }
        }

        public bool ContainsProjectReference(ProjectReference projectReference)
        {
            if (projectReference == null)
            {
                throw new ArgumentNullException(nameof(projectReference));
            }

            lock (_gate)
            {
                if (_projectReferencesRemovedInBatch.Contains(projectReference))
                {
                    return false;
                }

                if (_projectReferencesAddedInBatch.Contains(projectReference))
                {
                    return true;
                }

                return _workspace.CurrentSolution.GetProject(Id).AllProjectReferences.Contains(projectReference);
            }
        }

        public IReadOnlyList<ProjectReference> GetProjectReferences()
        {
            lock (_gate)
            {
                // If we're not batching, then this is cheap: just fetch from the workspace and we're done
                var projectReferencesInWorkspace = _workspace.CurrentSolution.GetProject(Id).AllProjectReferences;

                if (_activeBatchScopes == 0)
                {
                    return projectReferencesInWorkspace;
                }

                // Not, so we get to compute a new list instead
                var newList = projectReferencesInWorkspace.ToList();
                newList.AddRange(_projectReferencesAddedInBatch);
                newList.RemoveAll(p => _projectReferencesRemovedInBatch.Contains(p));

                return newList;
            }
        }

        public void RemoveProjectReference(ProjectReference projectReference)
        {
            if (projectReference == null)
            {
                throw new ArgumentNullException(nameof(projectReference));
            }

            lock (_gate)
            {
                if (_activeBatchScopes > 0)
                {
                    if (!_projectReferencesAddedInBatch.Remove(projectReference))
                    {
                        _projectReferencesRemovedInBatch.Add(projectReference);
                    }
                }
                else
                {
                    _workspace.ApplyChangeToWorkspace(w => w.OnProjectReferenceRemoved(Id, projectReference));
                }
            }
        }

        #endregion

        public void RemoveFromWorkspace()
        {
            _documentFileChangeContext.Dispose();

877 878 879 880 881 882 883 884 885 886 887
            lock (_gate)
            {
                // clear tracking to external components
                foreach (var provider in _eventSubscriptionTracker)
                {
                    provider.Updated -= OnDynamicFileInfoUpdated;
                }

                _eventSubscriptionTracker.Clear();
            }

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
            _workspace.ApplyChangeToWorkspace(w => w.OnProjectRemoved(Id));
        }

        /// <summary>
        /// Adds an additional output path that can be used for automatic conversion of metadata references to P2P references.
        /// Any projects with metadata references to the path given here will be converted to project-to-project references.
        /// </summary>
        public void AddOutputPath(string outputPath)
        {
            if (string.IsNullOrEmpty(outputPath))
            {
                throw new ArgumentException($"{nameof(outputPath)} isn't a valid path.", nameof(outputPath));
            }

            _workspace.AddProjectOutputPath(Id, outputPath);
        }

        /// <summary>
        /// Removes an additional output path that was added by <see cref="AddOutputPath(string)"/>.
        /// </summary>
        public void RemoveOutputPath(string outputPath)
        {
            if (string.IsNullOrEmpty(outputPath))
            {
                throw new ArgumentException($"{nameof(outputPath)} isn't a valid path.", nameof(outputPath));
            }

            _workspace.RemoveProjectOutputPath(Id, outputPath);
        }

        /// <summary>
        /// Clears a list and zeros out the capacity. The lists we use for batching are likely to get large during an initial load, but after
        /// that point should never get that large again.
        /// </summary>
        private static void ClearAndZeroCapacity<T>(List<T> list)
        {
            list.Clear();
            list.Capacity = 0;
        }

        /// <summary>
        /// Clears a list and zeros out the capacity. The lists we use for batching are likely to get large during an initial load, but after
        /// that point should never get that large again.
        /// </summary>
        private static void ClearAndZeroCapacity<T>(ImmutableArray<T>.Builder list)
        {
            list.Clear();
            list.Capacity = 0;
        }

        /// <summary>
        /// Helper class to manage collections of source-file like things; this exists just to avoid duplicating all the logic for regular source files
        /// and additional files.
        /// </summary>
        /// <remarks>This class should be free-threaded, and any synchronization is done via <see cref="VisualStudioProject._gate"/>.
        /// This class is otehrwise free to operate on private members of <see cref="_project"/> if needed.</remarks>
        private sealed class BatchingDocumentCollection
        {
            private readonly VisualStudioProject _project;

            /// <summary>
            /// The map of file paths to the underlying <see cref="DocumentId"/>. This document may exist in <see cref="_documentsAddedInBatch"/> or has been
            /// pushed to the actual workspace.
            /// </summary>
            private readonly Dictionary<string, DocumentId> _documentPathsToDocumentIds = new Dictionary<string, DocumentId>(StringComparer.OrdinalIgnoreCase);

            /// <summary>
            /// A map of explicitly-added "always open" <see cref="SourceTextContainer"/> and their associated <see cref="DocumentId"/>. This does not contain
            /// any regular files that have been open.
            /// </summary>
            private IBidirectionalMap<SourceTextContainer, DocumentId> _sourceTextContainersToDocumentIds = BidirectionalMap<SourceTextContainer, DocumentId>.Empty;

960
            /// <summary>
H
HeeJae Chang 已提交
961
            /// The map of <see cref="DocumentId"/> to <see cref="IDynamicFileInfoProvider"/> whose <see cref="DynamicFileInfo"/> got added into <see cref="Workspace"/>
962 963 964
            /// </summary>
            private readonly Dictionary<DocumentId, IDynamicFileInfoProvider> _documentIdToDynamicFileInfoProvider = new Dictionary<DocumentId, IDynamicFileInfoProvider>();

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 1002 1003 1004
            /// <summary>
            /// The current list of documents that are to be added in this batch.
            /// </summary>
            private readonly ImmutableArray<DocumentInfo>.Builder _documentsAddedInBatch = ImmutableArray.CreateBuilder<DocumentInfo>();

            /// <summary>
            /// The current list of documents that are being removed in this batch. Once the document is in this list, it is no longer in <see cref="_documentPathsToDocumentIds"/>.
            /// </summary>
            private readonly List<DocumentId> _documentsRemovedInBatch = new List<DocumentId>();

            private readonly Func<Solution, DocumentId, bool> _documentAlreadyInWorkspace;
            private readonly Action<Workspace, DocumentInfo> _documentAddAction;
            private readonly Action<Workspace, DocumentId> _documentRemoveAction;

            public BatchingDocumentCollection(VisualStudioProject project,
                Func<Solution, DocumentId, bool> documentAlreadyInWorkspace,
                Action<Workspace, DocumentInfo> documentAddAction,
                Action<Workspace, DocumentId> documentRemoveAction)
            {
                _project = project;
                _documentAlreadyInWorkspace = documentAlreadyInWorkspace;
                _documentAddAction = documentAddAction;
                _documentRemoveAction = documentRemoveAction;
            }

            public DocumentId AddFile(string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray<string> folders)
            {
                if (string.IsNullOrEmpty(fullPath))
                {
                    throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath));
                }

                var documentId = DocumentId.CreateNewId(_project.Id, fullPath);
                var textLoader = new FileTextLoader(fullPath, defaultEncoding: null);
                var documentInfo = DocumentInfo.Create(
                    documentId,
                    FileNameUtilities.GetFileName(fullPath),
                    folders: folders.IsDefault ? null : (IEnumerable<string>)folders,
                    sourceCodeKind: sourceCodeKind,
                    loader: textLoader,
1005 1006
                    filePath: fullPath,
                    isGenerated: false);
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

                lock (_project._gate)
                {
                    if (_documentPathsToDocumentIds.ContainsKey(fullPath))
                    {
                        throw new ArgumentException($"'{fullPath}' has already been added to this project.", nameof(fullPath));
                    }

                    _documentPathsToDocumentIds.Add(fullPath, documentId);
                    _project._fileWatchingTokens.Add(documentId, _project._documentFileChangeContext.EnqueueWatchingFile(fullPath));

                    if (_project._activeBatchScopes > 0)
                    {
                        _documentsAddedInBatch.Add(documentInfo);
                    }
                    else
                    {
                        _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo));
                        _project._workspace.CheckForOpenDocuments(ImmutableArray.Create(fullPath));
                    }
                }

                return documentId;
            }

1032
            public DocumentId AddTextContainer(SourceTextContainer textContainer, string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray<string> folders, IDocumentServiceProvider documentServiceProvider)
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
            {
                if (textContainer == null)
                {
                    throw new ArgumentNullException(nameof(textContainer));
                }

                var documentId = DocumentId.CreateNewId(_project.Id, fullPath);
                var textLoader = new SourceTextLoader(textContainer, fullPath);
                var documentInfo = DocumentInfo.Create(
                    documentId,
                    FileNameUtilities.GetFileName(fullPath),
                    folders: folders.IsDefault ? null : (IEnumerable<string>)folders,
                    sourceCodeKind: sourceCodeKind,
                    loader: textLoader,
1047 1048 1049
                    filePath: fullPath,
                    isGenerated: false,
                    documentServiceProvider: documentServiceProvider);
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

                lock (_project._gate)
                {
                    if (_sourceTextContainersToDocumentIds.ContainsKey(textContainer))
                    {
                        throw new ArgumentException($"{nameof(textContainer)} is already added to this project.", nameof(textContainer));
                    }

                    if (fullPath != null)
                    {
                        if (_documentPathsToDocumentIds.ContainsKey(fullPath))
                        {
                            throw new ArgumentException($"'{fullPath}' has already been added to this project.");
                        }

                        _documentPathsToDocumentIds.Add(fullPath, documentId);
                    }

                    _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.Add(textContainer, documentInfo.Id);

                    if (_project._activeBatchScopes > 0)
                    {
                        _documentsAddedInBatch.Add(documentInfo);
                    }
                    else
                    {
1076 1077
                        _project._workspace.ApplyChangeToWorkspace(w =>
                        {
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
                            _project._workspace.AddDocumentToDocumentsNotFromFiles(documentInfo.Id);
                            _documentAddAction(w, documentInfo);
                            w.OnDocumentOpened(documentInfo.Id, textContainer);
                        });
                    }
                }

                return documentId;
            }

1088
            public void AddDynamicFile(IDynamicFileInfoProvider fileInfoProvider, DynamicFileInfo fileInfo, ImmutableArray<string> folders)
1089
            {
1090
                var documentInfo = CreateDocumentInfoFromFileInfo(fileInfo, folders.NullToEmpty());
1091 1092 1093 1094
                var documentId = documentInfo.Id;

                lock (_project._gate)
                {
1095
                    var filePath = documentInfo.FilePath;
1096 1097 1098 1099 1100 1101 1102
                    if (_documentPathsToDocumentIds.ContainsKey(filePath))
                    {
                        throw new ArgumentException($"'{filePath}' has already been added to this project.", nameof(filePath));
                    }

                    _documentPathsToDocumentIds.Add(filePath, documentId);

1103
                    _documentIdToDynamicFileInfoProvider.Add(documentId, fileInfoProvider);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

                    if (_project._eventSubscriptionTracker.Add(fileInfoProvider))
                    {
                        // subscribe to the event when we use this provider the first time
                        fileInfoProvider.Updated += _project.OnDynamicFileInfoUpdated;
                    }

                    if (_project._activeBatchScopes > 0)
                    {
                        _documentsAddedInBatch.Add(documentInfo);
                    }
                    else
                    {
1117
                        // right now, assumption is dynamically generated file can never be opened in editor
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
                        _project._workspace.ApplyChangeToWorkspace(w => _documentAddAction(w, documentInfo));
                    }
                }
            }

            public IDynamicFileInfoProvider RemoveDynamicFile(string fullPath)
            {
                if (string.IsNullOrEmpty(fullPath))
                {
                    throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath));
                }

                lock (_project._gate)
                {
                    if (!_documentPathsToDocumentIds.TryGetValue(fullPath, out var documentId) ||
1133
                        !_documentIdToDynamicFileInfoProvider.TryGetValue(documentId, out var fileInfoProvider))
1134
                    {
1135
                        throw new ArgumentException($"'{fullPath}' is not a dynamic file of this project.");
1136 1137
                    }

1138
                    _documentIdToDynamicFileInfoProvider.Remove(documentId);
1139 1140 1141 1142 1143 1144 1145

                    RemoveFileInternal(documentId, fullPath);

                    return fileInfoProvider;
                }
            }

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
            public void RemoveFile(string fullPath)
            {
                if (string.IsNullOrEmpty(fullPath))
                {
                    throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath));
                }

                lock (_project._gate)
                {
                    if (!_documentPathsToDocumentIds.TryGetValue(fullPath, out var documentId))
                    {
                        throw new ArgumentException($"'{fullPath}' is not a source file of this project.");
                    }

1160 1161 1162
                    _project._documentFileChangeContext.StopWatchingFile(_project._fileWatchingTokens[documentId]);
                    _project._fileWatchingTokens.Remove(documentId);

1163 1164 1165
                    RemoveFileInternal(documentId, fullPath);
                }
            }
1166

1167 1168 1169
            private void RemoveFileInternal(DocumentId documentId, string fullPath)
            {
                _documentPathsToDocumentIds.Remove(fullPath);
1170

1171 1172 1173 1174 1175 1176 1177 1178
                // There are two cases:
                // 
                // 1. This file is actually been pushed to the workspace, and we need to remove it (either
                //    as a part of the active batch or immediately)
                // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch
                if (_documentAlreadyInWorkspace(_project._workspace.CurrentSolution, documentId))
                {
                    if (_project._activeBatchScopes > 0)
1179
                    {
1180
                        _documentsRemovedInBatch.Add(documentId);
1181 1182 1183
                    }
                    else
                    {
1184 1185 1186 1187 1188 1189 1190 1191
                        _project._workspace.ApplyChangeToWorkspace(w => _documentRemoveAction(w, documentId));
                    }
                }
                else
                {
                    for (int i = 0; i < _documentsAddedInBatch.Count; i++)
                    {
                        if (_documentsAddedInBatch[i].Id == documentId)
1192
                        {
1193 1194
                            _documentsAddedInBatch.RemoveAt(i);
                            break;
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
                        }
                    }
                }
            }

            public void RemoveTextContainer(SourceTextContainer textContainer)
            {
                if (textContainer == null)
                {
                    throw new ArgumentNullException(nameof(textContainer));
                }

                lock (_project._gate)
                {
                    if (!_sourceTextContainersToDocumentIds.TryGetValue(textContainer, out var documentId))
                    {
                        throw new ArgumentException($"{nameof(textContainer)} is not a text container added to this project.");
                    }

                    _sourceTextContainersToDocumentIds = _sourceTextContainersToDocumentIds.RemoveKey(textContainer);

1216 1217 1218 1219 1220 1221 1222
                    // if the TextContainer had a full path provided, remove it from the map.
                    var entry = _documentPathsToDocumentIds.Where(kv => kv.Value == documentId).FirstOrDefault();
                    if (entry.Key != null)
                    {
                        _documentPathsToDocumentIds.Remove(entry.Key);
                    }

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
                    // There are two cases:
                    // 
                    // 1. This file is actually been pushed to the workspace, and we need to remove it (either
                    //    as a part of the active batch or immediately)
                    // 2. It hasn't been pushed yet, but is contained in _documentsAddedInBatch
                    if (_project._workspace.CurrentSolution.GetDocument(documentId) != null)
                    {
                        if (_project._activeBatchScopes > 0)
                        {
                            _documentsRemovedInBatch.Add(documentId);
                        }
                        else
                        {
1236 1237
                            _project._workspace.ApplyChangeToWorkspace(w =>
                            {
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
                                w.OnDocumentClosed(documentId, new SourceTextLoader(textContainer, filePath: null));
                                _documentRemoveAction(w, documentId);
                                _project._workspace.RemoveDocumentToDocumentsNotFromFiles(documentId);
                            });
                        }
                    }
                    else
                    {
                        for (int i = 0; i < _documentsAddedInBatch.Count; i++)
                        {
                            if (_documentsAddedInBatch[i].Id == documentId)
                            {
                                _documentsAddedInBatch.RemoveAt(i);
                                break;
                            }
                        }
                    }
                }
            }

            public bool ContainsFile(string fullPath)
            {
                if (string.IsNullOrEmpty(fullPath))
                {
                    throw new ArgumentException($"{nameof(fullPath)} isn't a valid path.", nameof(fullPath));
                }

                lock (_project._gate)
                {
                    return _documentPathsToDocumentIds.ContainsKey(fullPath);
                }
            }

1271 1272 1273 1274 1275
            public void ProcessFileChange(string filePath)
            {
                ProcessFileChange(filePath, filePath);
            }

1276 1277 1278 1279 1280 1281
            /// <summary>
            /// Process file content changes
            /// </summary>
            /// <param name="projectSystemFilePath">filepath given from project system</param>
            /// <param name="workspaceFilePath">filepath used in workspace. it might be different than projectSystemFilePath. ex) dynamic file</param>
            public void ProcessFileChange(string projectSystemFilePath, string workspaceFilePath)
1282 1283 1284
            {
                lock (_project._gate)
                {
1285
                    if (_documentPathsToDocumentIds.TryGetValue(workspaceFilePath, out var documentId))
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
                    {
                        // We create file watching prior to pushing the file to the workspace in batching, so it's
                        // possible we might see a file change notification early. In this case, toss it out. Since
                        // all adds/removals of documents for this project happen under our lock, it's safe to do this
                        // check without taking the main workspace lock
                        var document = _project._workspace.CurrentSolution.GetDocument(documentId);
                        if (document == null)
                        {
                            return;
                        }

1297
                        _documentIdToDynamicFileInfoProvider.TryGetValue(documentId, out var fileInfoProvider);
1298

1299 1300 1301 1302 1303 1304 1305
                        _project._workspace.ApplyChangeToWorkspace(w =>
                        {
                            if (w.IsDocumentOpen(documentId))
                            {
                                return;
                            }

1306 1307 1308 1309
                            TextLoader textLoader;
                            IDocumentServiceProvider documentServiceProvider;
                            if (fileInfoProvider == null)
                            {
1310
                                textLoader = new FileTextLoader(projectSystemFilePath, defaultEncoding: null);
1311 1312 1313 1314
                                documentServiceProvider = null;
                            }
                            else
                            {
1315 1316 1317 1318
                                // we do not expect JTF to be used around this code path. and contract of fileInfoProvider is it being real free-threaded
                                // meaning it can't use JTF to go back to UI thread.
                                // so, it is okay for us to call regular ".Result" on a task here.
                                var fileInfo = fileInfoProvider.GetDynamicFileInfoAsync(
1319
                                    _project.Id, _project._filePath, projectSystemFilePath, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333

                                textLoader = fileInfo.TextLoader;
                                documentServiceProvider = fileInfo.DocumentServiceProvider;
                            }

                            var documentInfo = DocumentInfo.Create(
                                document.Id,
                                document.Name,
                                document.Folders,
                                document.SourceCodeKind,
                                loader: textLoader,
                                document.FilePath,
                                document.State.Attributes.IsGenerated,
                                documentServiceProvider: documentServiceProvider);
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344

                            w.OnDocumentReloaded(documentInfo);
                        });
                    }
                }
            }

            internal Solution UpdateSolutionForBatch(
                Solution solution,
                ImmutableArray<string>.Builder documentFileNamesAdded,
                List<(DocumentId, SourceTextContainer)> documentsToOpen,
1345
                Func<Solution, ImmutableArray<DocumentInfo>, Solution> addDocuments,
1346 1347 1348
                Func<Solution, DocumentId, Solution> removeDocument)
            {
                // Document adding...
1349
                solution = addDocuments(solution, _documentsAddedInBatch.ToImmutable());
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

                foreach (var documentInfo in _documentsAddedInBatch)
                {
                    documentFileNamesAdded.Add(documentInfo.FilePath);

                    if (_sourceTextContainersToDocumentIds.TryGetKey(documentInfo.Id, out var textContainer))
                    {
                        documentsToOpen.Add((documentInfo.Id, textContainer));
                    }
                }

                ClearAndZeroCapacity(_documentsAddedInBatch);

                // Document removing...
                foreach (var documentId in _documentsRemovedInBatch)
                {
1366
                    solution = removeDocument(solution, documentId);
1367 1368 1369 1370 1371 1372 1373
                }

                ClearAndZeroCapacity(_documentsRemovedInBatch);

                return solution;
            }

1374 1375
            private DocumentInfo CreateDocumentInfoFromFileInfo(DynamicFileInfo fileInfo, IEnumerable<string> folders)
            {
1376
                // we use this file path for editorconfig. 
1377 1378
                var filePath = fileInfo.FilePath;

1379
                var name = FileNameUtilities.GetFileName(filePath);
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
                var documentId = DocumentId.CreateNewId(_project.Id, filePath);

                var textLoader = fileInfo.TextLoader;
                var documentServiceProvider = fileInfo.DocumentServiceProvider;

                return DocumentInfo.Create(
                    documentId,
                    name,
                    folders: folders,
                    sourceCodeKind: fileInfo.SourceCodeKind,
                    loader: textLoader,
                    filePath: filePath,
                    isGenerated: false,
                    documentServiceProvider: documentServiceProvider);
            }

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
            private sealed class SourceTextLoader : TextLoader
            {
                private readonly SourceTextContainer _textContainer;
                private readonly string _filePath;

                public SourceTextLoader(SourceTextContainer textContainer, string filePath)
                {
                    _textContainer = textContainer;
                    _filePath = filePath;
                }

                public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
                {
                    return Task.FromResult(TextAndVersion.Create(_textContainer.CurrentText, VersionStamp.Create(), _filePath));
                }
            }
        }
    }
}