protected async override Task <IEnumerable <CompletionData> > GetItemsWorkerAsync(CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken)
        {
            var model = ctx.SemanticModel;
            var tree  = ctx.SyntaxTree;

            if (tree.IsInNonUserCode(completionContext.Position, cancellationToken))
            {
                return(Enumerable.Empty <CompletionData> ());
            }

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

            if (token.IsMandatoryNamedParameterPosition())
            {
                return(Enumerable.Empty <CompletionData> ());
            }
            var result = new List <CompletionData> ();

            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(completionContext.Position, model, cancellationToken).ConfigureAwait(false);

                if (string.IsNullOrEmpty(completionResult.DefaultCompletionString))
                {
                    completionResult.DefaultCompletionString = type.Name;
                }

                result.Add(engine.Factory.CreateSymbolCompletionData(this, type, RoslynCompletionData.SafeMinimalDisplayString(type, model, completionContext.Position, SymbolDisplayFormat.CSharpErrorMessageFormat)));
                foreach (IFieldSymbol field in type.GetMembers().OfType <IFieldSymbol>())
                {
                    if (field.DeclaredAccessibility == Accessibility.Public && (field.IsConst || field.IsStatic))
                    {
                        result.Add(engine.Factory.CreateEnumMemberCompletionData(this, alias, field));
                    }
                }
            }
            return(result);
        }
        //
        //		void AppendBraceStart (StringBuilder result, BraceStyle braceStyle)
        //		{
        //			switch (braceStyle) {
        //			case BraceStyle.BannerStyle:
        //			case BraceStyle.EndOfLine:
        //				result.Append (" {");
        //				AppendLine (result);
        //				break;
        //			case BraceStyle.EndOfLineWithoutSpace:
        //				result.Append ("{");
        //				AppendLine (result);
        //				break;
        //			case BraceStyle.NextLine:
        //				AppendLine (result);
        //				AppendIndent (result);
        //				result.Append ("{");
        //				AppendLine (result);
        //				break;
        //			case BraceStyle.NextLineShifted:
        //				AppendLine (result);
        //				result.Append (GetIndent (IndentLevel + 1));
        //				result.Append ("{");
        //				AppendLine (result);
        //				break;
        //			case BraceStyle.NextLineShifted2:
        //				AppendLine (result);
        //				result.Append (GetIndent (IndentLevel + 1));
        //				result.Append ("{");
        //				AppendLine (result);
        //				IndentLevel++;
        //				break;
        //			default:
        //				goto case BraceStyle.NextLine;
        //			}
        //			IndentLevel++;
        //		}
        //
        //		void AppendBraceEnd (StringBuilder result, BraceStyle braceStyle)
        //		{
        //			switch (braceStyle) {
        //			case BraceStyle.EndOfLineWithoutSpace:
        //			case BraceStyle.NextLine:
        //			case BraceStyle.EndOfLine:
        //				IndentLevel --;
        //				AppendIndent (result);
        //				result.Append ("}");
        //				break;
        //			case BraceStyle.BannerStyle:
        //			case BraceStyle.NextLineShifted:
        //				AppendIndent (result);
        //				result.Append ("}");
        //				IndentLevel--;
        //				break;
        //			case BraceStyle.NextLineShifted2:
        //				IndentLevel--;
        //				AppendIndent (result);
        //				result.Append ("}");
        //				IndentLevel--;
        //				break;
        //			default:
        //				goto case BraceStyle.NextLine;
        //			}
        //		}
        //
        //		void AppendIndent (StringBuilder result)
        //		{
        //			result.Append (GetIndent (IndentLevel));
        //		}
        //
        static void AppendReturnType(StringBuilder result, CodeGenerationOptions options, ITypeSymbol type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            result.Append(RoslynCompletionData.SafeMinimalDisplayString(type, options.SemanticModel, options.Part.SourceSpan.Start, Ambience.LabelFormat));

            //			var implementingType = options.Part;
            //			var loc = implementingType.Region.End;
            //
            //			var pf = implementingType.UnresolvedFile;
            //			var file = pf as CSharpUnresolvedFile;
            //			var resolved = type;
            //			if (resolved.Kind == TypeKind.Unknown) {
            //				result.Append (type.FullName);
            //				return;
            //			}
            //			var def = type.GetDefinition ();
            //			if (def != null) {
            //				using (var stringWriter = new System.IO.StringWriter ()) {
            //					var formatter = new TextWriterTokenWriter (stringWriter);
            //					stringWriter.NewLine = EolMarker;
            //					var visitor = new CSharpOutputVisitor (formatter, FormattingOptionsFactory.CreateMono ());
            //					var shortType = CreateShortType (def.Compilation, file, loc, resolved);
            //					shortType.AcceptVisitor (visitor);
            //
            //					var typeString = stringWriter.ToString ();
            //					if (typeString.StartsWith ("global::"))
            //						typeString = typeString.Substring ("global::".Length);
            //					result.Append (typeString);
            //				}
            //			} else {
            //				result.Append (new ICSharpCode.NRefactory.CSharp.CSharpAmbience ().ConvertType (type));
            //			}
        }
            public string GetShortType(string ns, string name, int typeArguments = 0)
            {
                if (DocumentContext == null || Editor == null || SemanticModel == null || DocumentContext.ParsedDocument == null)
                {
                    return(ns + "." + name);
                }

                var model = DocumentContext.ParsedDocument.GetAst <SemanticModel>();

                if (model == null)
                {
                    return(ns + "." + name);
                }

                var type = model.Compilation.GetTypeByMetadataName(ns + "." + name);

                if (type == null)
                {
                    return(ns + "." + name);
                }


                return(RoslynCompletionData.SafeMinimalDisplayString(type, model, Editor.CaretOffset, Ambience.LabelFormat));
            }
Пример #4
0
        protected async override Task <IEnumerable <CompletionData> > GetItemsWorkerAsync(CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken)
        {
            var model = ctx.SemanticModel;
            var tree  = ctx.SyntaxTree;

            if (tree.IsInNonUserCode(completionContext.Position, cancellationToken))
            {
                return(Enumerable.Empty <CompletionData> ());
            }

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

            if (token.IsKind(SyntaxKind.DotToken) || token.IsMandatoryNamedParameterPosition())
            {
                return(Enumerable.Empty <CompletionData> ());
            }
            var result = new List <CompletionData> ();

            // 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(Enumerable.Empty <CompletionData> ());
                }
                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(completionContext.Position, model, cancellationToken).ConfigureAwait(false);

                var displayString = RoslynCompletionData.SafeMinimalDisplayString(type, model, completionContext.Position, SymbolDisplayFormat.CSharpErrorMessageFormat);
                if (string.IsNullOrEmpty(completionResult.DefaultCompletionString))
                {
                    completionResult.DefaultCompletionString = displayString;
                    completionResult.AutoCompleteEmptyMatch  = true;
                }
                if (!IsReachable(model, type, token.Parent))
                {
                    result.Add(engine.Factory.CreateSymbolCompletionData(this, type, displayString));
                }
                foreach (IFieldSymbol field in type.GetMembers().OfType <IFieldSymbol> ())
                {
                    if (field.DeclaredAccessibility == Accessibility.Public && (field.IsConst || field.IsStatic))
                    {
                        result.Add(engine.Factory.CreateEnumMemberCompletionData(this, alias, field));
                    }
                }
            }
            return(result);
        }
Пример #5
0
        void AddDelegateHandlers(List <CompletionData> completionList, SyntaxNode parent, SemanticModel semanticModel, CompletionEngine engine, CompletionResult result, ITypeSymbol delegateType, int position, string optDelegateName, CancellationToken cancellationToken)
        {
            var delegateMethod = delegateType.GetDelegateInvokeMethod();

            result.PossibleDelegates.Add(delegateMethod);

            var    thisLineIndent = "";
            string EolMarker      = "\n";
            bool   addSemicolon   = true;
            bool   addDefault     = true;

            string delegateEndString = EolMarker + thisLineIndent + "}" + (addSemicolon ? ";" : "");
            //bool containsDelegateData = completionList.Result.Any(d => d.DisplayText.StartsWith("delegate("));
            CompletionData item;

            if (addDefault)
            {
                item = engine.Factory.CreateAnonymousMethod(
                    this,
                    "delegate",
                    "Creates anonymous delegate.",
                    "delegate {" + EolMarker + thisLineIndent,
                    delegateEndString
                    );
                if (!completionList.Any(i => i.DisplayText == item.DisplayText))
                {
                    completionList.Add(item);
                }

                //if (LanguageVersion.Major >= 5)

                item = engine.Factory.CreateAnonymousMethod(
                    this,
                    "async delegate",
                    "Creates anonymous async delegate.",
                    "async delegate {" + EolMarker + thisLineIndent,
                    delegateEndString
                    );
                if (!completionList.Any(i => i.DisplayText == item.DisplayText))
                {
                    completionList.Add(item);
                }
            }

            var sb             = new StringBuilder("(");
            var sbWithoutTypes = new StringBuilder("(");

            for (int k = 0; k < delegateMethod.Parameters.Length; k++)
            {
                if (k > 0)
                {
                    sb.Append(", ");
                    sbWithoutTypes.Append(", ");
                }
                sb.Append(RoslynCompletionData.SafeMinimalDisplayString(delegateMethod.Parameters [k], semanticModel, position, overrideNameFormat));
                sbWithoutTypes.Append(delegateMethod.Parameters [k].Name);
            }

            sb.Append(")");
            sbWithoutTypes.Append(")");
            var signature = sb.ToString()
                            .Replace(", params ", ", ")
                            .Replace("(params ", "(");

            if (completionList.All(data => data.DisplayText != signature))
            {
                item = engine.Factory.CreateAnonymousMethod(
                    this,
                    signature + " =>",
                    "Creates typed lambda expression.",
                    signature + " => ",
                    (addSemicolon ? ";" : "")
                    );
                if (!completionList.Any(i => i.DisplayText == item.DisplayText))
                {
                    completionList.Add(item);
                }

                // if (LanguageVersion.Major >= 5) {

                item = engine.Factory.CreateAnonymousMethod(
                    this,
                    "async " + signature + " =>",
                    "Creates typed async lambda expression.",
                    "async " + signature + " => ",
                    (addSemicolon ? ";" : "")
                    );
                if (!completionList.Any(i => i.DisplayText == item.DisplayText))
                {
                    completionList.Add(item);
                }

                var signatureWithoutTypes = sbWithoutTypes.ToString();
                if (!delegateMethod.Parameters.Any(p => p.RefKind != RefKind.None) && completionList.All(data => data.DisplayText != signatureWithoutTypes))
                {
                    item = engine.Factory.CreateAnonymousMethod(
                        this,
                        signatureWithoutTypes + " =>",
                        "Creates typed lambda expression.",
                        signatureWithoutTypes + " => ",
                        (addSemicolon ? ";" : "")
                        );
                    if (!completionList.Any(i => i.DisplayText == item.DisplayText))
                    {
                        completionList.Add(item);
                    }

                    //if (LanguageVersion.Major >= 5) {
                    item = engine.Factory.CreateAnonymousMethod(
                        this,
                        "async " + signatureWithoutTypes + " =>",
                        "Creates typed async lambda expression.",
                        "async " + signatureWithoutTypes + " => ",
                        (addSemicolon ? ";" : "")
                        );
                    if (!completionList.Any(i => i.DisplayText == item.DisplayText))
                    {
                        completionList.Add(item);
                    }

                    //}
                }
            }
            string varName = optDelegateName ?? "Handle" + delegateType.Name;


            var curType    = semanticModel.GetEnclosingSymbol <INamedTypeSymbol> (position, cancellationToken);
            var uniqueName = new UniqueNameGenerator(semanticModel).CreateUniqueMethodName(parent, varName);

            item = engine.Factory.CreateNewMethodDelegate(this, delegateType, uniqueName, curType);
            if (!completionList.Any(i => i.DisplayText == item.DisplayText))
            {
                completionList.Add(item);
            }
        }
Пример #6
0
 public string CreateShortType(ITypeSymbol fullType)
 {
     return(RoslynCompletionData.SafeMinimalDisplayString(fullType, CurrentState, offset));
 }
Пример #7
0
 public static TypeSyntax ConvertType(SemanticModel model, int position, ITypeSymbol type)
 {
     return(SyntaxFactory.ParseTypeName(RoslynCompletionData.SafeMinimalDisplayString(type, model, position)));
 }
Пример #8
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document          = context.Document;
            var span              = context.Span;
            var diagnostics       = context.Diagnostics;
            var cancellationToken = context.CancellationToken;

            var project    = document.Project;
            var diagnostic = diagnostics.First();
            var model      = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

            if (model.IsFromGeneratedCode(context.CancellationToken))
            {
                return;
            }

            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var node = root.FindToken(span.Start).GetAncestors <SyntaxNode>().First(n => n.Span.Contains(span));

            // Has to be a simple identifier or generic name.
            if (node != null && CanFullyQualify(diagnostic, ref node))
            {
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                var matchingTypes = await this.GetMatchingTypesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);

                var matchingNamespaces = await this.GetMatchingNamespacesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);

                if (matchingTypes != null || matchingNamespaces != null)
                {
                    matchingTypes      = matchingTypes ?? SpecializedCollections.EmptyEnumerable <ISymbol>();
                    matchingNamespaces = matchingNamespaces ?? SpecializedCollections.EmptyEnumerable <ISymbol>();

                    var matchingTypeContainers      = FilterAndSort(GetContainers(matchingTypes, semanticModel.Compilation));
                    var matchingNamespaceContainers = FilterAndSort(GetContainers(matchingNamespaces, semanticModel.Compilation));

                    var proposedContainers =
                        matchingTypeContainers.Concat(matchingNamespaceContainers)
                        .Distinct()
                        .Take(8);

                    foreach (var container in proposedContainers)
                    {
                        var containerName = RoslynCompletionData.SafeMinimalDisplayString(container, semanticModel, node.SpanStart);

                        string name;
                        int    arity;
                        node.GetNameAndArityOfSimpleName(out name, out arity);

                        // Actual member name might differ by case.
                        string memberName;
                        if (this.IgnoreCase)
                        {
                            var member = container.GetMembers(name).FirstOrDefault();
                            memberName = member != null ? member.Name : name;
                        }
                        else
                        {
                            memberName = name;
                        }

                        var codeAction = new DocumentChangeAction(
                            node.Span,
                            DiagnosticSeverity.Info,
                            string.Format(GettextCatalog.GetString("Change '{0}' to '{1}.{2}'"), name, containerName, memberName),
                            (c) =>
                        {
                            var newRoot = this.ReplaceNode(node, containerName, c);
                            return(Task.FromResult(document.WithSyntaxRoot(newRoot)));
                        });

                        context.RegisterCodeFix(codeAction, diagnostic);
                    }
                }
            }
        }