void Analyze(Microsoft.CodeAnalysis.Completion.CompletionContext context, SemanticModel model, SyntaxNode node, ITypeSymbol type, ITypeSymbol stopAt, ISymbol within, HashSet <string> addedSymbols, CancellationToken cancellationToken)
        {
            var startType  = type;
            var typeString = CSharpAmbience.SafeMinimalDisplayString(type, model, context.CompletionListSpan.Start, Ambience.LabelFormat);
            var pDict      = ImmutableDictionary <string, string> .Empty;

            if (typeString != null)
            {
                pDict = pDict.Add("CastTypeString", typeString);
            }
            pDict = pDict.Add("DescriptionMarkup", "- <span foreground=\"darkgray\" size='small'>" + GettextCatalog.GetString("Cast to '{0}'", type.Name) + "</span>");

            pDict = pDict.Add("NodeString", node.ToString());

            while (type != null && type.SpecialType != SpecialType.System_Object && type != stopAt)
            {
                foreach (var member in type.GetMembers())
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (member.IsImplicitlyDeclared || member.IsStatic)
                    {
                        continue;
                    }
                    if (member.IsOrdinaryMethod() || member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property)
                    {
                        if (member.IsAccessibleWithin(within))
                        {
                            var completionData = SymbolCompletionItem.CreateWithSymbolId(
                                member.Name,
                                new [] { member },
                                CompletionItemRules.Default,
                                context.Position,
                                properties: pDict
                                );

                            if (addedSymbols.Contains(completionData.DisplayText))
                            {
                                continue;
                            }
                            addedSymbols.Add(completionData.DisplayText);
                            context.AddItem(completionData);
                        }
                    }
                }
                type = type.BaseType;
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            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, glyph: Glyph.TypeParameter));
            }
        }
        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 (tree.IsInNonUserCode(position, cancellationToken))
            {
                return;
            }

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

            if (targetToken.IsKind(SyntaxKind.AliasKeyword) && targetToken.Parent.IsKind(SyntaxKind.ExternAliasDirective))
            {
                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, glyph: Glyph.Namespace));
                    }
                }
            }
        }
        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:
            Workspace ws;
            SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
            if (Workspace.TryGetWorkspace(sourceText.Container, out ws))
            {
                var workspace = ws as InteractiveWorkspace;
                if (workspace != null)
                {
                    var window = workspace.Window;
                    var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                    if (await ShouldDisplayCommandCompletionsAsync(tree, position, cancellationToken).ConfigureAwait(false))
                    {
                        IInteractiveWindowCommands commands = window.GetInteractiveCommands();
                        if (commands != null)
                        {
                            foreach (var command in commands.GetCommands())
                            {
                                foreach (var commandName in command.Names)
                                {
                                    string completion = GetCompletionString(commandName);
                                    context.AddItem(CommonCompletionItem.Create(
                                        completion, description: command.Description.ToSymbolDisplayParts(), glyph: Glyph.Intrinsic));
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 5
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 tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                if (tree.IsInNonUserCode(position, cancellationToken))
                {
                    return;
                }

                var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
                if (token.IsMandatoryNamedParameterPosition())
                {
                    return;
                }

                var typeInferenceService = document.GetLanguageService<ITypeInferenceService>();
                Contract.ThrowIfNull(typeInferenceService, nameof(typeInferenceService));

                var span = new TextSpan(position, 0);
                var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
                var type = typeInferenceService.InferType(semanticModel, position,
                    objectAsDefault: true,
                    cancellationToken: cancellationToken);

                // If we have a Nullable<T>, unwrap it.
                if (type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
                {
                    type = type.GetTypeArguments().FirstOrDefault();

                    if (type == null)
                    {
                        return;
                    }
                }

                if (type.TypeKind != TypeKind.Enum)
                {
                    type = GetCompletionListType(type, semanticModel.GetEnclosingNamedType(position, cancellationToken), semanticModel.Compilation);
                    if (type == null)
                    {
                        return;
                    }
                }

                if (!type.IsEditorBrowsable(options.GetOption(CompletionOptions.HideAdvancedMembers, semanticModel.Language), semanticModel.Compilation))
                {
                    return;
                }

                // Does type have any aliases?
                ISymbol alias = await type.FindApplicableAlias(position, semanticModel, cancellationToken).ConfigureAwait(false);

                var displayService = document.GetLanguageService<ISymbolDisplayService>();
                var displayText = alias != null
                    ? alias.Name
                    : displayService.ToMinimalDisplayString(semanticModel, position, type);

                var workspace = document.Project.Solution.Workspace;
                var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);

                var item = SymbolCompletionItem.Create(
                    displayText: displayText,
                    insertionText: null,
                    span: context.DefaultItemSpan,
                    symbol: alias ?? type,
                    descriptionPosition: position,
                    matchPriority: MatchPriority.Preselect,
                    rules: s_rules);

                context.AddItem(item);
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
        public override async Task ProvideCompletionsAsync(CompletionContext context)
        {
            var document = context.Document;
            var position = context.Position;
            var options = context.Options;
            var cancellationToken = context.CancellationToken;

            var span = new TextSpan(position, length: 0);
            var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
            var syntaxTree = semanticModel.SyntaxTree;

            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
            var semanticFacts = document.GetLanguageService<ISemanticFactsService>();

            if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) ||
                semanticFacts.IsPreProcessorDirectiveContext(semanticModel, position, cancellationToken))
            {
                return;
            }

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

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

            if (node.Kind() != SyntaxKind.ExplicitInterfaceSpecifier)
            {
                return;
            }

            // Bind the interface name which is to the left of the dot
            var name = ((ExplicitInterfaceSpecifierSyntax)node).Name;

            var symbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol as ITypeSymbol;
            if (symbol?.TypeKind != TypeKind.Interface)
            {
                return;
            }

            var members = semanticModel.LookupSymbols(
                position: name.SpanStart,
                container: symbol)
                    .WhereAsArray(s => !s.IsStatic)
                    .FilterToVisibleAndBrowsableSymbols(options.GetOption(CompletionOptions.HideAdvancedMembers, semanticModel.Language), semanticModel.Compilation);

            // We're going to create a entry for each one, including the signature
            var namePosition = name.SpanStart;

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

            foreach (var member in members)
            {
                var displayText = member.ToMinimalDisplayString(
                    semanticModel, namePosition, s_signatureDisplayFormat);
                var insertionText = displayText;

                var item = SymbolCompletionItem.Create(
                    displayText,
                    insertionText: insertionText,
                    symbol: member,
                    contextPosition: position,
                    rules: CompletionItemRules.Default);
                item = item.AddProperty(InsertionTextOnOpenParen, member.Name);

                context.AddItem(item);
            }
        }
        public override async Task ProvideCompletionsAsync(Microsoft.CodeAnalysis.Completion.CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var cancellationToken = context.CancellationToken;

            var model = await document.GetSemanticModelForSpanAsync(new TextSpan (position, 0), cancellationToken).ConfigureAwait(false);

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

            var tree = ctx.SyntaxTree;

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

            var token = tree.FindTokenOnLeftOfPosition(context.Position, cancellationToken);

            if (token.IsKind(SyntaxKind.DotToken) || token.IsMandatoryNamedParameterPosition())
            {
                return;
            }

            // check if it's the first parameter and set autoselect == false if a parameterless version exists.
            if (token.IsKind(SyntaxKind.OpenParenToken))
            {
                var parent = token.Parent?.Parent;
                if (parent == null)
                {
                    return;
                }
                var symbolInfo = model.GetSymbolInfo(parent);
                foreach (var symbol in new [] { symbolInfo.Symbol }.Concat(symbolInfo.CandidateSymbols))
                {
                    if (symbol != null && symbol.IsKind(SymbolKind.Method))
                    {
                        if (symbol.GetParameters().Length == 0)
                        {
                            // completionResult.AutoSelect = false;
                            break;
                        }
                    }
                }
            }

            foreach (var _type in ctx.InferredTypes)
            {
                var type = _type;
                if (type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
                {
                    type = type.GetTypeArguments().FirstOrDefault();
                    if (type == null)
                    {
                        continue;
                    }
                }

                if (type.TypeKind != TypeKind.Enum)
                {
                    continue;
                }
                if (!type.IsEditorBrowsable())
                {
                    continue;
                }

                // Does type have any aliases?
                ISymbol alias = await type.FindApplicableAlias(context.Position, model, cancellationToken).ConfigureAwait(false);

                if (!IsReachable(model, type, token.Parent))
                {
                    var pDict         = ImmutableDictionary <string, string> .Empty;
                    var displayString = CSharpAmbience.SafeMinimalDisplayString(type, model, context.Position, SymbolDisplayFormat.CSharpErrorMessageFormat);
                    var item          = CompletionItem.Create(displayString, properties: pDict, tags: tags);
                    context.AddItem(item.WithRules(item.Rules.WithMatchPriority(int.MaxValue)));
                }

                foreach (IFieldSymbol field in type.GetMembers().OfType <IFieldSymbol> ())
                {
                    if (field.DeclaredAccessibility == Accessibility.Public && (field.IsConst || field.IsStatic))
                    {
                        var displayString = CSharpAmbience.SafeMinimalDisplayString(alias ?? field.Type, model, context.Position, SymbolDisplayFormat.CSharpErrorMessageFormat) + "." + field.Name;
                        var pDict         = ImmutableDictionary <string, string> .Empty;
                        context.AddItem(CompletionItem.Create(displayString, properties: pDict, tags: tags));
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public override async Task ProvideCompletionsAsync(Microsoft.CodeAnalysis.Completion.CompletionContext context)
        {
            var document          = context.Document;
            var position          = context.Position;
            var cancellationToken = context.CancellationToken;

            var semanticModel = await document.GetSemanticModelForSpanAsync(new TextSpan (position, 0), cancellationToken).ConfigureAwait(false);

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

            if (context.Trigger.Character == '\\')
            {
                if (ctx.TargetToken.Parent != null && ctx.TargetToken.Parent.Parent != null &&
                    ctx.TargetToken.Parent.Parent.IsKind(SyntaxKind.Argument))
                {
                    var argument = ctx.TargetToken.Parent.Parent as ArgumentSyntax;

                    var symbolInfo = semanticModel.GetSymbolInfo(ctx.TargetToken.Parent.Parent.Parent.Parent);
                    if (symbolInfo.Symbol == null)
                    {
                        return;
                    }

                    if (SemanticHighlightingVisitor <string> .IsRegexMatchMethod(symbolInfo))
                    {
                        if (((ArgumentListSyntax)argument.Parent).Arguments [1] != argument)
                        {
                            return;
                        }
                        AddFormatCompletionData(context, argument.Expression.ToString() [0] == '@');
                        return;
                    }
                    if (SemanticHighlightingVisitor <string> .IsRegexConstructor(symbolInfo))
                    {
                        if (((ArgumentListSyntax)argument.Parent).Arguments [0] != argument)
                        {
                            return;
                        }
                        AddFormatCompletionData(context, argument.Expression.ToString() [0] == '@');
                        return;
                    }
                }
            }
            else
            {
                var ma = ctx.TargetToken.Parent as MemberAccessExpressionSyntax;
                if (ma != null)
                {
                    var symbolInfo = semanticModel.GetSymbolInfo(ma.Expression);
                    var typeInfo   = semanticModel.GetTypeInfo(ma.Expression);
                    var type       = typeInfo.Type;
                    if (type != null && type.Name == "Match" && type.ContainingNamespace.GetFullName() == "System.Text.RegularExpressions")
                    {
                        foreach (var grp in GetGroups(ctx, symbolInfo.Symbol))
                        {
                            context.AddItem(FormatItemCompletionProvider.CreateCompletionItem("Groups[\"" + grp + "\"]", null, null));
                        }
                    }
                }
            }
        }