public AtomFeedCreated(DocumentId documentId, string feedTitle, string feedAuthor, FeedId feedId)
 {
     DocumentId = documentId;
     FeedTitle = feedTitle;
     FeedAuthor = feedAuthor;
     FeedId = feedId;
 }
        internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath)
        {
            if (documentId == null)
            {
                return false;
            }

            var project = ProjectTracker.GetProject(documentId.ProjectId);
            if (project == null)
            {
                return false;
            }

            var document = project.GetDocumentOrAdditionalDocument(documentId);
            if (document == null)
            {
                return false;
            }

            var codeModelProvider = project as IProjectCodeModelProvider;
            if (codeModelProvider == null)
            {
                return false;
            }

            var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache();
            if (codeModelCache == null)
            {
                return false;
            }

            codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath);

            return true;
        }
Example #3
0
        public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
        {
            DateTime prevLastWriteTime = File.GetLastWriteTimeUtc(this.path);

            // Open file for reading with FileShare mode read/write/delete so that we do not lock this file.
            // Allowing other theads/processes to write or delete the file is essential for scenarios such as
            // Rename refactoring where File.Replace API is invoked for updating the modified file. 
            TextAndVersion textAndVersion;
            using (var stream = File.Open(this.path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
            {
                var version = VersionStamp.Create(prevLastWriteTime);
                var memoryStream = await this.ReadStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);

                var text = CreateText(memoryStream, workspace);
                textAndVersion = TextAndVersion.Create(text, version, path);
            }

            // this has a potential to return corrupted state text if someone changed text in the middle of us reading it.
            // previously, we attempted to detect such case and return empty string with workspace failed event. 
            // but that is nothing better or even worse than returning what we have read so far.
            //
            // I am letting it to return what we have read so far. and hopefully, file change event let us re-read this file.
            // (* but again, there is still a chance where file change event happens even before writing has finished which ends up
            //    let us stay in corrupted state)
            DateTime newLastWriteTime = File.GetLastWriteTimeUtc(this.path);
            if (!newLastWriteTime.Equals(prevLastWriteTime))
            {
                // TODO: remove this once we know how often this can happen.
                //       I am leaving this here for now for diagnostic purpose.
                var message = string.Format(WorkspacesResources.FileWasExternallyModified, this.path);
                workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.FileAccessFailure, message, documentId));
            }

            return textAndVersion;
        }
Example #4
0
        public AbstractSourceTreeItem(Document document, TextSpan sourceSpan, ushort glyphIndex, int commonPathElements = 0)
            : base(glyphIndex)
        {
            // We store the document ID, line and offset for navigation so that we
            // still provide reasonable navigation if the user makes changes elsewhere
            // in the document other than inserting or removing lines.

            _workspace = document.Project.Solution.Workspace;
            _documentId = document.Id;
            _projectName = document.Project.Name;
            _filePath = GetFilePath(document, commonPathElements);
            _sourceSpan = sourceSpan;

            var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            var textLine = text.Lines.GetLineFromPosition(_sourceSpan.Start);
            _textLineString = textLine.ToString();

            _lineNumber = textLine.LineNumber;
            _offset = sourceSpan.Start - textLine.Start;

            var spanInSecondaryBuffer = text.GetVsTextSpanForLineOffset(_lineNumber, _offset);

            VsTextSpan spanInPrimaryBuffer;
            var succeeded = spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(_workspace, _documentId, out spanInPrimaryBuffer);

            _mappedLineNumber = succeeded ? spanInPrimaryBuffer.iStartLine : _lineNumber;
            _mappedOffset = succeeded ? spanInPrimaryBuffer.iStartIndex : _offset;
        }
        public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId)
        {
            if (documentId == null)
            {
                throw new ArgumentNullException("documentId");
            }

            var project = ProjectTracker.GetProject(documentId.ProjectId);
            if (project == null)
            {
                throw new ArgumentException(ServicesVSResources.DocumentIdNotFromWorkspace, "documentId");
            }

            var document = project.GetDocumentOrAdditionalDocument(documentId);
            if (document == null)
            {
                throw new ArgumentException(ServicesVSResources.DocumentIdNotFromWorkspace, "documentId");
            }

            var provider = project as IProjectCodeModelProvider;
            if (provider != null)
            {
                var projectCodeModel = provider.ProjectCodeModel;
                if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath))
                {
                    return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath);
                }
            }

            return null;
        }
            private async Task<Solution> RenameFields(Solution solution, DocumentId documentId, int count, CancellationToken cancellationToken)
            {
                Solution oldSolution = null;
                for (int i = 0; i < count; i++)
                {
                    oldSolution = solution;

                    var semanticModel = await solution.GetDocument(documentId).GetSemanticModelAsync(cancellationToken);
                    var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken);
                    var declaration = root.GetAnnotatedNodes(s_markerAnnotation).ElementAt(i);
                    var fieldSymbol = (IFieldSymbol)semanticModel.GetDeclaredSymbol(declaration, cancellationToken);
                    var newName = GetNewFieldName(fieldSymbol);

                    // Can happen with pathologically bad field names like _
                    if (newName == fieldSymbol.Name)
                    {
                        continue;
                    }

                    solution = await Renamer.RenameSymbolAsync(solution, fieldSymbol, newName, solution.Workspace.Options, cancellationToken).ConfigureAwait(false);
                    solution = await CleanSolutionAsync(solution, oldSolution, cancellationToken);
                }

                return solution;
            }
            public void AddDocument(DocumentId id)
            {
                var vsWorkspace = (VisualStudioWorkspaceImpl)_workspace;
                Contract.ThrowIfNull(vsWorkspace);

                var solution = vsWorkspace.CurrentSolution;
                if (!solution.ContainsDocument(id))
                {
                    // document is not part of the workspace (newly created document that is not applied to the workspace yet?)
                    return;
                }

                if (vsWorkspace.IsDocumentOpen(id))
                {
                    var document = vsWorkspace.GetHostDocument(id);
                    var undoHistory = _undoHistoryRegistry.RegisterHistory(document.GetOpenTextBuffer());

                    using (var undoTransaction = undoHistory.CreateTransaction(_description))
                    {
                        undoTransaction.AddUndo(new NoOpUndoPrimitive());
                        undoTransaction.Complete();
                    }

                    return;
                }

                // open and close the document so that it is included in the global undo transaction
                using (vsWorkspace.OpenInvisibleEditor(id))
                {
                    // empty
                }
            }
Example #8
0
        public FileChange(TextDocument left,
            TextDocument right,
            IComponentModel componentModel,
            AbstractChange parent,
            PreviewEngine engine,
            IVsImageService2 imageService) : base(engine)
        {
            Contract.ThrowIfFalse(left != null || right != null);

            this.Id = left != null ? left.Id : right.Id;
            _left = left;
            _right = right;
            _imageService = imageService;

            _componentModel = componentModel;
            var bufferFactory = componentModel.GetService<ITextBufferFactoryService>();
            var bufferText = left != null ?
                left.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None) :
                right.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            _buffer = bufferFactory.CreateTextBuffer(bufferText.ToString(), bufferFactory.InertContentType);
            _encoding = bufferText.Encoding;

            this.Children = ComputeChildren(left, right, CancellationToken.None);
            this.parent = parent;
        }
Example #9
0
        protected Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId projectId = null, DocumentId documentId = null)
        {
            if (newSolution == null)
            {
                throw new ArgumentNullException("newSolution");
            }

            if (oldSolution == newSolution)
            {
                return SpecializedTasks.EmptyTask;
            }

            if (projectId == null && documentId != null)
            {
                projectId = documentId.ProjectId;
            }

            var handlers = this.eventMap.GetEventHandlers<EventHandler<WorkspaceChangeEventArgs>>(WorkspaceChangeEventName);
            if (handlers.Length > 0)
            {
                return this.ScheduleTask(() =>
                {
                    var args = new WorkspaceChangeEventArgs(kind, oldSolution, newSolution, projectId, documentId);
                    foreach (var handler in handlers)
                    {
                        handler(this, args);
                    }
                }, "Workspace.WorkspaceChanged");
            }
            else
            {
                return SpecializedTasks.EmptyTask;
            }
        }
Example #10
0
        public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
        {
            var document = this.CurrentSolution.GetAdditionalDocument(documentId);
            var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            this.OnAdditionalDocumentOpened(documentId, text.Container);
        }
        public void GetAdjustedDiagnosticSpan(
            DocumentId documentId, Location location,
            out TextSpan sourceSpan, out FileLinePositionSpan originalLineInfo, out FileLinePositionSpan mappedLineInfo)
        {
            sourceSpan = location.SourceSpan;
            originalLineInfo = location.GetLineSpan();
            mappedLineInfo = location.GetMappedLineSpan();

            // check quick bail out case.
            if (location == Location.None)
            {
                return;
            }
            // Update the original source span, if required.
            if (!TryAdjustSpanIfNeededForVenus(documentId, originalLineInfo, mappedLineInfo, out var originalSpan, out var mappedSpan))
            {
                return;
            }

            if (originalSpan.Start != originalLineInfo.StartLinePosition || originalSpan.End != originalLineInfo.EndLinePosition)
            {
                originalLineInfo = new FileLinePositionSpan(originalLineInfo.Path, originalSpan.Start, originalSpan.End);

                var textLines = location.SourceTree.GetText().Lines;
                var startPos = textLines.GetPosition(originalSpan.Start);
                var endPos = textLines.GetPosition(originalSpan.End);

                sourceSpan = TextSpan.FromBounds(startPos, Math.Max(startPos, endPos));
            }

            if (mappedSpan.Start != mappedLineInfo.StartLinePosition || mappedSpan.End != mappedLineInfo.EndLinePosition)
            {
                mappedLineInfo = new FileLinePositionSpan(mappedLineInfo.Path, mappedSpan.Start, mappedSpan.End);
            }
        }
 internal static Solution UpdateDocument(this Solution solution, DocumentId id, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken)
 {
     var oldDocument = solution.GetDocument(id);
     var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
     var newText = oldText.WithChanges(textChanges);
     return solution.WithDocumentText(id, newText, PreservationMode.PreserveIdentity);
 }
Example #13
0
        /// <summary>
        /// Create a new instance of a <see cref="DocumentInfo"/>.
        /// </summary>
        private DocumentInfo(
            DocumentId id,
            string name,
            IEnumerable<string> folders,
            SourceCodeKind sourceCodeKind,
            TextLoader loader,
            string filePath,
            bool isGenerated)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            this.Id = id;
            this.Name = name;
            this.Folders = folders.ToImmutableReadOnlyListOrEmpty();
            this.SourceCodeKind = sourceCodeKind;
            this.TextLoader = loader;
            this.FilePath = filePath;
            this.IsGenerated = isGenerated;
        }
            public DiagnosticGetter(
                DiagnosticIncrementalAnalyzer owner,
                Solution solution,
                ProjectId projectId,
                DocumentId documentId,
                object id,
                bool includeSuppressedDiagnostics)
            {
                Owner = owner;
                CurrentSolution = solution;

                CurrentDocumentId = documentId;
                CurrentProjectId = projectId ?? documentId?.ProjectId;

                Id = id;
                IncludeSuppressedDiagnostics = includeSuppressedDiagnostics;

                // try to retrieve projectId/documentId from id if possible.
                var argsId = id as LiveDiagnosticUpdateArgsId;
                if (argsId != null)
                {
                    CurrentDocumentId = CurrentDocumentId ?? argsId.Key as DocumentId;
                    CurrentProjectId = CurrentProjectId ?? (argsId.Key as ProjectId) ?? CurrentDocumentId.ProjectId;
                }

                _builder = null;
            }
 public DiagnosticDataLocation(
     DocumentId documentId = null,
     TextSpan? sourceSpan = null,
     string originalFilePath = null,
     int originalStartLine = 0,
     int originalStartColumn = 0,
     int originalEndLine = 0,
     int originalEndColumn = 0,
     string mappedFilePath = null,
     int mappedStartLine = 0,
     int mappedStartColumn = 0,
     int mappedEndLine = 0,
     int mappedEndColumn = 0)
 {
     DocumentId = documentId;
     SourceSpan = sourceSpan;
     MappedFilePath = mappedFilePath;
     MappedStartLine = mappedStartLine;
     MappedStartColumn = mappedStartColumn;
     MappedEndLine = mappedEndLine;
     MappedEndColumn = mappedEndColumn;
     OriginalFilePath = originalFilePath;
     OriginalStartLine = originalStartLine;
     OriginalStartColumn = originalStartColumn;
     OriginalEndLine = originalEndLine;
     OriginalEndColumn = originalEndColumn;
 }
            public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId projectId, DocumentId documentId, CancellationToken cancellationToken)
            {
                if (solution == null)
                {
                    return GetDiagnosticData();
                }

                if (documentId != null)
                {
                    var document = solution.GetDocument(documentId);

                    await AppendDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false);
                    await AppendProjectAndDocumentDiagnosticsAsync(document.Project, document, d => d.DocumentId == documentId, cancellationToken).ConfigureAwait(false);
                    return GetDiagnosticData();
                }

                if (projectId != null)
                {
                    await AppendDiagnosticsAsync(solution.GetProject(projectId), cancellationToken: cancellationToken).ConfigureAwait(false);
                    return GetDiagnosticData();
                }

                await AppendDiagnosticsAsync(solution, cancellationToken: cancellationToken).ConfigureAwait(false);
                return GetDiagnosticData();
            }
 internal SearchRefactoringWorkitem(ICodeHistoryRecord latestRecord, 
     DocumentId documentId)
 {
     this.latestRecord = latestRecord;
     this.documentId = documentId;
     logger = NLoggerUtil.GetNLogger(typeof(SearchRefactoringWorkitem));
 }
            public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId)
            {
                var nonComplexifiedSpans = GetNonComplexifiedReplacements(documentId);
                var complexifiedSpans = GetComplexifiedReplacements(documentId);

                return nonComplexifiedSpans.Concat(complexifiedSpans);
            }
Example #19
0
 public DiagnosticData(
     string id,
     string category,
     string message,
     string enuMessageForBingSearch,
     DiagnosticSeverity severity,
     bool isEnabledByDefault,
     int warningLevel,
     Workspace workspace,
     ProjectId projectId,
     DocumentId documentId = null,
     TextSpan? span = null,
     string originalFilePath = null,
     int originalStartLine = 0,
     int originalStartColumn = 0,
     int originalEndLine = 0,
     int originalEndColumn = 0,
     string title = null,
     string description = null,
     string helpLink = null) :
         this(
             id, category, message, enuMessageForBingSearch,
             severity, severity, isEnabledByDefault, warningLevel,
             ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty,
             workspace, projectId, documentId, span,
             null, originalStartLine, originalStartColumn, originalEndLine, originalEndColumn,
             originalFilePath, originalStartLine, originalStartColumn, originalEndLine, originalEndColumn,
             title, description, helpLink)
 {
 }
Example #20
0
        /// <summary>
        /// Load a text and a version of the document in the workspace.
        /// </summary>
        /// <exception cref="IOException"></exception>
        public override async Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
        {
            DateTime prevLastWriteTime = FileUtilities.GetFileTimeStamp(_path);

            TextAndVersion textAndVersion;

            // Open file for reading with FileShare mode read/write/delete so that we do not lock this file.
            using (var stream = FileUtilities.RethrowExceptionsAsIOException(() => new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: true)))
            {
                var version = VersionStamp.Create(prevLastWriteTime);

                // we do this so that we asynchronously read from file. and this should allocate less for IDE case. 
                // but probably not for command line case where it doesn't use more sophisticated services.
                using (var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false))
                {
                    var text = CreateText(readStream, workspace);
                    textAndVersion = TextAndVersion.Create(text, version, _path);
                }
            }

            // Check if the file was definitely modified and closed while we were reading. In this case, we know the read we got was
            // probably invalid, so throw an IOException which indicates to our caller that we should automatically attempt a re-read.
            // If the file hasn't been closed yet and there's another writer, we will rely on file change notifications to notify us
            // and reload the file.
            DateTime newLastWriteTime = FileUtilities.GetFileTimeStamp(_path);
            if (!newLastWriteTime.Equals(prevLastWriteTime))
            {
                var message = string.Format(WorkspacesResources.File_was_externally_modified_colon_0, _path);
                throw new IOException(message);
            }

            return textAndVersion;
        }
 protected AbstractRemoveDocumentUndoUnit(
     VisualStudioWorkspaceImpl workspace,
     DocumentId documentId)
     : base(workspace, documentId.ProjectId)
 {
     DocumentId = documentId;
 }
 protected static ValueSource<TextAndVersion> CreateRecoverableText(TextLoader loader, DocumentId documentId, SolutionServices services)
 {
     return new RecoverableTextAndVersion(
         new AsyncLazy<TextAndVersion>(c => LoadTextAsync(loader, documentId, services, c), cacheResult: false),
         services.TemporaryStorage,
         services.TextCache);
 }
        protected Task RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind kind, Solution oldSolution, Solution newSolution, ProjectId projectId = null, DocumentId documentId = null)
        {
            if (newSolution == null)
            {
                throw new ArgumentNullException(nameof(newSolution));
            }

            if (oldSolution == newSolution)
            {
                return SpecializedTasks.EmptyTask;
            }

            if (projectId == null && documentId != null)
            {
                projectId = documentId.ProjectId;
            }

            var ev = _eventMap.GetEventHandlers<EventHandler<WorkspaceChangeEventArgs>>(WorkspaceChangeEventName);
            if (ev.HasHandlers)
            {
                return this.ScheduleTask(() =>
                {
                    var args = new WorkspaceChangeEventArgs(kind, oldSolution, newSolution, projectId, documentId);
                    ev.RaiseEvent(handler => handler(this, args));
                }, "Workspace.WorkspaceChanged");
            }
            else
            {
                return SpecializedTasks.EmptyTask;
            }
        }
 public SolutionPreviewItem(ProjectId projectId, DocumentId documentId, string text)
 {
     ProjectId = projectId;
     DocumentId = documentId;
     Text = text;
     LazyPreview = c => Task.FromResult<object>(text);
 }
Example #25
0
        public TodoItem(
            int priority,
            string message,
            Workspace workspace,
            DocumentId documentId,
            int mappedLine,
            int originalLine,
            int mappedColumn,
            int originalColumn,
            string mappedFilePath,
            string originalFilePath)
        {
            Priority = priority;
            Message = message;

            Workspace = workspace;
            DocumentId = documentId;

            MappedLine = mappedLine;
            MappedColumn = mappedColumn;
            MappedFilePath = mappedFilePath;

            OriginalLine = originalLine;
            OriginalColumn = originalColumn;
            OriginalFilePath = originalFilePath;
        }
            public Session(
                RenameLocations renameLocationSet,
                Location renameSymbolDeclarationLocation,
                string originalText,
                string replacementText,
                OptionSet optionSet,
                Func<IEnumerable<ISymbol>, bool?> newSymbolsAreValid,
                CancellationToken cancellationToken)
            {
                _renameLocationSet = renameLocationSet;
                _renameSymbolDeclarationLocation = renameSymbolDeclarationLocation;
                _originalText = originalText;
                _replacementText = replacementText;
                _optionSet = optionSet;
                _hasConflictCallback = newSymbolsAreValid;
                _cancellationToken = cancellationToken;

                _renamedSymbolDeclarationAnnotation = new RenameAnnotation();

                _conflictLocations = SpecializedCollections.EmptySet<ConflictLocationInfo>();
                _replacementTextValid = true;
                _possibleNameConflicts = new List<string>();

                // only process documents which possibly contain the identifiers.
                _documentsIdsToBeCheckedForConflict = new HashSet<DocumentId>();
                _documentIdOfRenameSymbolDeclaration = renameLocationSet.Solution.GetDocument(renameSymbolDeclarationLocation.SourceTree).Id;

                _renameAnnotations = new AnnotationTable<RenameAnnotation>(RenameAnnotation.Kind);
            }
 public ConflictLocationInfo(RelatedLocation location)
 {
     Debug.Assert(location.ComplexifiedTargetSpan.Contains(location.ConflictCheckSpan) || location.Type == RelatedLocationType.UnresolvableConflict);
     this.ComplexifiedSpan = location.ComplexifiedTargetSpan;
     this.DocumentId = location.DocumentId;
     this.OriginalIdentifierSpan = location.ConflictCheckSpan;
 }
 public DiagnosticsUpdatedArgs(
     object id, Workspace workspace, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<DiagnosticData> diagnostics) :
         base(id, workspace, projectId, documentId)
 {
     this.Solution = solution;
     this.Diagnostics = diagnostics;
 }
        private bool TryAdjustSpanIfNeededForVenus(
            DocumentId documentId, FileLinePositionSpan originalLineInfo, FileLinePositionSpan mappedLineInfo, out LinePositionSpan originalSpan, out LinePositionSpan mappedSpan)
        {
            var startChanged = true;
            MappedSpan startLineColumn;
            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, out startLineColumn))
            {
                startChanged = false;
                startLineColumn = new MappedSpan(originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, mappedLineInfo.StartLinePosition.Line, mappedLineInfo.StartLinePosition.Character);
            }

            var endChanged = true;
            MappedSpan endLineColumn;
            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, out endLineColumn))
            {
                endChanged = false;
                endLineColumn = new MappedSpan(originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, mappedLineInfo.EndLinePosition.Line, mappedLineInfo.EndLinePosition.Character);
            }

            // start and end position can be swapped when mapped between primary and secondary buffer if start position is within visible span (at the edge)
            // but end position is outside of visible span. in that case, swap start and end position.
            originalSpan = GetLinePositionSpan(startLineColumn.OriginalLinePosition, endLineColumn.OriginalLinePosition);
            mappedSpan = GetLinePositionSpan(startLineColumn.MappedLinePosition, endLineColumn.MappedLinePosition);

            return startChanged || endChanged;
        }
        public void GetAdjustedDiagnosticSpan(
            DocumentId documentId, Location location,
            out TextSpan sourceSpan, out FileLinePositionSpan originalLineInfo, out FileLinePositionSpan mappedLineInfo)
        {
            sourceSpan = location.SourceSpan;
            originalLineInfo = location.GetLineSpan();
            mappedLineInfo = location.GetMappedLineSpan();

            // Update the original source span, if required.
            LinePositionSpan originalSpan;
            LinePositionSpan mappedSpan;
            if (!TryAdjustSpanIfNeededForVenus(documentId, originalLineInfo, mappedLineInfo, out originalSpan, out mappedSpan))
            {
                return;
            }

            if (originalSpan.Start != originalLineInfo.StartLinePosition || originalSpan.End != originalLineInfo.EndLinePosition)
            {
                originalLineInfo = new FileLinePositionSpan(originalLineInfo.Path, originalSpan.Start, originalSpan.End);

                var textLines = location.SourceTree.GetText().Lines;
                var startPos = textLines.GetPosition(originalSpan.Start);
                var endPos = textLines.GetPosition(originalSpan.End);
                sourceSpan = new TextSpan(startPos, endPos - startPos);
            }

            if (mappedSpan.Start != mappedLineInfo.StartLinePosition || mappedSpan.End != mappedLineInfo.EndLinePosition)
            {
                mappedLineInfo = new FileLinePositionSpan(mappedLineInfo.Path, mappedSpan.Start, mappedSpan.End);
            }
        }
Example #31
0
 public void RemoveDocument(DocumentId documentId)
 {
     // REVIEW: do we need to fire events when a document is removed from the solution?
     FireEvents(documentId, CancellationToken.None);
 }
 private static string GetRemoveLogMessage(DocumentId id)
 => $"document remove: {id.ToString()}";
 private static object CreateId(StateSet stateSet, DocumentId documentId, AnalysisKind kind)
 => new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, documentId, (int)kind, stateSet.ErrorSourceName);
 public void RemoveDocument(DocumentId documentId)
 {
     // a file is removed from misc project
     RaiseEmptyDiagnosticUpdated(documentId);
 }
 public ImmutableArray <DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
 {
     // pull model not supported
     return(ImmutableArray <DiagnosticData> .Empty);
 }
 private void RaiseEmptyDiagnosticUpdated(DocumentId documentId)
 {
     _service.RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs.DiagnosticsRemoved(
                                          ValueTuple.Create(this, documentId), _workspace, null, documentId.ProjectId, documentId));
 }
Example #37
0
 public ExcessSource(LanguageService service, IVsTextLines textLines, Colorizer colorizer, VisualStudioWorkspace workspace, DocumentId id) :
     base(service, textLines, colorizer)
 {
     _workspace = workspace;
     _id        = id;
 }
Example #38
0
        public async Task PinvokeMethodReferences_VB()
        {
            var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                @"
Module Module1
        Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer
 
        Private prop As Integer
        Property Prop1 As Integer
            Get
                Return prop
            End Get
            Set(value As Integer)
                CreateDirectory(""T"")  ' Method Call 1
                prop = value
                prop = Nothing
            End Set
        End Property

        Sub Main()
          CreateDirectory(""T"") 'Method Call 2            
          NormalMethod() ' Method Call 1
          NormalMethod() ' Method Call 2
       End Sub

       Sub NormalMethod()
       End Sub
 End Module
            ");

            var prj1Id = ProjectId.CreateNewId();
            var docId  = DocumentId.CreateNewId(prj1Id);

            var sln = new AdhocWorkspace().CurrentSolution
                      .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                      .AddMetadataReference(prj1Id, MscorlibRef)
                      .AddDocument(docId, "testFile", tree.GetText());

            var prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            var comp = await prj.GetCompilationAsync();

            var semanticModel = comp.GetSemanticModel(tree);

            SyntaxNode declareMethod = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.DeclareStatementSyntax>().FirstOrDefault();
            SyntaxNode normalMethod  = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.MethodStatementSyntax>().ToList()[1];

            // declared method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
 public void OnDocumentRemoved(DocumentId documentId)
 {
 }
Example #40
0
        public async Task PinvokeMethodReferences_CS()
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
                @"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
static class Module1
{
	[DllImport(""kernel32"", EntryPoint = ""CreateDirectoryA"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern int CreateDirectory(string lpPathName);

        private static int prop;
        public static int Prop1
        {
            get { return prop; }
            set
            {
                CreateDirectory(""T"");
                // Method Call 1
                prop = value;
                prop = null;
            }
        }

        public static void Main()
        {
            CreateDirectory(""T""); // Method Call 2            
            NormalMethod(); // Method Call 1
            NormalMethod(); // Method Call 2
        }

        public static void NormalMethod()
        {
        }
    }
                ");

            var prj1Id = ProjectId.CreateNewId();
            var docId  = DocumentId.CreateNewId(prj1Id);

            var sln = new AdhocWorkspace().CurrentSolution
                      .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.CSharp)
                      .AddMetadataReference(prj1Id, MscorlibRef)
                      .AddDocument(docId, "testFile", tree.GetText());

            var prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            var comp = await prj.GetCompilationAsync();

            var semanticModel = comp.GetSemanticModel(tree);

            var        methodlist    = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax>().ToList();
            SyntaxNode declareMethod = methodlist.ElementAt(0);
            SyntaxNode normalMethod  = methodlist.ElementAt(2);

            // pinvoke method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(2, references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(2, references.ElementAt(0).Locations.Count());
        }
 public void OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext)
 {
 }
 public void OnDocumentTextUpdatedOnDisk(DocumentId id)
 {
 }
 public void OnAdditionalDocumentRemoved(DocumentId documentInfo)
 {
 }
 public void OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext)
 {
 }
 public void SetActiveDocument(DocumentId newActiveDocumentId)
 {
     _activeDocumentId = newActiveDocumentId;
     _activeDocumentChangedEventHandler?.Invoke(this, newActiveDocumentId);
 }
 public void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id)
 {
 }
 public ImmutableArray <DiagnosticData> GetDiagnostics(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(includeSuppressedDiagnostics ? _diagnostics : _diagnostics.WhereAsArray(d => !d.IsSuppressed));
 }
 public void OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader)
 {
 }
Example #49
0
 public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options = null) => true;
 /// <summary>
 /// Compares the specified actual source and the specified expected
 /// source and then if there is any difference in them, asserts to fail
 /// the test case with showing the specified <c>DocumentId</c> and the
 /// location of the first difference.
 /// </summary>
 /// <param name="id">
 /// The <c>DocumentId</c> of the source to compare.
 /// </param>
 /// <param name="actual">
 /// The actual source that the CodeFix provider provides.
 /// </param>
 /// <param name="expected">
 /// The expected source that the CodeFix provider is supposed to
 /// provide.
 /// </param>
 private static void Compare(
     DocumentId id, string actual, string expected)
 {
Example #51
0
 public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options = null) => true;
            public override Task <TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
            {
                TextAndVersion textAndVersion;

                try
                {
                    var prevLastWriteTime = File.GetLastWriteTimeUtc(_filePath);

                    using (var stream = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                    {
                        var version = VersionStamp.Create(prevLastWriteTime);
                        var text    = SourceText.From(stream);
                        textAndVersion = TextAndVersion.Create(text, version);
                    }

                    var newLastWriteTime = File.GetLastWriteTimeUtc(_filePath);
                    if (!newLastWriteTime.Equals(prevLastWriteTime))
                    {
                        throw new IOException($"File was externally modified: {_filePath}");
                    }
                }
                catch (FileNotFoundException)
                {
                    // This can typically occur when a file is renamed. What happens is the client "closes" the old file before any file system "rename" event makes it to us. Resulting
                    // in us trying to refresh the "closed" files buffer with what's on disk; however, there's nothing actually on disk because the file was renamed.
                    textAndVersion = TextAndVersion.Create(SourceText.From(string.Empty), VersionStamp.Default, filePath: _filePath);
                }

                return(Task.FromResult(textAndVersion));
            }
Example #53
0
 public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0) => true;
Example #54
0
 public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0, OptionSet options = null) => true;
 public void UpdateText(DocumentId documentId, string text)
 {
     OnDocumentTextChanged(documentId, SourceText.From(text, Encoding.UTF8), PreservationMode.PreserveValue);
 }
Example #56
0
 public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) => true;
Example #57
0
        protected ImmutableArray <DocumentId> GetDocumentsWithSameFilePath(Solution solution, DocumentId documentId)
        {
            var document = solution.GetDocument(documentId);

            if (document == null)
            {
                return(ImmutableArray <DocumentId> .Empty);
            }

            return(solution.GetDocumentIdsWithFilePath(document.FilePath));
        }
Example #58
0
 public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) => true;
        public override Task <TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            SourceText text;

            if (IdeServices.DocumentManager?.Documents.Any(doc => doc.IsFile && doc.FileName != null && FilePath.PathComparer.Compare(Path.GetFullPath(doc.FileName), fileName) == 0 && doc.Editor != null) == true)
            {
                var document = IdeServices.DocumentManager?.Documents.FirstOrDefault(doc => doc.IsFile && doc.FileName != null && FilePath.PathComparer.Compare(Path.GetFullPath(doc.FileName), fileName) == 0 && doc.Editor != null);
                text = MonoDevelopSourceText.Create(document.Editor);
            }
            else
            {
                try {
                    if (File.Exists(fileName))
                    {
                        text = SourceText.From(TextFileUtility.GetText(fileName));
                    }
                    else
                    {
                        text = SourceText.From("");
                    }
                } catch (Exception e) {
                    LoggingService.LogError($"Failed to get file text for {fileName}", e);
                    text = SourceText.From("");
                }
            }
            return(Task.FromResult(TextAndVersion.Create(text, VersionStamp.Create())));
        }
 public void RemoveProject(DocumentId id)
 {
     OnProjectRemoved(id.ProjectId);
 }