Beispiel #1
0
 public SyntaxTree ParseText(string code, SourceCodeKind kind)
 {
     var options = _roslynAbstraction.NewParseOptions<LanguageVersion, CSharpParseOptions>(
         _roslynAbstraction.GetMaxValue<LanguageVersion>(), kind
     );
     return _roslynAbstraction.ParseText(typeof(CSharpSyntaxTree), code, options);
 }
Beispiel #2
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;
        }
        protected async Task AssertNavigatedAsync(string code, bool next, SourceCodeKind? sourceCodeKind = null)
        {
            var kinds = sourceCodeKind != null
                ? SpecializedCollections.SingletonEnumerable(sourceCodeKind.Value)
                : new[] { SourceCodeKind.Regular, SourceCodeKind.Script };

            foreach (var kind in kinds)
            {
                using (var workspace = await TestWorkspaceFactory.CreateWorkspaceFromFileAsync(
                    LanguageName,
                    compilationOptions: null,
                    parseOptions: DefaultParseOptions.WithKind(kind),
                    content: code))
                {
                    var hostDocument = workspace.DocumentWithCursor;
                    var document = workspace.CurrentSolution.GetDocument(hostDocument.Id);
                    Assert.Empty((await document.GetSyntaxTreeAsync()).GetDiagnostics());
                    var targetPosition = await GoToAdjacentMemberCommandHandler.GetTargetPositionAsync(
                        document,
                        hostDocument.CursorPosition.Value,
                        next,
                        CancellationToken.None);

                    Assert.NotNull(targetPosition);
                    Assert.Equal(hostDocument.SelectedSpans.Single().Start, targetPosition.Value);
                }
            }
        }
Beispiel #4
0
        private ScriptSource/*!*/ CreateCommandSource(string/*!*/ command, SourceCodeKind kind, string/*!*/ sourceUnitId) {
#if SILVERLIGHT
            return Engine.CreateScriptSourceFromString(command, kind);
#else
            var encoding = GetSourceCodeEncoding();
            return Engine.CreateScriptSource(new BinaryContentProvider(encoding.GetBytes(command)), sourceUnitId, encoding, kind);
#endif
        }
 public static DocumentId AddDocument(this Workspace workspace, ProjectId projectId, IEnumerable<string> folders, string name, SourceText initialText, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
 {
     var id = projectId.CreateDocumentId(name, folders);
     var oldSolution = workspace.CurrentSolution;
     var newSolution = oldSolution.AddDocument(id, name, initialText, folders).GetDocument(id).WithSourceCodeKind(sourceCodeKind).Project.Solution;
     workspace.TryApplyChanges(newSolution);
     return id;
 }
 public DocumentChecksumObjectInfo(DocumentId id, string name, IReadOnlyList<string> folders, SourceCodeKind sourceCodeKind, string filePath, bool isGenerated)
 {
     Id = id;
     Name = name;
     Folders = folders;
     SourceCodeKind = sourceCodeKind;
     FilePath = filePath;
     IsGenerated = isGenerated;
 }
            public StandardTextDocument(
                DocumentProvider documentProvider,
                IVisualStudioHostProject project,
                DocumentKey documentKey,
                IReadOnlyList<string> folderNames,
                SourceCodeKind sourceCodeKind,
                ITextUndoHistoryRegistry textUndoHistoryRegistry,
                IVsFileChangeEx fileChangeService,
                ITextBuffer openTextBuffer,
                DocumentId id,
                EventHandler updatedOnDiskHandler,
                EventHandler<bool> openedHandler,
                EventHandler<bool> closingHandler)
            {
                Contract.ThrowIfNull(documentProvider);

                this.Project = project;
                this.Id = id ?? DocumentId.CreateNewId(project.Id, documentKey.Moniker);
                this.Folders = folderNames;

                _documentProvider = documentProvider;

                this.Key = documentKey;
                this.SourceCodeKind = sourceCodeKind;
                _itemMoniker = documentKey.Moniker;
                _textUndoHistoryRegistry = textUndoHistoryRegistry;
                _fileChangeTracker = new FileChangeTracker(fileChangeService, this.FilePath);
                _fileChangeTracker.UpdatedOnDisk += OnUpdatedOnDisk;

                _openTextBuffer = openTextBuffer;
                _snapshotTracker = new ReiteratedVersionSnapshotTracker(openTextBuffer);

                // The project system does not tell us the CodePage specified in the proj file, so
                // we use null to auto-detect.
                _doNotAccessDirectlyLoader = new FileTextLoader(documentKey.Moniker, defaultEncoding: null);

                // If we aren't already open in the editor, then we should create a file change notification
                if (openTextBuffer == null)
                {
                    _fileChangeTracker.StartFileChangeListeningAsync();
                }

                if (updatedOnDiskHandler != null)
                {
                    UpdatedOnDisk += updatedOnDiskHandler;
                }

                if (openedHandler != null)
                {
                    Opened += openedHandler;
                }

                if (closingHandler != null)
                {
                    Closing += closingHandler;
                }
            }
 protected override Task VerifyWorkerAsync(
     string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull,
     SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
     int? glyph, int? matchPriority)
 {
     return base.VerifyWorkerAsync(code, position,
         expectedItemOrNull, expectedDescriptionOrNull,
         SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence,
         glyph, matchPriority);
 }
 public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
 {
     switch (sourceCodeKind)
     {
         case SourceCodeKind.Script:
             return ".csx";
         default:
             return ".cs";
     }
 }
 protected override void VerifyWorker(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph)
 {
     BaseVerifyWorker(code,
         position,
         expectedItemOrNull,
         expectedDescriptionOrNull,
         sourceCodeKind,
         usePreviousCharAsTrigger,
         checkForAbsence,
         glyph);
 }
		protected void VerifyItemExists(string input, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, bool experimental = false, int? glyph = null)
		{
			var provider = CreateProvider (input, sourceCodeKind, usePreviousCharAsTrigger);

			if (provider.Find (expectedItem) == null) {
				foreach (var item in provider)
					Console.WriteLine (item.DisplayText);
			}

			Assert.IsNotNull(provider.Find(expectedItem), "item '" + expectedItem + "' not found.");	
		}
Beispiel #12
0
 public static DocumentInfo Create(
     DocumentId id,
     string name,
     IEnumerable<string> folders = null,
     SourceCodeKind sourceCodeKind = SourceCodeKind.Regular,
     TextLoader loader = null,
     string filePath = null,
     bool isGenerated = false)
 {
     return new DocumentInfo(id, name, folders, sourceCodeKind, loader, filePath, isGenerated);
 }
        private async Task VerifyKeywordWithRefsAsync(SourceCodeKind kind, string text)
        {
            switch (kind)
            {
                case SourceCodeKind.Regular:
                    await VerifyWorkerAsync(text, absent: false, options: Options.Regular);
                    break;

                case SourceCodeKind.Script:
                    await VerifyWorkerAsync(text, absent: false, options: Options.Script);
                    break;
            }
        }
 public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
 {
     string result;
     if (sourceCodeKind != SourceCodeKind.Script)
     {
         result = ".vb";
     }
     else
     {
         result = ".vbx";
     }
     return result;
 }
        private async Task VerifyAbsenceWithRefsAsync(SourceCodeKind kind, string text)
        {
            switch (kind)
            {
                case SourceCodeKind.Regular:
                    await VerifyWorkerAsync(text, absent: true, options: Options.Regular.WithRefsFeature());
                    break;

                case SourceCodeKind.Script:
                    await VerifyWorkerAsync(text, absent: true, options: Options.Script.WithRefsFeature());
                    break;
            }
        }
        protected override async Task VerifyWorkerAsync(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph)
        {
            await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
            await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);

            // Items cannot be partially written if we're checking for their absence,
            // or if we're verifying that the list will show up (without specifying an actual item)
            if (!checkForAbsence && expectedItemOrNull != null)
            {
                await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
                await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
            }
        }
Beispiel #17
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));

            IVsHierarchy sharedHierarchy;
            uint itemIdInSharedHierarchy;
            var isSharedHierarchy = LinkedFileUtilities.TryGetSharedHierarchyAndItemId(hierarchy, itemId, out sharedHierarchy, out itemIdInSharedHierarchy);

            var filePath = isSharedHierarchy
                ? rdt.GetMonikerForHierarchyAndItemId(sharedHierarchy, itemIdInSharedHierarchy)
                : rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);

            // we couldn't look up the document moniker in RDT for a hierarchy/item pair
            // Since we only use this moniker as a key, we could fall back to something else, like the document name.
            if (filePath == null)
            {
                Debug.Assert(false, "Could not get the document moniker for an item in its hierarchy.");
                filePath = hierarchy.GetDocumentNameForHierarchyAndItemId(itemId);
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
        protected override void VerifyWorker(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph)
        {
            // We don't need to try writing comments in from of items in doc comments.
            VerifyAtPosition(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
            VerifyAtEndOfFile(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);

            // Items cannot be partially written if we're checking for their absence,
            // or if we're verifying that the list will show up (without specifying an actual item)
            if (!checkForAbsence && expectedItemOrNull != null)
            {
                VerifyAtPosition_ItemPartiallyWritten(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
                VerifyAtEndOfFile_ItemPartiallyWritten(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
            }
        }
Beispiel #19
0
        public SourceUnit GenerateCode(CodeMemberMethod codeDom, LanguageContext context, string path, SourceCodeKind kind) {
            ContractUtils.RequiresNotNull(codeDom, "codeDom");
            ContractUtils.RequiresNotNull(context, "context");
            ContractUtils.Requires(path == null || path.Length > 0, "path");

            // Convert the CodeDom to source code
            if (_writer != null) {
                _writer.Close();
            }
            _writer = new PositionTrackingWriter();

            WriteFunctionDefinition(codeDom);

            return CreateSourceUnit(context, path, kind);
        }
            public StandardTextDocument(
                DocumentProvider documentProvider,
                IVisualStudioHostProject project,
                DocumentKey documentKey,
                uint itemId,
                SourceCodeKind sourceCodeKind,
                ITextBufferFactoryService textBufferFactoryService,
                ITextUndoHistoryRegistry textUndoHistoryRegistry,
                IVsFileChangeEx fileChangeService,
                ITextBuffer openTextBuffer,
                DocumentId id)
            {
                Contract.ThrowIfNull(documentProvider);
                Contract.ThrowIfNull(textBufferFactoryService);

                this.Project = project;
                this.Id = id ?? DocumentId.CreateNewId(project.Id, documentKey.Moniker);
                this.Folders = project.GetFolderNames(itemId);

                // TODO: 
                // this one doesn't work for asynchronous project load situation where shared projects is loaded after one uses shared file. 
                // we need to figure out what to do on those case. but this works for project k case.
                // opened an issue to track this issue - https://github.com/dotnet/roslyn/issues/1859
                this.SharedHierarchy = project.Hierarchy == null ? null : LinkedFileUtilities.GetSharedHierarchyForItem(project.Hierarchy, itemId);
                _documentProvider = documentProvider;

                this.Key = documentKey;
                this.SourceCodeKind = sourceCodeKind;
                _itemMoniker = documentKey.Moniker;
                _textBufferFactoryService = textBufferFactoryService;
                _textUndoHistoryRegistry = textUndoHistoryRegistry;
                _fileChangeTracker = new FileChangeTracker(fileChangeService, this.FilePath);
                _fileChangeTracker.UpdatedOnDisk += OnUpdatedOnDisk;

                _openTextBuffer = openTextBuffer;
                _snapshotTracker = new ReiteratedVersionSnapshotTracker(openTextBuffer);

                // The project system does not tell us the CodePage specified in the proj file, so
                // we use null to auto-detect.
                _doNotAccessDirectlyLoader = new FileTextLoader(documentKey.Moniker, defaultEncoding: null);

                // If we aren't already open in the editor, then we should create a file change notification
                if (openTextBuffer == null)
                {
                    _fileChangeTracker.StartFileChangeListeningAsync();
                }
            }
Beispiel #21
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            string filePath;
            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemId, out filePath))
                {
                    Environment.FailFast("Failed to get document moniker for a contained document");
                }
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
Beispiel #22
0
        public async Task<Document> UpdateDocumentAsync(string text, SourceCodeKind sourceCodeKind, bool cleanBeforeUpdate = true)
        {
            var hostDocument = (await GetWorkspaceAsync()).Documents.Single();
            var textBuffer = hostDocument.TextBuffer;

            // clear the document
            if (cleanBeforeUpdate)
            {
                UpdateText(hostDocument.TextBuffer, string.Empty);
            }

            // and set the content
            UpdateText(hostDocument.TextBuffer, text);

            (await GetWorkspaceAsync()).OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind);

            return (await GetWorkspaceAsync()).CurrentSolution.GetDocument(hostDocument.Id);
        }
        public Document UpdateDocument(string text, SourceCodeKind sourceCodeKind, bool cleanBeforeUpdate = true)
        {
            var hostDocument = this.Workspace.Documents.Single();
            var textBuffer = hostDocument.TextBuffer;

            // clear the document
            if (cleanBeforeUpdate)
            {
                UpdateText(hostDocument.TextBuffer, string.Empty);
            }

            // and set the conent
            UpdateText(hostDocument.TextBuffer, text);

            this.Workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind);

            return this.Workspace.CurrentSolution.GetDocument(hostDocument.Id);
        }
		public CompletionResult CreateProvider(string input, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false)
		{
			int cursorPosition;
			SemanticModel semanticModel;
			Document document;
			var idx = input.IndexOf("$$", StringComparison.Ordinal);
			if (idx >= 0) {
				input = input.Substring(0, idx) + input.Substring(idx + 1);
			}
			var engine = CodeCompletionBugTests.CreateEngine(input, out cursorPosition, out semanticModel, out document, null, sourceCodeKind);
			char triggerChar = cursorPosition > 0 ? document.GetTextAsync().Result [cursorPosition - 1] : '\0';
			var completionContext = new CompletionContext (document, cursorPosition, semanticModel);
			var exclusiveHandler = CreateContextHandler ();
			if (exclusiveHandler != null) {
				completionContext.AdditionalContextHandlers = new [] { exclusiveHandler };
				completionContext.UseDefaultContextHandlers = false;
			}

			return engine.GetCompletionDataAsync (
				completionContext,
				new CompletionTriggerInfo (usePreviousCharAsTrigger ? CompletionTriggerReason.CharTyped : CompletionTriggerReason.CompletionCommand, triggerChar)).Result;
		}
Beispiel #25
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));
            var filePath = rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
Beispiel #26
0
 public Document WithSourceCodeKind(SourceCodeKind kind)
 => this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id) !;
Beispiel #27
0
        public SourceUnit GenerateCode(CodeMemberMethod codeDom, LanguageContext context, string path, SourceCodeKind kind)
        {
            ContractUtils.RequiresNotNull(codeDom, "codeDom");
            ContractUtils.RequiresNotNull(context, "context");
            ContractUtils.Requires(path == null || path.Length > 0, "path");

            // Convert the CodeDom to source code
            if (_writer != null)
            {
                _writer.Close();
            }
            _writer = new PositionTrackingWriter();

            WriteFunctionDefinition(codeDom);

            return(CreateSourceUnit(context, path, kind));
        }
 public static SourceUnit Make(ScriptEngine engine, string text, SourceCodeKind kind)
 {
     return(Make(engine, text, "None", kind));
 }
 protected override void VerifyWorker(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int?glyph)
 {
     base.VerifyWorker(code, position, expectedItemOrNull, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence, experimental, glyph);
 }
        public DocumentId AddDocument(ProjectId projectId, string filePath, TextLoader loader, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            var documentId = DocumentId.CreateNewId(projectId);
            var project    = this.CurrentSolution.GetProject(projectId);

            return(AddDocument(documentId, project, filePath, loader, sourceCodeKind));
        }
        public DocumentId AddDocument(ProjectId projectId, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            var project = this.CurrentSolution.GetProject(projectId);

            return(AddDocument(project, filePath, sourceCodeKind));
        }
 public DocumentId AddDocument(DocumentId documentId, Project project, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
 {
     return(AddDocument(documentId, project, filePath, new OmniSharpTextLoader(filePath), sourceCodeKind));
 }
        public DocumentId AddDocument(Project project, string filePath, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            var documentId = DocumentId.CreateNewId(project.Id);

            return(AddDocument(documentId, project, filePath, sourceCodeKind));
        }
        protected void AddFile(string filename, SourceCodeKind sourceCodeKind)
        {
            Func <IVisualStudioHostDocument, bool> getIsCurrentContext = document => LinkedFileUtilities.IsCurrentContextHierarchy(document, RunningDocumentTable);

            AddFile(filename, sourceCodeKind, getIsCurrentContext, GetFolderNamesFromHierarchy);
        }
Beispiel #35
0
 protected override ParseOptions CommonWithKind(SourceCodeKind kind)
 {
     return(WithKind(kind));
 }
Beispiel #36
0
        public SourceUnit(LanguageContext context, TextContentProvider contentProvider, string path, SourceCodeKind kind)
        {
            Assert.NotNull(context, contentProvider);
            Debug.Assert(context.CanCreateSourceCode);

            _language        = context;
            _contentProvider = contentProvider;
            Kind             = kind;
            Path             = path;
        }
Beispiel #37
0
        public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName2(SourceCodeKind kind)
        {
            var file1 = @"
namespace Foo.Bar
{
    public class MyClass { }
}";

            var file2 = @"
namespace Foo
{
    using CollectionOfStringBuilders = System.Collections.Generic.List<$$>
}";

            // Completion is not fully qualified
            var expectedCodeAfterCommit = @"
namespace Foo
{
    using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.Bar.MyClass$$>
}";

            var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp);

            await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind : kind);
        }
        internal DocumentId AddDocument(DocumentId documentId, ProjectId projectId, string filePath, TextLoader loader, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            var project = this.CurrentSolution.GetProject(projectId);

            return(AddDocument(documentId, project, filePath, loader, sourceCodeKind));
        }
Beispiel #39
0
            public DocumentId AddTextContainer(SourceTextContainer textContainer, string fullPath, SourceCodeKind sourceCodeKind, ImmutableArray <string> folders)
            {
                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,
                    filePath: fullPath);

                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
                    {
                        _project._workspace.ApplyChangeToWorkspace(w =>
                        {
                            _project._workspace.AddDocumentToDocumentsNotFromFiles(documentInfo.Id);
                            _documentAddAction(w, documentInfo);
                            w.OnDocumentOpened(documentInfo.Id, textContainer);
                        });
                    }
                }

                return(documentId);
            }
Beispiel #40
0
 public abstract ParseOptions CommonWithKind(SourceCodeKind kind);
Beispiel #41
0
        private protected override async Task VerifyWorkerAsync(
            string code,
            int position,
            string expectedItemOrNull,
            string expectedDescriptionOrNull,
            SourceCodeKind sourceCodeKind,
            bool usePreviousCharAsTrigger,
            bool checkForAbsence,
            int?glyph,
            int?matchPriority,
            bool?hasSuggestionItem,
            string displayTextSuffix,
            string displayTextPrefix,
            string inlineDescription = null,
            bool?isComplexTextEdit   = null,
            List <CompletionFilter> matchingFilters = null,
            CompletionItemFlags?flags = null
            )
        {
            await VerifyAtPositionAsync(
                code,
                position,
                usePreviousCharAsTrigger,
                expectedItemOrNull,
                expectedDescriptionOrNull,
                sourceCodeKind,
                checkForAbsence,
                glyph,
                matchPriority,
                hasSuggestionItem,
                displayTextSuffix,
                displayTextPrefix,
                inlineDescription,
                isComplexTextEdit,
                matchingFilters,
                flags
                );

            await VerifyAtEndOfFileAsync(
                code,
                position,
                usePreviousCharAsTrigger,
                expectedItemOrNull,
                expectedDescriptionOrNull,
                sourceCodeKind,
                checkForAbsence,
                glyph,
                matchPriority,
                hasSuggestionItem,
                displayTextSuffix,
                displayTextPrefix,
                inlineDescription,
                isComplexTextEdit,
                matchingFilters,
                flags
                );

            // Items cannot be partially written if we're checking for their absence,
            // or if we're verifying that the list will show up (without specifying an actual item)
            if (!checkForAbsence && expectedItemOrNull != null)
            {
                await VerifyAtPosition_ItemPartiallyWrittenAsync(
                    code,
                    position,
                    usePreviousCharAsTrigger,
                    expectedItemOrNull,
                    expectedDescriptionOrNull,
                    sourceCodeKind,
                    checkForAbsence,
                    glyph,
                    matchPriority,
                    hasSuggestionItem,
                    displayTextSuffix,
                    displayTextPrefix,
                    inlineDescription,
                    isComplexTextEdit,
                    matchingFilters
                    );

                await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(
                    code,
                    position,
                    usePreviousCharAsTrigger,
                    expectedItemOrNull,
                    expectedDescriptionOrNull,
                    sourceCodeKind,
                    checkForAbsence,
                    glyph,
                    matchPriority,
                    hasSuggestionItem,
                    displayTextSuffix,
                    displayTextPrefix,
                    inlineDescription,
                    isComplexTextEdit,
                    matchingFilters
                    );
            }
        }
Beispiel #42
0
 public DocumentInfo WithSourceCodeKind(SourceCodeKind kind)
 {
     return(this.With(attributes: Attributes.With(sourceCodeKind: kind)));
 }
 public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
 {
     // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
     //return (sourceCodeKind != SourceCodeKind.Script) ? ".cs" : ".csx";
     return(".cs");
 }
Beispiel #44
0
        /// <summary>
        /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts.
        /// </summary>
        /// <param name="codeBeforeCommit">The source code (not markup).</param>
        /// <param name="position">Position where intellisense is invoked.</param>
        /// <param name="itemToCommit">The item to commit from the completion provider.</param>
        /// <param name="expectedCodeAfterCommit">The expected code after commit.</param>
        protected virtual async Task VerifyProviderCommitWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit,
                                                                     char?commitChar, string textTypedSoFar, SourceCodeKind sourceCodeKind)
        {
            var document1 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind);

            await VerifyProviderCommitCheckResultsAsync(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar);

            if (await CanUseSpeculativeSemanticModelAsync(document1, position))
            {
                var document2 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate : false);
                await VerifyProviderCommitCheckResultsAsync(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar);
            }
        }
		static DocumentInfo CreateDocumentInfo (SolutionData data, string projectName, ProjectData id, MonoDevelop.Projects.ProjectFile f, SourceCodeKind sourceCodeKind)
		{
			var filePath = f.FilePath;
			return DocumentInfo.Create (
				id.GetOrCreateDocumentId (filePath),
				filePath,
				new [] { projectName }.Concat (f.ProjectVirtualPath.ParentDirectory.ToString ().Split (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)),
				sourceCodeKind,
				CreateTextLoader (data, f.Name),
				f.Name,
				false
			);
		}
Beispiel #46
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sources"></param>
 /// <param name="refAssemblies"></param>
 /// <param name="codeKind"></param>
 /// <returns></returns>
 public static ScriptScope ExecutePythonSource(string sources, string[] refAssemblies, SourceCodeKind codeKind = SourceCodeKind.Statements)
 {
     if (IsCompiling)
     {
         return(null);
     }
     return(_runtimeDomain.Scope.ExecutePythonSource(sources, refAssemblies, codeKind));
 }
Beispiel #47
0
        /// <summary>
        /// Gets the <see cref="IVisualStudioHostDocument"/> for the file at the given filePath.
        /// If we are on the foreground thread and this document is already open in the editor,
        /// then we also attempt to associate the text buffer with it.
        /// Otherwise, if we are on a background thread, then this text buffer association will happen on a scheduled task
        /// whenever <see cref="NotifyDocumentRegisteredToProjectAndStartToRaiseEvents"/> is invoked for the returned document.
        /// </summary>
        public IVisualStudioHostDocument TryGetDocumentForFile(
            IVisualStudioHostProject hostProject,
            string filePath,
            SourceCodeKind sourceCodeKind,
            Func <ITextBuffer, bool> canUseTextBuffer,
            Func <uint, IReadOnlyList <string> > getFolderNames,
            EventHandler updatedOnDiskHandler  = null,
            EventHandler <bool> openedHandler  = null,
            EventHandler <bool> closingHandler = null)
        {
            var documentKey = new DocumentKey(hostProject, filePath);
            StandardTextDocument document;

            lock (_gate)
            {
                if (_documentMap.TryGetValue(documentKey, out document))
                {
                    return(document);
                }
            }

            ITextBuffer openTextBuffer = null;
            uint        foundCookie    = VSConstants.VSCOOKIE_NIL;

            if (IsForeground())
            {
                // If we are on the foreground thread and this document is already open in the editor we want to associate the text buffer with it.
                // Otherwise, we are on a background thread, and this text buffer association will happen on a scheduled task
                // whenever NotifyDocumentRegisteredToProjectAndStartToRaiseEvents is invoked for the returned document.
                // However, determining if a document is already open is a bit complicated. With the introduction
                // of the lazy tabs feature in Dev12, a document may be open (i.e. it has a tab in the shell) but not
                // actually initialized (no data has been loaded for it because its contents have not actually been
                // viewed or used). We only care about documents that are open AND initialized.
                // That means we can't call IVsRunningDocumentTable::FindAndLockDocument to find the document; if the
                // document is open but not initialized, the call will force initialization. This is bad for two
                // reasons:
                //   1.) It circumvents lazy tabs for any document that is part of a VB or C# project.
                //   2.) Initialization may cause a whole host of other code to run synchronously, such as taggers.
                // Instead, we check if the document is already initialized, and avoid asking for the doc data and
                // hierarchy if it is not.
                if (_runningDocumentTable.TryGetCookieForInitializedDocument(documentKey.Moniker, out foundCookie))
                {
                    object foundDocData = _runningDocumentTable.GetDocumentData(foundCookie);
                    openTextBuffer = TryGetTextBufferFromDocData(foundDocData);
                    if (openTextBuffer == null)
                    {
                        // We're open but not open as a normal text buffer. This can happen if the
                        // project system (say in ASP.NET cases) is telling us to add a file which
                        // actually isn't a normal text file at all.
                        return(null);
                    }

                    if (!canUseTextBuffer(openTextBuffer))
                    {
                        return(null);
                    }
                }
            }

            lock (_gate)
            {
                // If this is being added through a public call to Workspace.AddDocument (say, ApplyChanges) then we might
                // already have a document ID that we should be using here.
                _documentIdHints.TryGetValue(filePath, out var id);

                document = new StandardTextDocument(
                    this,
                    hostProject,
                    documentKey,
                    getFolderNames,
                    sourceCodeKind,
                    _textUndoHistoryRegistry,
                    _fileChangeService,
                    openTextBuffer,
                    id,
                    updatedOnDiskHandler,
                    openedHandler,
                    closingHandler);

                // Add this to our document map
                _documentMap.Add(documentKey, document);

                if (openTextBuffer != null)
                {
                    AddCookieOpenDocumentPair_NoLock(foundCookie, documentKey);
                }
            }

            return(document);
        }
Beispiel #48
0
 protected abstract Task BaseVerifyWorkerAsync(
     string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull,
     SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
     int?glyph, int?matchPriority);
Beispiel #49
0
 /// <summary>
 /// Creates a new options instance with the specified source code kind.
 /// </summary>
 public ParseOptions WithKind(SourceCodeKind kind)
 {
     return(CommonWithKind(kind));
 }
Beispiel #50
0
        public static DocumentId AddDocument(this Workspace workspace, ProjectId projectId, IEnumerable <string> folders, string name, SourceText initialText, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            var id          = projectId.CreateDocumentId(name, folders);
            var oldSolution = workspace.CurrentSolution;
            var newSolution = oldSolution.AddDocument(id, name, initialText, folders).GetDocument(id).WithSourceCodeKind(sourceCodeKind).Project.Solution;

            workspace.TryApplyChanges(newSolution);
            return(id);
        }
        internal DocumentId AddDocument(DocumentId documentId, Project project, string filePath, TextLoader loader, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            var basePath = Path.GetDirectoryName(project.FilePath);
            var fullPath = Path.GetDirectoryName(filePath);

            IEnumerable <string> folders = null;

            // folder computation is best effort. in case of exceptions, we back out because it's not essential for core features
            try
            {
                // find the relative path from project file to our document
                var relativeDocumentPath = FileSystemHelper.GetRelativePath(fullPath, basePath);

                // only set document's folders if
                // 1. relative path was computed
                // 2. path is not pointing any level up
                if (relativeDocumentPath != null && !relativeDocumentPath.StartsWith(".."))
                {
                    folders = relativeDocumentPath?.Split(new[] { Path.DirectorySeparatorChar });
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"An error occurred when computing a relative path from {basePath} to {fullPath}. Document at {filePath} will be processed without folder structure.");
            }

            var documentInfo = DocumentInfo.Create(documentId, Path.GetFileName(filePath), folders: folders, filePath: filePath, loader: loader, sourceCodeKind: sourceCodeKind);

            AddDocument(documentInfo);

            return(documentId);
        }
 public void AddSourceFile(string filePath, bool isInCurrentContext = true, IEnumerable <string> folderNames = null, SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
 {
     UnderlyingContext.AddSourceFile(filePath, isInCurrentContext, folderNames, sourceCodeKind);
 }
Beispiel #53
0
        protected void AddFile(string filename, SourceCodeKind sourceCodeKind, Func<IVisualStudioHostDocument, bool> getIsCurrentContext, IReadOnlyList<string> folderNames)
        {
            var document = this.DocumentProvider.TryGetDocumentForFile(
                this,
                folderNames,
                filePath: filename,
                sourceCodeKind: sourceCodeKind,
                canUseTextBuffer: CanUseTextBuffer);

            if (document == null)
            {
                // It's possible this file is open in some very strange editor. In that case, we'll just ignore it.
                // This might happen if somebody decides to mark a non-source-file as something to compile.

                // TODO: Venus does this for .aspx/.cshtml files which is completely unnecessary for Roslyn. We should remove that code.
                AddUntrackedFile(filename);
                return;
            }

            AddDocument(document, getIsCurrentContext(document));
        }
Beispiel #54
0
        protected override void VerifyWorker(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int?glyph)
        {
            // We don't need to try writing comments in from of items in doc comments.
            VerifyAtPosition(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
            VerifyAtEndOfFile(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);

            // Items cannot be partially written if we're checking for their absence,
            // or if we're verifying that the list will show up (without specifying an actual item)
            if (!checkForAbsence && expectedItemOrNull != null)
            {
                VerifyAtPosition_ItemPartiallyWritten(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
                VerifyAtEndOfFile_ItemPartiallyWritten(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, experimental, glyph);
            }
        }
Beispiel #55
0
 /// <summary>
 /// Creates a new instance of this document updated to have the source code kind specified.
 /// </summary>
 public Document WithSourceCodeKind(SourceCodeKind kind)
 {
     return this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id);
 }
Beispiel #56
0
 public abstract string GetDocumentExtension(SourceCodeKind kind);
Beispiel #57
0
 protected async Task VerifyAbsenceAsync(SourceCodeKind kind, string text)
 {
     switch (kind)
     {
         case SourceCodeKind.Regular:
             await VerifyWorkerAsync(text, absent: true);
             break;
         case SourceCodeKind.Script:
             await VerifyWorkerAsync(text, absent: true, options: Options.Script);
             break;
     }
 }
        private void VerifyTriggerCharactersWorker(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters, SourceCodeKind sourceCodeKind)
        {
            ISignatureHelpProvider signatureHelpProvider = CreateSignatureHelpProvider();

            foreach (var expectedTriggerCharacter in expectedTriggerCharacters)
            {
                Assert.True(signatureHelpProvider.IsTriggerCharacter(expectedTriggerCharacter), "Expected '" + expectedTriggerCharacter + "' to be a trigger character");
            }

            foreach (var unexpectedTriggerCharacter in unexpectedTriggerCharacters)
            {
                Assert.False(signatureHelpProvider.IsTriggerCharacter(unexpectedTriggerCharacter), "Expected '" + unexpectedTriggerCharacter + "' to NOT be a trigger character");
            }
        }
Beispiel #59
0
        protected void AddFile(
            string filename,
            SourceCodeKind sourceCodeKind,
            Func<IVisualStudioHostDocument, bool> getIsCurrentContext,
            Func<uint, IReadOnlyList<string>> getFolderNames)
        {
            AssertIsForeground();

            // We can currently be on a background thread.
            // So, hookup the handlers when creating the standard text document, as we might receive these handler notifications on the UI thread.
            var document = this.DocumentProvider.TryGetDocumentForFile(
                this,
                filePath: filename,
                sourceCodeKind: sourceCodeKind,
                getFolderNames: getFolderNames,
                canUseTextBuffer: CanUseTextBuffer,
                updatedOnDiskHandler: s_documentUpdatedOnDiskEventHandler,
                openedHandler: s_documentOpenedEventHandler,
                closingHandler: s_documentClosingEventHandler);

            if (document == null)
            {
                // It's possible this file is open in some very strange editor. In that case, we'll just ignore it.
                // This might happen if somebody decides to mark a non-source-file as something to compile.

                // TODO: Venus does this for .aspx/.cshtml files which is completely unnecessary for Roslyn. We should remove that code.
                AddUntrackedFile(filename);
                return;
            }

            AddDocument(document, getIsCurrentContext(document), hookupHandlers: false);
        }
        private async Task VerifyCurrentParameterNameWorkerAsync(string markup, string expectedParameterName, SourceCodeKind sourceCodeKind)
        {
            string code;
            int    cursorPosition;

            MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out code, out cursorPosition);

            var document = await workspaceFixture.UpdateDocumentAsync(code, sourceCodeKind);

            var signatureHelpProvider = CreateSignatureHelpProvider();
            var triggerInfo           = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
            var items = signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None).Result;

            Assert.Equal(expectedParameterName, (await GetArgumentStateAsync(cursorPosition, document, signatureHelpProvider, triggerInfo)).ArgumentName);
        }