public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            if (await IsWatchWindowAsync(context).ConfigureAwait(false))
            {
                // Completions are not usable in watch window
                return;
            }

            var syntaxContext = await SyntaxContext.CreateAsync(context.Document, context.Position, context.CancellationToken)
                                .ConfigureAwait(false);

            var applicableTypeProviders = typeCompletionProviders
                                          .Where(p => p.IsApplicable(syntaxContext, Options))
                                          .ToArray();

            if (applicableTypeProviders.Length > 0)
            {
                var typeCompletions = GetAllTypes(syntaxContext, Options)
                                      .SelectMany(type => applicableTypeProviders
                                                  .Select(provider => provider.GetCompletionItemsForType(type, syntaxContext, Options)))
                                      .Where(enumerable => enumerable != null)
                                      .SelectMany(enumerable => enumerable);

                context.AddItems(typeCompletions);
            }

            var simpleCompletions = simpleCompletionProviders
                                    .Where(p => p.IsApplicable(syntaxContext, Options))
                                    .Select(provider => provider.GetCompletionItems(syntaxContext, Options))
                                    .Where(enumerable => enumerable != null)
                                    .SelectMany(enumerable => enumerable);

            context.AddItems(simpleCompletions);
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                var document          = context.Document;
                var position          = context.Position;
                var cancellationToken = context.CancellationToken;

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

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

                var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
                token = token.GetPreviousTokenIfTouchingWord(position);

                if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken))
                {
                    return;
                }
                if (!(token.Parent.Parent is AttributeSyntax attributeSyntax) || !(token.Parent is AttributeArgumentListSyntax attributeArgumentList))
                {
                    return;
                }

                if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token))
                {
                    context.IsExclusive = true;
                }

                // We actually want to collect two sets of named parameters to present the user.  The
                // normal named parameters that come from the attribute constructors.  These will be
                // presented like "goo:".  And also the named parameters that come from the writable
                // fields/properties in the attribute.  These will be presented like "bar =".

                var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position);

                var workspace     = document.Project.Solution.Workspace;
                var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false);

                var nameColonItems = await GetNameColonItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false);

                var nameEqualsItems = await GetNameEqualsItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false);

                context.AddItems(nameEqualsItems);

                // If we're after a name= parameter, then we only want to show name= parameters.
                // Otherwise, show name: parameters too.
                if (!IsAfterNameEqualsArgument(token))
                {
                    context.AddItems(nameColonItems);
                }
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // nop
            }
        }
Пример #3
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 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"))));
            }
        }
Пример #5
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var span              = context.DefaultItemSpan;
            var options           = context.Options;
            var cancellationToken = context.CancellationToken;

            // If we were triggered by typing a character, then do a semantic check to make sure
            // we're still applicable.  If not, then return immediately.
            if (context.Trigger.Kind == CompletionTriggerKind.Insertion)
            {
                var isSemanticTriggerCharacter = await IsSemanticTriggerCharacterAsync(document, position - 1, cancellationToken).ConfigureAwait(false);

                if (!isSemanticTriggerCharacter)
                {
                    return;
                }
            }

            context.IsExclusive = IsExclusive();

            using (Logger.LogBlock(FunctionId.Completion_SymbolCompletionProvider_GetItemsWorker, cancellationToken))
            {
                var regularItems = await GetItemsWorkerAsync(document, position, span, options, preselect : false, cancellationToken : cancellationToken).ConfigureAwait(false);

                context.AddItems(regularItems);

                var preselectedItems = await GetItemsWorkerAsync(document, position, span, options, preselect : true, cancellationToken : cancellationToken).ConfigureAwait(false);

                context.AddItems(preselectedItems);
            }
        }
Пример #6
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var cancellationToken = context.CancellationToken;

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

            // first try to get the #r string literal token.  If we couldn't, then we're not in a #r
            // reference directive and we immediately bail.
            SyntaxToken stringLiteral;

            if (!TryGetStringLiteralToken(tree, position, out stringLiteral, cancellationToken))
            {
                return;
            }

            var textChangeSpan = GetTextChangeSpan(stringLiteral, position);

            var gacHelper         = new GlobalAssemblyCacheCompletionHelper(textChangeSpan, _rules);
            var referenceResolver = document.Project.CompilationOptions.MetadataReferenceResolver;

            // TODO: https://github.com/dotnet/roslyn/issues/5263
            // Avoid dependency on a specific resolvers.
            // The search paths should be provided by specialized workspaces:
            // - InteractiveWorkspace for interactive window
            // - ScriptWorkspace for loose .csx files (we don't have such workspace today)
            ImmutableArray <string> searchPaths;

            RuntimeMetadataReferenceResolver       rtResolver;
            WorkspaceMetadataFileReferenceResolver workspaceResolver;

            if ((rtResolver = referenceResolver as RuntimeMetadataReferenceResolver) != null)
            {
                searchPaths = rtResolver.PathResolver.SearchPaths;
            }
            else if ((workspaceResolver = referenceResolver as WorkspaceMetadataFileReferenceResolver) != null)
            {
                searchPaths = workspaceResolver.PathResolver.SearchPaths;
            }
            else
            {
                return;
            }

            var fileSystemHelper = new FileSystemCompletionHelper(
                this, textChangeSpan,
                new CurrentWorkingDirectoryDiscoveryService(Directory.GetCurrentDirectory()),
                Microsoft.CodeAnalysis.Glyph.OpenFolder,
                Microsoft.CodeAnalysis.Glyph.Assembly, searchPaths, new[] { ".dll", ".exe" }, path => path.Contains(","), _rules);

            var pathThroughLastSlash = GetPathThroughLastSlash(stringLiteral, position);

            var documentPath = document.Project.IsSubmission ? null : document.FilePath;

            context.AddItems(gacHelper.GetItems(pathThroughLastSlash, documentPath));
            context.AddItems(fileSystemHelper.GetItems(pathThroughLastSlash, documentPath));
        }
Пример #7
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                if (Options == null)
                {
                    // Package not loaded yet (e.g. no solution opened)
                    return;
                }
                if (await IsWatchWindowAsync(context).ConfigureAwait(false))
                {
                    // Completions are not usable in watch window
                    return;
                }

                if (IsRazorView(context))
                {
                    // Completions are not usable in cshtml-Razor Views. Insertion of Namespaces doesn't work there.
                    return;
                }

                var syntaxContext = await SyntaxContext.CreateAsync(context.Document, context.Position, context.CancellationToken)
                                    .ConfigureAwait(false);

                var applicableTypeProviders = typeCompletionProviders
                                              .Where(p => p.IsApplicable(syntaxContext, Options))
                                              .ToArray();
                if (applicableTypeProviders.Length > 0)
                {
                    var typeCompletions = SymbolNavigator.GetAllTypes(syntaxContext, Options)
                                          .SelectMany(type => applicableTypeProviders
                                                      .Select(provider => provider.GetCompletionItemsForType(type, syntaxContext, Options)))
                                          .Where(enumerable => enumerable != null)
                                          .SelectMany(enumerable => enumerable);

                    context.AddItems(typeCompletions);
                }

                var simpleCompletions = simpleCompletionProviders
                                        .Where(p => p.IsApplicable(syntaxContext, Options))
                                        .Select(provider => provider.GetCompletionItems(syntaxContext, Options))
                                        .Where(enumerable => enumerable != null)
                                        .SelectMany(enumerable => enumerable);

                context.AddItems(simpleCompletions);

                // If Completion was triggered by this provider - use suggestion mode
                if (_triggeredByUs && context.SuggestionModeItem == null)
                {
                    context.SuggestionModeItem = CompletionItem.Create("");
                }
            }
            finally
            {
                _triggeredByUs = false;
            }
        }
Пример #8
0
        public override async Task ProvideCompletionsAsync(CompletionContext completionContext)
        {
            try
            {
                var document          = completionContext.Document;
                var position          = completionContext.Position;
                var options           = completionContext.Options;
                var cancellationToken = completionContext.CancellationToken;

                // If we were triggered by typing a character, then do a semantic check to make sure
                // we're still applicable.  If not, then return immediately.
                if (completionContext.Trigger.Kind == CompletionTriggerKind.Insertion)
                {
                    var isSemanticTriggerCharacter = await IsSemanticTriggerCharacterAsync(document, position - 1, cancellationToken).ConfigureAwait(false);

                    if (!isSemanticTriggerCharacter)
                    {
                        return;
                    }
                }

                completionContext.IsExclusive = IsExclusive();

                using (Logger.LogBlock(FunctionId.Completion_SymbolCompletionProvider_GetItemsWorker, cancellationToken))
                    using (var telemetryCounter = new TelemetryCounter(ShouldCollectTelemetryForTargetTypeCompletion && IsTargetTypeCompletionFilterExperimentEnabled(document.Project.Solution.Workspace)))
                    {
                        var syntaxContext = await GetOrCreateContextAsync(document, position, cancellationToken).ConfigureAwait(false);

                        var inferredTypes = new Lazy <ImmutableArray <ITypeSymbol> >(() =>
                        {
                            var typeInferenceService = document.GetLanguageService <ITypeInferenceService>();
                            return(typeInferenceService.InferTypes(syntaxContext.SemanticModel, position, cancellationToken));
                        });

                        var regularItems = await GetItemsWorkerAsync(completionContext, syntaxContext, document, position, inferredTypes, options, preselect : false, telemetryCounter, cancellationToken).ConfigureAwait(false);

                        completionContext.AddItems(regularItems);

                        // We may or may not want to provide preselected items based on context. For example, C# avoids provide providing preselected items when
                        // triggered via text insertion in an argument list.
                        if (await ShouldProvidePreselectedItemsAsync(completionContext, syntaxContext, document, position, inferredTypes, options).ConfigureAwait(false))
                        {
                            var preselectedItems = await GetItemsWorkerAsync(completionContext, syntaxContext, document, position, inferredTypes, options, preselect : true, telemetryCounter, cancellationToken).ConfigureAwait(false);

                            completionContext.AddItems(preselectedItems);
                        }
                    }
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // nop
            }
        }
Пример #9
0
        protected override async Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash)
        {
            if (GacFileResolver.IsAvailable && pathThroughLastSlash.IndexOfAny(s_pathIndicators) < 0)
            {
                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, ImmutableArray.Create(".dll", ".exe"), s_rules);
                context.AddItems(await helper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false));
            }
        }
        protected override async Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash)
        {
            if (GacFileResolver.IsAvailable && pathThroughLastSlash.IndexOfAny(s_pathIndicators) < 0)
            {
                var gacHelper = new GlobalAssemblyCacheCompletionHelper(s_rules);
                context.AddItems(await gacHelper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false));
            }

            if (pathThroughLastSlash.IndexOf(',') < 0)
            {
                var text = await context.Document.GetTextAsync(context.CancellationToken).ConfigureAwait(false);
                var fileSystemHelper = GetFileSystemCompletionHelper(text, context.Document);
                context.AddItems(await fileSystemHelper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false));
            }
        }
Пример #11
0
        public async sealed override Task ProvideCompletionsAsync(CompletionContext completionContext)
        {
            try
            {
                var document          = completionContext.Document;
                var position          = completionContext.Position;
                var cancellationToken = completionContext.CancellationToken;

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

                var node = GetPartialTypeSyntaxNode(tree, position, cancellationToken);

                if (node != null)
                {
                    var semanticModel = await document.GetSemanticModelForNodeAsync(node, cancellationToken).ConfigureAwait(false);

                    var syntaxContext = await CreateSyntaxContextAsync(document, semanticModel, position, cancellationToken).ConfigureAwait(false);

                    if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is INamedTypeSymbol declaredSymbol)
                    {
                        var symbols = LookupCandidateSymbols(syntaxContext, declaredSymbol, cancellationToken);
                        var items   = symbols?.Select(s => CreateCompletionItem(s, syntaxContext));

                        if (items != null)
                        {
                            completionContext.AddItems(items);
                        }
                    }
                }
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // nop
            }
        }
Пример #12
0
        public async sealed override Task ProvideCompletionsAsync(CompletionContext completionContext)
        {
            var document          = completionContext.Document;
            var position          = completionContext.Position;
            var cancellationToken = completionContext.CancellationToken;

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

            var node = GetPartialTypeSyntaxNode(tree, position, cancellationToken);

            if (node != null)
            {
                var semanticModel = await document.GetSemanticModelForNodeAsync(node, cancellationToken).ConfigureAwait(false);

                var syntaxContext = await CreateSyntaxContextAsync(document, semanticModel, position, cancellationToken).ConfigureAwait(false);

                var declaredSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken) as INamedTypeSymbol;

                if (declaredSymbol != null)
                {
                    var symbols = LookupCandidateSymbols(syntaxContext, declaredSymbol, cancellationToken);
                    var items   = symbols?.Select(s => CreateCompletionItem(s, syntaxContext));

                    if (items != null)
                    {
                        completionContext.AddItems(items);
                    }
                }
            }
        }
Пример #13
0
        protected async override Task AddCompletionItemsAsync(
            CompletionContext completionContext,
            SyntaxContext syntaxContext,
            HashSet <string> namespaceInScope,
            bool isExpandedCompletion,
            CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync, cancellationToken))
            {
                var syntaxFacts = completionContext.Document.GetRequiredLanguageService <ISyntaxFactsService>();
                if (TryGetReceiverTypeSymbol(syntaxContext, syntaxFacts, cancellationToken, out var receiverTypeSymbol))
                {
                    var items = await ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsAsync(
                        completionContext.Document,
                        completionContext.Position,
                        receiverTypeSymbol,
                        namespaceInScope,
                        forceIndexCreation : isExpandedCompletion,
                        cancellationToken).ConfigureAwait(false);

                    completionContext.AddItems(items.Select(i => Convert(i)));
                }
                else
                {
                    // If we can't get a valid receiver type, then we don't show expander as available.
                    // We need to set this explicitly here because we didn't do the (more expensive) symbol check inside
                    // `ShouldProvideCompletion` method above, which is intended for quick syntax based check.
                    completionContext.ExpandItemsAvailable = false;
                }
            }
        }
        public async sealed override Task ProvideCompletionsAsync(CompletionContext completionContext)
        {
            var document = completionContext.Document;
            var position = completionContext.Position;
            var cancellationToken = completionContext.CancellationToken;

            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var node = GetPartialTypeSyntaxNode(tree, position, cancellationToken);

            if (node != null)
            {
                var semanticModel = await document.GetSemanticModelForNodeAsync(node, cancellationToken).ConfigureAwait(false);
                var syntaxContext = await CreateSyntaxContextAsync(document, semanticModel, position, cancellationToken).ConfigureAwait(false);

                var declaredSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken) as INamedTypeSymbol;

                if (declaredSymbol != null)
                {
                    var symbols = LookupCandidateSymbols(syntaxContext, declaredSymbol, cancellationToken);
                    var items = symbols?.Select(s => CreateCompletionItem(s, syntaxContext));

                    if (items != null)
                    {
                        completionContext.AddItems(items);
                    }
                }
            }
        }
Пример #15
0
        public sealed override async Task ProvideCompletionsAsync(CompletionContext completionContext)
        {
            try
            {
                var document          = completionContext.Document;
                var position          = completionContext.Position;
                var cancellationToken = completionContext.CancellationToken;

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

                var node = GetPartialTypeSyntaxNode(tree, position, cancellationToken);

                if (node != null)
                {
                    var semanticModel = await document.ReuseExistingSpeculativeModelAsync(node, cancellationToken).ConfigureAwait(false);

                    if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is INamedTypeSymbol declaredSymbol)
                    {
                        var syntaxContextService = document.GetRequiredLanguageService <ISyntaxContextService>();
                        var syntaxContext        = (TSyntaxContext)syntaxContextService.CreateContext(document, semanticModel, position, cancellationToken);
                        var symbols = LookupCandidateSymbols(syntaxContext, declaredSymbol, cancellationToken);
                        var items   = symbols?.Select(s => CreateCompletionItem(s, syntaxContext));

                        if (items != null)
                        {
                            completionContext.AddItems(items);
                        }
                    }
                }
            }
            catch (Exception e) when(FatalError.ReportAndCatchUnlessCanceled(e))
            {
                // nop
            }
        }
Пример #16
0
        private Task AddCompletionItems(CompletionContext context)
        {
            if (!_codeDocumentProvider.Value.TryGetFromDocument(context.Document, out var codeDocument))
            {
                // A Razor code document has not yet been associated with the document.
                return(Task.CompletedTask);
            }

            var syntaxTree = codeDocument.GetSyntaxTree();

            if (syntaxTree == null)
            {
                // No syntax tree has been computed for the current document.
                return(Task.CompletedTask);
            }

            if (!AtDirectiveCompletionPoint(syntaxTree, context))
            {
                // Can't have a valid directive at the current location.
                return(Task.CompletedTask);
            }

            var completionItems = GetCompletionItems(syntaxTree);

            context.AddItems(completionItems);

            return(Task.CompletedTask);
        }
Пример #17
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                var document          = context.Document;
                var position          = context.Position;
                var options           = context.Options;
                var cancellationToken = context.CancellationToken;

                var(token, semanticModel, symbols) = await GetSymbolsAsync(document, position, options, cancellationToken).ConfigureAwait(false);

                if (symbols.Length == 0)
                {
                    return;
                }

                context.IsExclusive = true;

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

                var span = GetCompletionItemSpan(text, position);
                var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers, semanticModel.Language);
                var serializedOptions   = ImmutableDictionary <string, string> .Empty.Add(HideAdvancedMembers, hideAdvancedMembers.ToString());

                var items = CreateCompletionItems(document.Project.Solution.Workspace,
                                                  semanticModel, symbols, token, span, position, serializedOptions);

                context.AddItems(items);
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // nop
            }
        }
Пример #18
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var cancellationToken = context.CancellationToken;

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

            DeclarationModifiers modifiers;
            SyntaxToken          token;

            if (!IsPartialMethodCompletionContext(tree, position, cancellationToken, out modifiers, out token))
            {
                return;
            }

            var items = await CreatePartialItemsAsync(
                document, position, context.CompletionListSpan, modifiers, token, cancellationToken).ConfigureAwait(false);

            if (items?.Any() == true)
            {
                context.IsExclusive = true;
                context.AddItems(items);
            }
        }
Пример #19
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                var document          = context.Document;
                var position          = context.Position;
                var options           = context.Options;
                var cancellationToken = context.CancellationToken;

                using (Logger.LogBlock(FunctionId.Completion_SnippetCompletionProvider_GetItemsWorker_CSharp, cancellationToken))
                {
                    // TODO (https://github.com/dotnet/roslyn/issues/5107): Enable in Interactive.
                    var workspace = document.Project.Solution.Workspace;
                    if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument) ||
                        workspace.Kind == WorkspaceKind.Debugger ||
                        workspace.Kind == WorkspaceKind.Interactive)
                    {
                        return;
                    }

                    var snippetCompletionItems = await document.GetUnionItemsFromDocumentAndLinkedDocumentsAsync(
                        UnionCompletionItemComparer.Instance,
                        (d, c) => GetSnippetsForDocumentAsync(d, position, workspace, c),
                        cancellationToken).ConfigureAwait(false);

                    context.AddItems(snippetCompletionItems);
                }
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // nop
            }
        }
Пример #20
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var text = await context.Document.GetTextAsync(context.CancellationToken).ConfigureAwait(false);

            var items = GetItems(text, context.Document, context.Position, context.Trigger, context.CancellationToken);

            context.AddItems(items);
        }
Пример #21
0
        protected override async Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash)
        {
            var text = await context.Document.GetTextAsync(context.CancellationToken).ConfigureAwait(false);

            var helper = GetFileSystemCompletionHelper(text, context.Document);

            context.AddItems(await helper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false));
        }
        protected override async Task AddCompletionItemsAsync(
            CompletionContext completionContext,
            SyntaxContext syntaxContext,
            HashSet <string> namespaceInScope,
            bool isExpandedCompletion,
            CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync, cancellationToken))
            {
                var syntaxFacts = completionContext.Document.GetRequiredLanguageService <ISyntaxFactsService>();
                if (TryGetReceiverTypeSymbol(syntaxContext, syntaxFacts, cancellationToken, out var receiverTypeSymbol))
                {
                    using var nestedTokenSource = new CancellationTokenSource();
                    using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken);
                    var inferredTypes = completionContext.CompletionOptions.TargetTypedCompletionFilter
                        ? syntaxContext.InferredTypes
                        : ImmutableArray <ITypeSymbol> .Empty;

                    var getItemsTask = Task.Run(() => ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsAsync(
                                                    completionContext.Document,
                                                    completionContext.Position,
                                                    receiverTypeSymbol,
                                                    namespaceInScope,
                                                    inferredTypes,
                                                    forceIndexCreation: isExpandedCompletion,
                                                    hideAdvancedMembers: completionContext.CompletionOptions.HideAdvancedMembers,
                                                    linkedTokenSource.Token));

                    var timeoutInMilliseconds = completionContext.CompletionOptions.TimeoutInMillisecondsForExtensionMethodImportCompletion;

                    // Timebox is enabled if timeout value is >= 0 and we are not triggered via expander
                    if (timeoutInMilliseconds >= 0 && !isExpandedCompletion)
                    {
                        // timeout == 0 means immediate timeout (for testing purpose)
                        if (timeoutInMilliseconds == 0 || await Task.WhenAny(getItemsTask, Task.Delay(timeoutInMilliseconds, linkedTokenSource.Token)).ConfigureAwait(false) != getItemsTask)
                        {
                            nestedTokenSource.Cancel();
                            CompletionProvidersLogger.LogExtensionMethodCompletionTimeoutCount();
                            return;
                        }
                    }

                    // Either the timebox is not enabled, so we need to wait until the operation for complete,
                    // or there's no timeout, and we now have all completion items ready.
                    var items = await getItemsTask.ConfigureAwait(false);

                    var receiverTypeKey = SymbolKey.CreateString(receiverTypeSymbol, cancellationToken);
                    completionContext.AddItems(items.Select(i => Convert(i, receiverTypeKey)));
                }
                else
                {
                    // If we can't get a valid receiver type, then we don't show expander as available.
                    // We need to set this explicitly here because we didn't do the (more expensive) symbol check inside
                    // `ShouldProvideCompletion` method above, which is intended for quick syntax based check.
                    completionContext.ExpandItemsAvailable = false;
                }
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            if (!context.Document.SupportsSemanticModel)
            {
                return;
            }

            var model = await context.Document.GetSemanticModelAsync();

            var tree = model.SyntaxTree;
            var node = GetCurrentLiteral(tree, context.Position);

            // if in string literal in method arguments
            if (node is LiteralExpressionSyntax && node.IsKind(SyntaxKind.StringLiteralExpression) && node.Parent is ArgumentSyntax && node.Parent.Parent is ArgumentListSyntax)
            {
                var memberReference = (node.Parent.Parent.Parent as InvocationExpressionSyntax)?.Expression as MemberAccessExpressionSyntax;
                if (memberReference != null)
                {
                    // get possible methods
                    var memberSymbol = model.GetSymbolInfo(memberReference);
                    var methodName   = memberSymbol.CandidateSymbols.Concat(new[] { memberSymbol.Symbol }).OfType <IMethodSymbol>().Select(GetFullName).First();                  // it should be single method name, as the symbols are oveloads
                    var typeSymbol   = TryFindResultType(memberReference.Expression, model);
                    if (typeSymbol != null)
                    {
                        if (methodName == typeof(Type).FullName + ".GetMethod")
                        {
                            context.AddItems(GetCompletionItems <IMethodSymbol>(typeSymbol, model, context.Position));
                        }
                        if (methodName == typeof(Type).FullName + ".GetField")
                        {
                            context.AddItems(GetCompletionItems <IFieldSymbol>(typeSymbol, model, context.Position));
                        }
                        if (methodName == typeof(Type).FullName + ".GetProperty")
                        {
                            context.AddItems(GetCompletionItems <IPropertySymbol>(typeSymbol, model, context.Position));
                        }
                        if (methodName == typeof(Type).FullName + ".GetMembers")
                        {
                            context.AddItems(GetCompletionItems <ISymbol>(typeSymbol, model, context.Position));
                        }
                    }
                }
            }
        }
Пример #24
0
        /// <inheritdoc />
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var items = await GetItemsAsync(context.Document, context.Position, context.Trigger,
                                            context.CancellationToken).ConfigureAwait(false);

            if (items != null)
            {
                context.AddItems(items);
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var state = await ItemGetter.CreateAsync(this, context.Document, context.Position, context.CancellationToken).ConfigureAwait(false);
            var items = await state.GetItemsAsync().ConfigureAwait(false);

            if (items?.Any() == true)
            {
                context.IsExclusive = true;
                context.AddItems(items);
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var state = await ItemGetter.CreateAsync(this, context.Document, context.Position, context.CancellationToken).ConfigureAwait(false);

            var items = await state.GetItemsAsync().ConfigureAwait(false);

            if (items?.Any() == true)
            {
                context.IsExclusive = true;
                context.AddItems(items);
            }
        }
        protected override async Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash)
        {
            var extension = Path.GetExtension(context.Document.FilePath);

            if (extension == null)
            {
                return;
            }

            var helper = GetFileSystemCompletionHelper(context.Document, Microsoft.CodeAnalysis.Glyph.CSharpFile, ImmutableArray.Create(extension), s_rules);

            context.AddItems(await helper.GetItemsAsync(pathThroughLastSlash, context.CancellationToken).ConfigureAwait(false));
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            if (!context.Options.GetOption(CompletionControllerOptions.ShowXmlDocCommentCompletion))
            {
                return;
            }

            var items = await GetItemsWorkerAsync(context.Document, context.Position, context.DefaultItemSpan, context.Trigger, context.CancellationToken).ConfigureAwait(false);

            if (items != null)
            {
                context.AddItems(items);
            }
        }
Пример #29
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var options           = context.Options;
            var cancellationToken = context.CancellationToken;

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

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

            var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true)
                        .GetPreviousTokenIfTouchingWord(position);

            // To get a Speculative SemanticModel (which is much faster), we need to
            // walk up to the node the DocumentationTrivia is attached to.
            var parentNode = token.Parent.FirstAncestorOrSelf <DocumentationCommentTriviaSyntax>()?.ParentTrivia.Token.Parent;

            _testSpeculativeNodeCallbackOpt?.Invoke(parentNode);
            if (parentNode == null)
            {
                return;
            }

            var semanticModel = await document.GetSemanticModelForNodeAsync(
                parentNode, cancellationToken).ConfigureAwait(false);

            var symbols = GetSymbols(token, semanticModel, cancellationToken);

            symbols = symbols.FilterToVisibleAndBrowsableSymbols(options.GetOption(CompletionOptions.HideAdvancedMembers, semanticModel.Language), semanticModel.Compilation);

            if (!symbols.Any())
            {
                return;
            }

            context.IsExclusive = true;

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

            var span = GetCompletionItemSpan(text, position);

            var items = CreateCompletionItems(document.Project.Solution.Workspace, semanticModel, symbols, token, span);

            context.AddItems(items);
        }
Пример #30
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                var document          = context.Document;
                var position          = context.Position;
                var cancellationToken = context.CancellationToken;

                var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

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

                var token = syntaxTree
                            .FindTokenOnLeftOfPosition(position, cancellationToken)
                            .GetPreviousTokenIfTouchingWord(position);

                if (!token.IsKind(SyntaxKind.OpenBracketToken, SyntaxKind.CommaToken))
                {
                    return;
                }

                if (token.Parent is not FunctionPointerUnmanagedCallingConventionListSyntax callingConventionList)
                {
                    return;
                }

                var contextPosition = token.SpanStart;
                var semanticModel   = await document.ReuseExistingSpeculativeModelAsync(callingConventionList, cancellationToken).ConfigureAwait(false);

                var completionItems = new HashSet <CompletionItem>(CompletionItemComparer.Instance);
                AddTypes(completionItems, contextPosition, semanticModel, cancellationToken);

                // Even if we didn't have types, there are four magic calling conventions recognized regardless.
                // We add these after doing the type lookup so if we had types we can show that instead
                foreach (var callingConvention in s_predefinedCallingConventions)
                {
                    completionItems.Add(CompletionItem.Create(callingConvention, tags: GlyphTags.GetTags(Glyph.Keyword)));
                }

                context.AddItems(completionItems);
            }
            catch (Exception e) when(FatalError.ReportWithoutCrashUnlessCanceled(e))
            {
                // nop
            }
        }
Пример #31
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            try
            {
                if (Options == null)
                {
                    // Package not loaded yet (e.g. no solution opened)
                    return;
                }
                if (await IsWatchWindowAsync(context).ConfigureAwait(false))
                {
                    // Completions are not usable in watch window
                    return;
                }

                if (IsRazorView(context))
                {
                    // Completions are not usable in cshtml-Razor Views. Insertion of Namespaces doesn't work there.
                    return;
                }

                var syntaxContext = await SyntaxContext.CreateAsync(context.Document, context.Position, context.CancellationToken)
                                    .ConfigureAwait(false);

                if (syntaxContext == null)
                {
                    return;
                }

                var completionsTasks = completionProviders
                                       .Where(p => p.IsApplicable(syntaxContext, Options))
                                       .Select(provider => provider.GetCompletionItemsAsync(syntaxContext, Options));

                var completions = (await Task.WhenAll(completionsTasks).ConfigureAwait(false)).SelectMany(i => i);

                context.AddItems(completions);

                // If Completion was triggered by this provider - use suggestion mode
                if (_triggeredByUs && context.SuggestionModeItem == null)
                {
                    context.SuggestionModeItem = CompletionItem.Create("");
                }
            }
            finally
            {
                _triggeredByUs = false;
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            if (Options.EnableUnimportedSuggestions)
            {
                _symbolMapping = new Dictionary <string, ISymbol>();
                var syntaxContext = await SyntaxContext.Create(context.Document, context.Position, context.CancellationToken)
                                    .ConfigureAwait(false);

                var symbols = GetSymbols(syntaxContext);
                var completionItemsToAdd = symbols
                                           .Select(symbol => CreateCompletionItemForSymbol(symbol, syntaxContext))
                                           .ToList();

                context.AddItems(completionItemsToAdd);
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document = context.Document;
            var position = context.Position;
            var cancellationToken = context.CancellationToken;

            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            if (!IsPartialMethodCompletionContext(tree, position, cancellationToken, out var modifiers, out var token))
            {
                return;
            }

            var items = await CreatePartialItemsAsync(
                document, position, context.CompletionListSpan, modifiers, token, cancellationToken).ConfigureAwait(false);

            if (items?.Any() == true)
            {
                context.IsExclusive = true;
                context.AddItems(items);
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document = context.Document;
            var position = context.Position;
            var options = context.Options;
            var cancellationToken = context.CancellationToken;

            // If we were triggered by typing a character, then do a semantic check to make sure
            // we're still applicable.  If not, then return immediately.
            if (context.Trigger.Kind == CompletionTriggerKind.Insertion)
            {
                var isSemanticTriggerCharacter = await IsSemanticTriggerCharacterAsync(document, position - 1, cancellationToken).ConfigureAwait(false);
                if (!isSemanticTriggerCharacter)
                {
                    return;
                }
            }

            context.IsExclusive = IsExclusive();

            using (Logger.LogBlock(FunctionId.Completion_SymbolCompletionProvider_GetItemsWorker, cancellationToken))
            {
                var regularItems = await GetItemsWorkerAsync(document, position, options, preselect: false, cancellationToken: cancellationToken).ConfigureAwait(false);
                context.AddItems(regularItems);

                var preselectedItems = await GetItemsWorkerAsync(document, position, options, preselect: true, cancellationToken: cancellationToken).ConfigureAwait(false);
                context.AddItems(preselectedItems);
            }
        }
Пример #35
0
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            if (!context.Options.GetOption(CompletionControllerOptions.ShowXmlDocCommentCompletion))
            {
                return;
            }

            var items = await GetItemsWorkerAsync(context.Document, context.Position, context.DefaultItemSpan, context.Trigger, context.CancellationToken).ConfigureAwait(false);
            if (items != null)
            {
                context.AddItems(items);
            }
        }