예제 #1
0
        public static CompletionItem Create(
            string displayText,
            string displayTextSuffix,
            CompletionItemRules rules,
            FSharpGlyph?glyph = null,
            ImmutableArray <SymbolDisplayPart> description = default,
            string sortText       = null,
            string filterText     = null,
            bool showsWarningIcon = false,
            ImmutableDictionary <string, string> properties = null,
            ImmutableArray <string> tags = default,
            string inlineDescription     = null
            )
        {
            var roslynGlyph = glyph.HasValue
                ? FSharpGlyphHelpers.ConvertTo(glyph.Value)
                : (Glyph?)null;

            return(CommonCompletionItem.Create(
                       displayText,
                       displayTextSuffix,
                       rules,
                       roslynGlyph,
                       description,
                       sortText,
                       filterText,
                       showsWarningIcon,
                       properties,
                       tags,
                       inlineDescription
                       ));
        }
        // internal for testing
        internal ImmutableArray <CompletionItem> GetItems(string directoryPath, CancellationToken cancellationToken)
        {
            var result = ArrayBuilder <CompletionItem> .GetInstance();

            var comma = directoryPath.IndexOf(',');

            if (comma >= 0)
            {
                var partialName = directoryPath.Substring(0, comma);
                foreach (var identity in GetAssemblyIdentities(partialName))
                {
                    result.Add(CommonCompletionItem.Create(identity.GetDisplayName(), glyph: Glyph.Assembly, rules: _itemRules));
                }
            }
            else
            {
                foreach (var displayName in s_lazyAssemblySimpleNames.Value)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    result.Add(CommonCompletionItem.Create(displayName, glyph: Glyph.Assembly, rules: _itemRules));
                }
            }

            return(result.ToImmutableAndFree());
        }
 private CompletionItem CreateNuGetRoot()
 => CommonCompletionItem.Create(
     displayText: NuGetPrefix,
     displayTextSuffix: "",
     rules: s_rules,
     glyph: Microsoft.CodeAnalysis.Glyph.NuGet,
     sortText: "");
        private async Task AddAssemblyCompletionItemsAsync(CompletionContext context, CancellationToken cancellationToken)
        {
            var currentProject = context.Document.Project;
            var allInternalsVisibleToAttributesOfProject = await GetAllInternalsVisibleToAssemblyNamesOfProjectAsync(context, cancellationToken).ConfigureAwait(false);

            foreach (var project in context.Document.Project.Solution.Projects)
            {
                if (project == currentProject)
                {
                    continue;
                }

                if (allInternalsVisibleToAttributesOfProject.Contains(project.AssemblyName))
                {
                    continue;
                }

                var projectGuid    = project.Id.Id.ToString();
                var completionItem = CommonCompletionItem.Create(
                    displayText: project.AssemblyName,
                    rules: CompletionItemRules.Default,
                    glyph: project.GetGlyph(),
                    properties: ImmutableDictionary.Create <string, string>().Add(ProjectGuidKey, projectGuid));
                context.AddItem(completionItem);
            }
        }
        private async Task ProvideNuGetCompletionsAsync(CompletionContext context, string packageIdAndVersion)
        {
            var(id, version) = ParseNuGetReference(packageIdAndVersion);
            var packages = await Task.Run(() => _nuGetCompletionProvider.SearchPackagesAsync(id, exactMatch: version != null, context.CancellationToken), context.CancellationToken).ConfigureAwait(false);

            if (version != null)
            {
                if (packages.Count > 0)
                {
                    var package  = packages[0];
                    var versions = package.Versions;
                    if (!string.IsNullOrWhiteSpace(version))
                    {
                        versions = versions.Where(v => v.StartsWith(version, StringComparison.InvariantCultureIgnoreCase));
                    }

                    context.AddItems(versions.Select((v, i) =>
                                                     CommonCompletionItem.Create(
                                                         v,
                                                         s_rules,
                                                         Microsoft.CodeAnalysis.Glyph.NuGet,
                                                         sortText: i.ToString("0000"))));
                }
            }
            else
            {
                context.AddItems(packages.Select((p, i) =>
                                                 CommonCompletionItem.Create(
                                                     NuGetPrefix + p.Id + "/",
                                                     s_rules,
                                                     Microsoft.CodeAnalysis.Glyph.NuGet,
                                                     sortText: i.ToString("0000"))));
            }
        }
예제 #6
0
        protected override async Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash)
        {
            var resolver = context.Document.Project.CompilationOptions.MetadataReferenceResolver as RuntimeMetadataReferenceResolver;

            if (resolver != null && pathThroughLastSlash.IndexOfAny(s_pathIndicators) < 0)
            {
                foreach (var(name, path) in resolver.TrustedPlatformAssemblies)
                {
                    context.AddItem(CommonCompletionItem.Create(name, displayTextSuffix: "", glyph: Glyph.Assembly, rules: s_rules));
                    context.AddItem(CommonCompletionItem.Create(PathUtilities.GetFileName(path, includeExtension: true), displayTextSuffix: "", glyph: Glyph.Assembly, rules: s_rules));
                }

                if (resolver.GacFileResolver is object)
                {
                    var gacHelper = new GlobalAssemblyCacheCompletionHelper(s_rules);
                    context.AddItems(await gacHelper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false));
                }
            }

            if (pathThroughLastSlash.IndexOf(',') < 0)
            {
                var helper = GetFileSystemCompletionHelper(context.Document, Glyph.Assembly, RuntimeMetadataReferenceResolver.AssemblyExtensions, s_rules);
                context.AddItems(await helper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false));
            }
        }
        private static CompletionItem CreateSymbolCompletion(Symbol symbol, SymbolMarkupToken nameSuffix = null)
        {
            var displayText = symbol.Name;

            var description = symbol.ToMarkup();

            var descriptionTokens = description.Tokens;

            if (nameSuffix != null)
            {
                descriptionTokens = descriptionTokens.Add(nameSuffix);
            }

            if (!string.IsNullOrEmpty(symbol.Documentation))
            {
                descriptionTokens = descriptionTokens.Add(new SymbolMarkupToken(SymbolMarkupKind.Whitespace, "\n"));
                descriptionTokens = descriptionTokens.Add(new SymbolMarkupToken(SymbolMarkupKind.PlainText, symbol.Documentation));
            }

            var glyph = symbol.GetGlyph();

            return(CommonCompletionItem.Create(
                       displayText,
                       CompletionItemRules.Default,
                       glyph,
                       descriptionTokens));
        }
예제 #8
0
        private async Task <IEnumerable <CompletionItem> > GetSnippetCompletionItemsAsync(
            Workspace workspace, SemanticModel semanticModel, bool isPreProcessorContext, bool isTupleContext, CancellationToken cancellationToken)
        {
            var service = _snippetInfoService ?? workspace.Services.GetLanguageServices(semanticModel.Language).GetService <ISnippetInfoService>();

            if (service == null)
            {
                return(SpecializedCollections.EmptyEnumerable <CompletionItem>());
            }

            var snippets = service.GetSnippetsIfAvailable();

            if (isPreProcessorContext)
            {
                snippets = snippets.Where(snippet => snippet.Shortcut != null && snippet.Shortcut.StartsWith("#", StringComparison.Ordinal));
            }
            var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);

            return(snippets.Select(snippet =>
            {
                var rules = isTupleContext ? s_tupleRules : CompletionItemRules.Default;
                rules = rules.WithFormatOnCommit(service.ShouldFormatSnippet(snippet));

                return CommonCompletionItem.Create(
                    displayText: isPreProcessorContext?snippet.Shortcut.Substring(1) : snippet.Shortcut,
                        displayTextSuffix: "",
                        sortText: isPreProcessorContext ? snippet.Shortcut.Substring(1) : snippet.Shortcut,
                        description: (snippet.Title + Environment.NewLine + snippet.Description).ToSymbolDisplayParts(),
                        glyph: Glyph.Snippet,
                        rules: rules);
            }).ToImmutableArray());
        }
예제 #9
0
 public static CompletionItem CreateCommonCompletionItem(
     string displayText,
     string displayTextSuffix,
     CompletionItemRules rules,
     PythiaGlyph?glyph,
     ImmutableArray <SymbolDisplayPart> description,
     string sortText,
     string filterText,
     bool showsWarningIcon = false,
     ImmutableDictionary <string, string>?properties = null,
     ImmutableArray <string> tags = default,
     string?inlineDescription     = null
     ) =>
 CommonCompletionItem.Create(
     displayText,
     displayTextSuffix,
     rules,
     (Glyph?)glyph,
     description,
     sortText,
     filterText,
     showsWarningIcon,
     properties,
     tags,
     inlineDescription
     );
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var originatingDocument = context.Document;

            if (originatingDocument.SourceCodeKind != SourceCodeKind.Regular)
            {
                return;
            }

            var cancellationToken = context.CancellationToken;
            var position          = context.Position;
            var semanticModel     = await originatingDocument.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);

            var service       = originatingDocument.GetRequiredLanguageService <ISyntaxContextService>();
            var solution      = originatingDocument.Project.Solution;
            var syntaxContext = service.CreateContext(solution.Workspace, semanticModel, position, cancellationToken);

            if (!syntaxContext.IsPreProcessorExpressionContext)
            {
                return;
            }

            foreach (var name in s_directivesName)
            {
                context.AddItem(CommonCompletionItem.Create(
                                    name,
                                    displayTextSuffix: "",
                                    CompletionItemRules.Default,
                                    glyph: Microsoft.CodeAnalysis.Glyph.Keyword,
                                    sortText: "_0_" + name));
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var cancellationToken = context.CancellationToken;

            // the provider might be invoked in non-interactive context:
            var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            if (Workspace.TryGetWorkspace(sourceText.Container, out var ws))
            {
                if (ws is InteractiveWorkspace workspace)
                {
                    var window = workspace.Window;
                    var tree   = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                    if (await ShouldDisplayCommandCompletionsAsync(tree, position, cancellationToken).ConfigureAwait(false))
                    {
                        var commands = window.GetInteractiveCommands();
                        if (commands != null)
                        {
                            foreach (var command in commands.GetCommands())
                            {
                                foreach (var commandName in command.Names)
                                {
                                    var completion = GetCompletionString(commandName);
                                    context.AddItem(CommonCompletionItem.Create(
                                                        completion, displayTextSuffix: "", CompletionItemRules.Default, description: command.Description.ToSymbolDisplayParts(), glyph: Glyph.Intrinsic));
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #12
0
        private async Task <IEnumerable <CompletionItem> > GetSnippetCompletionItemsAsync(Workspace workspace, SemanticModel semanticModel, int position, TextSpan itemSpan, bool isPreProcessorContext, CancellationToken cancellationToken)
        {
            var service = _snippetInfoService ?? workspace.Services.GetLanguageServices(semanticModel.Language).GetService <ISnippetInfoService>();

            if (service == null)
            {
                return(SpecializedCollections.EmptyEnumerable <CompletionItem>());
            }

            var snippets = service.GetSnippetsIfAvailable();

            if (isPreProcessorContext)
            {
                snippets = snippets.Where(snippet => snippet.Shortcut.StartsWith("#", StringComparison.Ordinal));
            }

            var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);

            return(snippets.Select(snippet => CommonCompletionItem.Create(
                                       displayText: isPreProcessorContext?snippet.Shortcut.Substring(1) : snippet.Shortcut,
                                           sortText: isPreProcessorContext ? snippet.Shortcut.Substring(1) : snippet.Shortcut,
                                           description: (snippet.Title + Environment.NewLine + snippet.Description).ToSymbolDisplayParts(),
                                           span: itemSpan,
                                           glyph: Glyph.Snippet,
                                           shouldFormatOnCommit: service.ShouldFormatSnippet(snippet))).ToList());
        }
예제 #13
0
 protected CompletionItem CreateSuggestionModeItem(string displayText, string description)
 {
     return(CommonCompletionItem.Create(
                displayText: displayText ?? string.Empty,
                description: description != null ? description.ToSymbolDisplayParts() : default(ImmutableArray <SymbolDisplayPart>),
                rules: s_rules));
 }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                var document          = context.Document;
                var position          = context.Position;
                var cancellationToken = context.CancellationToken;

                var showSpeculativeT = await document.IsValidContextForDocumentOrLinkedDocumentsAsync(
                    (doc, ct) => ShouldShowSpeculativeTCompletionItemAsync(doc, position, ct),
                    cancellationToken).ConfigureAwait(false);

                if (showSpeculativeT)
                {
                    var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

                    const string T = nameof(T);
                    context.AddItem(CommonCompletionItem.Create(
                                        T, displayTextSuffix: "", CompletionItemRules.Default, glyph: Glyph.TypeParameter));
                }
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // nop
            }
        }
예제 #15
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var cancellationToken = context.CancellationToken;
            var semanticModel     = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);

            var workspace     = document.Project.Solution.Workspace;
            var syntaxContext = CSharpSyntaxContext.CreateContext(workspace, semanticModel, position, cancellationToken);

            if (!syntaxContext.IsAwaitKeywordContext(position))
            {
                return;
            }

            var method = syntaxContext.TargetToken.GetAncestor(node => node.IsAsyncSupportingFunctionSyntax());
            var shouldMakeContainerAsync = method is not null && !method.GetModifiers().Any(SyntaxKind.AsyncKeyword);
            var completionItem           = CommonCompletionItem.Create(
                displayText: SyntaxFacts.GetText(SyntaxKind.AwaitKeyword),
                displayTextSuffix: "",
                rules: CompletionItemRules.Default,
                Glyph.Keyword,
                description: RecommendedKeyword.CreateDisplayParts(SyntaxFacts.GetText(SyntaxKind.AwaitKeyword), string.Empty),
                inlineDescription: shouldMakeContainerAsync ? CSharpFeaturesResources.Make_container_async : null,
                isComplexTextEdit: shouldMakeContainerAsync);

            context.AddItem(completionItem);
        }
예제 #16
0
 private CompletionItem CreateLogicalDriveItem(string drive)
 => CommonCompletionItem.Create(
     drive,
     "",
     glyph: _folderGlyph,
     description: drive.ToSymbolDisplayParts(),
     rules: _itemRules);
예제 #17
0
 private CompletionItem CreateFileSystemEntryItem(string fullPath, bool isDirectory)
 => CommonCompletionItem.Create(
     PathUtilities.GetFileName(fullPath),
     "",
     glyph: isDirectory ? _folderGlyph : _fileGlyph,
     description: fullPath.ToSymbolDisplayParts(),
     rules: _itemRules);
예제 #18
0
 private CompletionItem CreateUnixRoot()
 => CommonCompletionItem.Create(
     "/",
     "",
     glyph: _folderGlyph,
     description: "/".ToSymbolDisplayParts(),
     rules: _itemRules);
예제 #19
0
 private CompletionItem CreateNetworkRoot()
 => CommonCompletionItem.Create(
     "\\\\",
     "",
     glyph: null,
     description: "\\\\".ToSymbolDisplayParts(),
     rules: _itemRules);
예제 #20
0
 private CompletionItem CreateCompletion(FileSystemInfo child)
 {
     return(CommonCompletionItem.Create(
                child.Name,
                glyph: child is DirectoryInfo ? _folderGlyph : _fileGlyph,
                description: child.FullName.ToSymbolDisplayParts(),
                rules: _itemRules));
 }
예제 #21
0
 private IEnumerable <CompletionItem> GetLogicalDrives()
 {
     // First, we may have a filename, so let's include all drives
     return(from d in _lazyGetDrives.Value
            where d.Length > 0 && (d.Last() == Path.DirectorySeparatorChar || d.Last() == Path.AltDirectorySeparatorChar)
            let text = d.Substring(0, d.Length - 1)
                       select CommonCompletionItem.Create(text, glyph : _folderGlyph, rules : _itemRules));
 }
예제 #22
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                var document          = context.Document;
                var position          = context.Position;
                var cancellationToken = context.CancellationToken;

                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                if (tree.IsInNonUserCode(position, cancellationToken))
                {
                    return;
                }

                var targetToken = tree
                                  .FindTokenOnLeftOfPosition(position, cancellationToken)
                                  .GetPreviousTokenIfTouchingWord(position);

                if (!targetToken.IsKind(SyntaxKind.AliasKeyword) &&
                    !(targetToken.IsKind(SyntaxKind.IdentifierToken) && targetToken.HasMatchingText(SyntaxKind.AliasKeyword)))
                {
                    return;
                }

                if (targetToken.Parent.IsKind(SyntaxKind.ExternAliasDirective) ||
                    (targetToken.Parent.IsKind(SyntaxKind.IdentifierName) && targetToken.Parent.IsParentKind(SyntaxKind.IncompleteMember)))
                {
                    var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                    var aliases = compilation.ExternalReferences.SelectMany(r => r.Properties.Aliases).ToSet();

                    if (aliases.Any())
                    {
                        var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);

                        var usedAliases = root.ChildNodes().OfType <ExternAliasDirectiveSyntax>()
                                          .Where(e => !e.Identifier.IsMissing)
                                          .Select(e => e.Identifier.ValueText);

                        aliases.RemoveRange(usedAliases);
                        aliases.Remove(MetadataReferenceProperties.GlobalAlias);

                        var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

                        foreach (var alias in aliases)
                        {
                            context.AddItem(CommonCompletionItem.Create(
                                                alias, displayTextSuffix: "", CompletionItemRules.Default, glyph: Glyph.Namespace));
                        }
                    }
                }
            }
            catch (Exception e) when(FatalError.ReportAndCatchUnlessCanceled(e))
            {
                // nop
            }
        }
예제 #23
0
 protected override CompletionItem CreateItem(RecommendedKeyword keyword, TextSpan span)
 {
     return(CommonCompletionItem.Create(
                displayText: keyword.Keyword,
                span: span,
                description: keyword.DescriptionFactory(CancellationToken.None),
                glyph: Glyph.Keyword,
                shouldFormatOnCommit: keyword.ShouldFormatOnCommit));
 }
 CompletionItem CreateCompletionItem(string name, Glyph glyph, string sortText)
 {
     return(CommonCompletionItem.Create(
                name,
                CompletionItemRules.Default,
                glyph: glyph,
                sortText: sortText,
                description: CSharpFeaturesResources.Suggested_name.ToSymbolDisplayParts()));
 }
예제 #25
0
 protected virtual CompletionItem CreateItem(RecommendedKeyword keyword, TContext context)
 {
     return(CommonCompletionItem.Create(
                displayText: keyword.Keyword,
                rules: s_keywordRules.WithMatchPriority(keyword.MatchPriority),
                description: keyword.DescriptionFactory(CancellationToken.None),
                glyph: Glyph.Keyword,
                tags: s_Tags));
 }
예제 #26
0
 protected virtual CompletionItem CreateItem(RecommendedKeyword keyword)
 {
     return(CommonCompletionItem.Create(
                displayText: keyword.Keyword,
                description: keyword.DescriptionFactory(CancellationToken.None),
                glyph: Glyph.Keyword,
                tags: s_Tags,
                matchPriority: keyword.MatchPriority));
 }
예제 #27
0
 protected virtual CompletionItem CreateItem(RecommendedKeyword keyword, TextSpan span)
 {
     return(CommonCompletionItem.Create(
                displayText: keyword.Keyword,
                span: span,
                description: keyword.DescriptionFactory(CancellationToken.None),
                glyph: Glyph.Keyword,
                tags: s_Tags,
                preselect: keyword.ShouldPreselect));
 }
예제 #28
0
        public sealed override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var cancellationToken   = context.CancellationToken;
            var originatingDocument = context.Document;
            var position            = context.Position;

            var semanticModel = await originatingDocument
                                .ReuseExistingSpeculativeModelAsync(position, cancellationToken)
                                .ConfigureAwait(false);

            var service       = originatingDocument.GetRequiredLanguageService <ISyntaxContextService>();
            var solution      = originatingDocument.Project.Solution;
            var syntaxContext = service.CreateContext(
                solution.Workspace,
                semanticModel,
                position,
                cancellationToken
                );

            if (!syntaxContext.IsPreProcessorExpressionContext)
            {
                return;
            }

            // Walk all the projects this document is linked in so that we get the full set of preprocessor symbols
            // defined across all of them.
            var syntaxFacts       = originatingDocument.GetRequiredLanguageService <ISyntaxFactsService>();
            var preprocessorNames = new HashSet <string>(syntaxFacts.StringComparer);

            foreach (var documentId in solution.GetRelatedDocumentIds(originatingDocument.Id))
            {
                var document          = solution.GetRequiredDocument(documentId);
                var currentSyntaxTree = await document
                                        .GetRequiredSyntaxTreeAsync(cancellationToken)
                                        .ConfigureAwait(false);

                preprocessorNames.AddRange(currentSyntaxTree.Options.PreprocessorSymbolNames);
            }

            // Keep all the preprocessor symbol names together.  We don't want to intermingle them with any keywords we
            // include (like `true/false`)
            foreach (var name in preprocessorNames.OrderBy(a => a))
            {
                context.AddItem(
                    CommonCompletionItem.Create(
                        name,
                        displayTextSuffix: "",
                        CompletionItemRules.Default,
                        glyph: Glyph.Keyword,
                        sortText: "_0_" + name
                        )
                    );
            }
        }
        public void FullReferenceIdentityDescription()
        {
            var code        = "System";
            var completions = GetItems(code);
            var systemsColl = from completion in completions
                              where completion.DisplayText == "System"
                              select completion;

            Assert.True(systemsColl.Any(
                            completion => CommonCompletionItem.GetDescription(completion).Text == typeof(System.Diagnostics.Process).Assembly.FullName));
        }
예제 #30
0
        protected override CompletionItem CreateItem(RecommendedKeyword keyword, CSharpSyntaxContext context)
        {
            var rules = context.IsPossibleTupleContext ? s_tupleRules : CompletionItemRules.Default;

            return(CommonCompletionItem.Create(
                       displayText: keyword.Keyword,
                       description: keyword.DescriptionFactory(CancellationToken.None),
                       glyph: Glyph.Keyword,
                       rules: rules.WithMatchPriority(keyword.MatchPriority)
                       .WithFormatOnCommit(keyword.ShouldFormatOnCommit)));
        }