Esempio n. 1
0
        private Document AddDocumentToProject(string filePath, string language, string projectName)
        {
            var project = CurrentSolution.Projects.FirstOrDefault(
                p => p.Name == projectName && p.Language == language
                );

            if (project == null)
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    projectName,
                    projectName,
                    language
                    );
                OnProjectAdded(projectInfo);
                project = CurrentSolution.GetRequiredProject(projectInfo.Id);
            }

            var docInfo = DocumentInfo.Create(
                DocumentId.CreateNewId(project.Id),
                name: Path.GetFileName(filePath),
                loader: new FileTextLoader(filePath, null),
                filePath: filePath
                );

            OnDocumentAdded(docInfo);
            return(CurrentSolution.GetDocument(docInfo.Id) !);
        }
 public IEnumerable <Document> GetDocuments(string filePath)
 {
     return(CurrentSolution
            .GetDocumentIdsWithFilePath(filePath)
            .Select(id => CurrentSolution.GetDocument(id))
            .OfType <Document>());
 }
        public Document GetOrAddDocument(string filePath)
        {
            DocumentId docId = CurrentSolution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault();

            if (docId != null)
            {
                return(CurrentSolution.GetDocument(docId));
            }

            if (!IsRemoteSession)
            {
                return(null);
            }

            // If the document is within the joined folder or it's a registered external file,
            // add it to the workspace, otherwise bail out.
            if (!filePath.StartsWith(_remoteRootPath) &&
                !IsExternalLocalUri(filePath))
            {
                return(null);
            }

            var language = GetLanguage(filePath);

            // Unsupported language.
            if (language == null)
            {
                return(null);
            }

            var folderName = Path.GetFileNameWithoutExtension(_remoteRootPath);

            return(AddDocumentToProject(filePath, language, folderName));
        }
Esempio n. 4
0
        public static async Task <(ImmutableArray <Diagnostic> diagnostics, Document document, Workspace workspace)> SetupAsync(string sourceCodeFile)
        {
            var workSpace = new AdhocWorkspace();

            var solution = workSpace.CurrentSolution;

            var projectId = ProjectId.CreateNewId();

            solution = solution.AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp);
            var documentId = DocumentId.CreateNewId(projectId);

            var sourceCode = await File.ReadAllTextAsync(sourceCodeFile);

            solution = solution.AddDocument(documentId, "File.cs", sourceCode);

            var project = solution.GetProject(projectId);

            project = project !.AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
            project = project.AddMetadataReferences(GetAllReferences(typeof(JsonObjectAttribute)));
            if (!workSpace.TryApplyChanges(project.Solution))
            {
                throw new Exception("Changes was not applied");
            }

            var compilation = await project.GetCompilationAsync();

            var compilationWithAnalyzer = compilation.WithAnalyzers(ImmutableArray.Create <DiagnosticAnalyzer>(new JsonAnalyzerAnalyzer()));

            var diagnostic = await compilationWithAnalyzer.GetAllDiagnosticsAsync();

            return(diagnostic, workSpace.CurrentSolution.GetDocument(documentId), workSpace);
        }
        /// <inheritdoc />
        protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text)
        {
            var document = CurrentSolution.GetDocument(documentId);

            if (document != null)
            {
                if (_openedDocs.Values.Contains(documentId) || IsDocumentOpen(documentId))
                {
                    var textBuffer = _threadingContext.JoinableTaskFactory.Run(async() =>
                    {
                        var sourceText    = await document.GetTextAsync().ConfigureAwait(false);
                        var textContainer = sourceText.Container;
                        return(textContainer.TryGetTextBuffer());
                    });

                    UpdateText(textBuffer, text);
                }
                else
                {
                    // The edits would get sent by the co-authoring service to the owner.
                    // The invisible editor saves the file on being disposed, which should get reflected  on the owner's side.
                    using (var invisibleEditor = new InvisibleEditor(_serviceProvider, document.FilePath, hierarchyOpt: null,
                                                                     needsSave: true, needsUndoDisabled: false))
                    {
                        UpdateText(invisibleEditor.TextBuffer, text);
                    }
                }
            }
        }
Esempio n. 6
0
        ///<summary>Unlinks an opened <see cref="Document"/> from its <see cref="ITextBuffer"/>.</summary>
        public override void CloseDocument(DocumentId documentId)
        {
            var document = CurrentSolution.GetDocument(documentId);

            OnDocumentClosed(documentId, TextLoader.From(TextAndVersion.Create(document.GetTextAsync().Result, document.GetTextVersionAsync().Result)));
            documentBuffers.Remove(documentId);
        }
Esempio n. 7
0
        public void ChangeAllMethodsToPublicStatic(DocumentId documentId)
        {
            var document      = CurrentSolution.GetDocument(documentId);
            var semanticModel = document.GetSemanticModelAsync().Result;

            var root = semanticModel.SyntaxTree.GetRoot();

            // Constructors
            var count = root.DescendantNodes().OfType <ConstructorDeclarationSyntax>().Count();

            for (var i = 0; i < count; i++)
            {
                var method    = root.DescendantNodes().OfType <ConstructorDeclarationSyntax>().ToArray()[i];
                var trivia    = method.GetTrailingTrivia();
                var modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword).WithTrailingTrivia(trivia));
                root = root.ReplaceNode(method, method.WithModifiers(modifiers));
            }

            // Methods
            count = root.DescendantNodes().OfType <MethodDeclarationSyntax>().Count();
            for (var i = 0; i < count; i++)
            {
                var method    = root.DescendantNodes().OfType <MethodDeclarationSyntax>().ToArray()[i];
                var trivia    = method.ReturnType.GetTrailingTrivia();
                var modifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword).WithTrailingTrivia(trivia), SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithTrailingTrivia(trivia));
                root = root.ReplaceNode(method, method.WithModifiers(modifiers));
            }

            document = document.WithSyntaxRoot(root);
            var text = document.GetTextAsync().Result;

            UpdateText(documentId, text.ToString());
        }
Esempio n. 8
0
        public IReadOnlyList <ISymbol> GetRecommendedSymbols(DocumentId documentId, int position)
        {
            var document      = CurrentSolution.GetDocument(documentId);
            var semanticModel = document.GetSemanticModelAsync().Result;

            return(Recommender.GetRecommendedSymbolsAtPosition(semanticModel, position, this).ToArray());
        }
Esempio n. 9
0
        public string FormatDocument(DocumentId documentId)
        {
            var document = CurrentSolution.GetDocument(documentId);

            document = Formatter.FormatAsync(document).Result;
            var text = document.GetTextAsync().Result;

            return(text.ToString());
        }
Esempio n. 10
0
        public IEnumerable <ClassifiedSpan> GetClassifiedSpans(DocumentId documentId, int start, int length)
        {
            var document = CurrentSolution.GetDocument(documentId);

            return(ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                return await Classifier.GetClassifiedSpansAsync(document, TextSpan.FromBounds(start, start + length)).ConfigureAwait(true);
            }).Join());
        }
Esempio n. 11
0
        public ISymbol GetSymbol(DocumentId documentId, int position)
        {
            var document      = CurrentSolution.GetDocument(documentId);
            var semanticModel = document.GetSemanticModelAsync().Result;
            var root          = semanticModel.SyntaxTree.GetRoot();
            var symbol        = root.FindToken(position);

            return(semanticModel.GetSymbolInfo(symbol.Parent).Symbol);
        }
Esempio n. 12
0
 public Task FormatDocumentAsync(DocumentId documentId)
 {
     return(Task.Run(async() =>
     {
         var formattedDocument = await Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(
             CurrentSolution.GetDocument(documentId) !).ConfigureAwait(false);
         TryApplyChanges(formattedDocument.Project.Solution);
     }));
 }
Esempio n. 13
0
        public IReadOnlyList <Diagnostic> GetDiagnostics(DocumentId documentId, int start, int length)
        {
            var document      = CurrentSolution.GetDocument(documentId);
            var semanticModel = document.GetSemanticModelAsync().Result;
            var bounds        = TextSpan.FromBounds(start, start + length);
            var diagnostics   = semanticModel.GetDiagnostics(bounds);

            return(diagnostics.ToArray());
        }
Esempio n. 14
0
        public IReadOnlyList <MethodDeclarationSyntax> GetMethods(DocumentId documentId)
        {
            var document   = CurrentSolution.GetDocument(documentId);
            var syntaxTree = document.GetSyntaxTreeAsync().Result;

            var root = syntaxTree.GetRoot();

            return(root.DescendantNodes().OfType <MethodDeclarationSyntax>().ToArray());
        }
Esempio n. 15
0
        protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text)
        {
            var document = CurrentSolution.GetDocument(documentId);

            if (document?.FilePath != null && text.Encoding != null)
            {
                SaveDocumentText(documentId, document.FilePath, text, text.Encoding);
                OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue);
            }
        }
Esempio n. 16
0
        public override void OpenDocument(DocumentId documentId, bool activate = true)
        {
            var doc = CurrentSolution.GetDocument(documentId);

            if (doc != null)
            {
                var text = doc.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
                OnDocumentOpened(documentId, text.Container, activate);
            }
        }
Esempio n. 17
0
 public Task <IReadOnlyList <ISymbol> > GetRecommendedSymbolsAsync(DocumentId documentId, int position, CancellationToken cancellationToken)
 {
     return(Task.Run(async() =>
     {
         var document = CurrentSolution.GetDocument(documentId);
         var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
         var symbols = await Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, position, this, null, cancellationToken).ConfigureAwait(false);
         return (IReadOnlyList <ISymbol>)symbols.ToArray();
     }, cancellationToken));
 }
        public Document? GetOrAddExternalDocument(string filePath, string language)
        {
            var docId = CurrentSolution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault();
            if (docId != null)
            {
                return CurrentSolution.GetDocument(docId);
            }

            return AddDocumentToProject(filePath, language, ExternalProjectName);
        }
        public Document GetDocument(string filePath)
        {
            var documentId = GetDocumentId(filePath);

            if (documentId == null)
            {
                return(null);
            }
            return(CurrentSolution.GetDocument(documentId));
        }
Esempio n. 20
0
            protected override void ApplyDocumentTextChanged(DocumentId id, SourceText text)
            {
                base.ApplyDocumentTextChanged(id, text);
                var document = CurrentSolution.GetDocument(id);

                if (document != null)
                {
                    OnDocumentTextChanged(id, text, PreservationMode.PreserveValue);
                }
            }
Esempio n. 21
0
        public EmitResult Compile(DocumentId documentId, string path)
        {
            var document    = CurrentSolution.GetDocument(documentId);
            var compilation = document.Project.GetCompilationAsync().Result;

            using (var fileStream = File.Create(path))
            {
                return(compilation.Emit(fileStream));
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
        /// is in the current context. For regular files (non-shared and non-linked) and closed
        /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked
        /// files and open shared files, the active context is already tracked by the
        /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the
        /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/>
        /// is preferred.
        /// </summary>
        internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
        {
            // If the document is open, then the Workspace knows the current context for both
            // linked and shared files
            if (IsDocumentOpen(documentId))
            {
                return(base.GetDocumentIdInCurrentContext(documentId));
            }

            var hostDocument = GetHostDocument(documentId);

            if (hostDocument == null)
            {
                // This can happen if the document was temporary and has since been closed/deleted.
                return(base.GetDocumentIdInCurrentContext(documentId));
            }

            var itemId = hostDocument.GetItemId();

            if (itemId == (uint)VSConstants.VSITEMID.Nil)
            {
                // An itemid is required to determine whether the file belongs to a Shared Project
                return(base.GetDocumentIdInCurrentContext(documentId));
            }

            // If this is a regular document or a closed linked (non-shared) document, then use the
            // default logic for determining current context.
            var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);

            if (sharedHierarchy == null)
            {
                return(base.GetDocumentIdInCurrentContext(documentId));
            }

            // This is a closed shared document, so we must determine the correct context.
            var hostProject     = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, DeferredState.ProjectTracker);
            var matchingProject = CurrentSolution.GetProject(hostProject.Id);

            if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy)
            {
                return(base.GetDocumentIdInCurrentContext(documentId));
            }

            if (matchingProject.ContainsDocument(documentId))
            {
                // The provided documentId is in the current context project
                return(documentId);
            }

            // The current context document is from another project.
            var linkedDocumentIds  = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds();
            var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id);

            return(matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId));
        }
Esempio n. 23
0
        public string FormatDocument(DocumentId documentId)
        {
            var document = CurrentSolution.GetDocument(documentId);

            return(ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                document = await Formatter.FormatAsync(document).ConfigureAwait(true);
                var text = await document.GetTextAsync().ConfigureAwait(true);
                return text.ToString();
            }).Join());
        }
Esempio n. 24
0
            public override void OpenDocument(DocumentId documentId, bool activate = true)
            {
                var document = CurrentSolution.GetDocument(documentId);

                if (document != null)
                {
                    var sourceText = document.GetTextAsync(CancellationToken.None).Result;
                    openDocumentState = openDocumentState.Add(documentId, new DocumentState());
                    OnDocumentOpened(documentId, sourceText.Container, activate);
                }
            }
Esempio n. 25
0
            public Document AddDocument(DocumentInfo documentInfo)
            {
                if (documentInfo == null)
                {
                    throw new ArgumentNullException(nameof(documentInfo));
                }

                OnDocumentAdded(documentInfo);

                return(CurrentSolution.GetDocument(documentInfo.Id));
            }
Esempio n. 26
0
        public IReadOnlyList <ISymbol> GetRecommendedSymbols(DocumentId documentId, int position)
        {
            var document = CurrentSolution.GetDocument(documentId);

            return(ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                var semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(true);
                var result = Recommender.GetRecommendedSymbolsAtPosition(semanticModel, position, this);
                return result.ToArray();
            }).Join());
        }
Esempio n. 27
0
        public void CallDocumentClosingAndClosed_CsFile(DocumentId documentId)
        {
            OnDocumentClosing(documentId);

            var document = CurrentSolution.GetDocument(documentId);

            if (document != null && document.TryGetText(out var text))
            {
                OnDocumentClosed(documentId, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Default, document.FilePath)));
            }
        }
Esempio n. 28
0
        public override void CloseDocument(DocumentId documentId)
        {
            var doc = CurrentSolution.GetDocument(documentId);

            if (doc != null)
            {
                var text    = doc.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
                var version = doc.GetTextVersionAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
                var loader  = TextLoader.From(TextAndVersion.Create(text, version, doc.FilePath));
                OnDocumentClosed(documentId, loader);
            }
        }
Esempio n. 29
0
 public Document GetOpenedDocumentByName(string fileName)
 {
     foreach (var id in GetOpenDocumentIds())
     {
         var doc = CurrentSolution.GetDocument(id);
         if (doc.Name == fileName)
         {
             return(doc);
         }
     }
     return(null);
 }
Esempio n. 30
0
        /// <summary>
        ///
        /// </summary>
        internal void OnDocumentContextUpdated(DocumentId documentId, SourceTextContainer container)
        {
            using (this.stateLock.DisposableWrite())
            {
                bufferToDocumentInCurrentContextMap[container] = documentId;
            }

            var document = CurrentSolution.GetDocument(documentId);

            this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, this.CurrentSolution, this.CurrentSolution, documentId: documentId);
            var task = this.RaiseDocumentActiveContextChangedEventAsync(document); // don't await this
        }