private static ILookupItem CreateMethodItem(CSharpCodeCompletionContext context, UnityEventFunction eventFunction,
                                                    IClassLikeDeclaration declaration)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            var method = eventFunction.CreateDeclaration(CSharpElementFactory.GetInstance(declaration), declaration);

            if (method.DeclaredElement == null)
            {
                return(null);
            }

            var instance = new DeclaredElementInstance(method.DeclaredElement);

            var declaredElementInfo = new DeclaredElementInfo(method.DeclaredName, instance, CSharpLanguage.Instance,
                                                              context.BasicContext.LookupItemsOwner, context)
            {
                Ranges = context.CompletionRanges
            };

            var withMatcher = LookupItemFactory.CreateLookupItem(declaredElementInfo).
                              WithPresentation(_ => new GenerateMemberPresentation(declaredElementInfo, PresenterStyles.DefaultPresenterStyle)).
                              WithBehavior(_ => new UnityEventFunctionBehavior(declaredElementInfo, eventFunction)).
                              WithMatcher(_ => new DeclaredElementMatcher(declaredElementInfo, context.BasicContext.IdentifierMatchingStyle));

            return(withMatcher);
        }
        private IList <LookupItem <PostfixTemplateInfo> > BuildLookupItems([NotNull] TPostfixTemplateContext context, [NotNull] CodeCompletionContext completionContext)
        {
            var items = new LocalList <LookupItem <PostfixTemplateInfo> >();

            //var multiplier = completionContext.Parameters.CodeCompletionTypes.Length;

            foreach (var templateRegistration in myTemplatesManager.GetEnabledTemplates(context))
            {
                var templateProvider = templateRegistration.Template;

                var postfixTemplateInfo = templateProvider.TryCreateInfo(context);
                if (postfixTemplateInfo == null)
                {
                    continue;
                }

                var templateName = templateRegistration.Metadata.TemplateName;

                Assertion.Assert(
                    string.Equals(templateName, postfixTemplateInfo.Text, StringComparison.Ordinal),
                    "Template text '{0}' should match declared template name '{1}'",
                    postfixTemplateInfo.Text, templateName);

                //postfixTemplateInfo.Multiplier = multiplier;

                items.Add(LookupItemFactory.CreateLookupItem(postfixTemplateInfo)
                          .WithMatcher(item => new PostfixTemplateMatcher(item.Info))
                          .WithBehavior(item => templateProvider.CreateBehavior(item.Info))
                          .WithPresentation(item => new PostfixTemplatePresentation(item.Info.Text)));
            }

            return(items.ResultingList());
        }
Example #3
0
        private static ILookupItem CreateMethodItem(CSharpCodeCompletionContext context, UnityMessage message,
                                                    IClassLikeDeclaration declaration)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            var method = message.CreateDeclaration(CSharpElementFactory.GetInstance(declaration), declaration);

            if (method.DeclaredElement == null)
            {
                return(null);
            }

            var instance            = new DeclaredElementInstance(method.DeclaredElement);
            var declaredElementInfo = new DeclaredElementInfo(method.DeclaredName, instance, CSharpLanguage.Instance,
                                                              context.BasicContext.LookupItemsOwner, context, context.BasicContext);

            return(LookupItemFactory.CreateLookupItem(declaredElementInfo).
                   WithPresentation(
                       _ => new GenerateMemberPresentation(declaredElementInfo, PresenterStyles.DefaultPresenterStyle)).
                   WithBehavior(_ =>
            {
                var behavior = new UnityMessageBehavior(declaredElementInfo, message);
                behavior.InitializeRanges(context.CompletionRanges, context.BasicContext);
                return behavior;
            }).
                   WithMatcher(_ => new DeclaredElementMatcher(declaredElementInfo, context.BasicContext.IdentifierMatchingStyle)));
        }
        private ILookupItem CreateLookoutItem(
            CSharpCodeCompletionContext context,
            string name,
            IList <DeclaredElementInstance <IMethod> > methods,
            bool skipGenericArguments,
            bool includeFollowingExpression = true,
            bool setFunctionParameters      = true)
        {
            var basicContext = context.BasicContext;
            var editorBrowsableProcessing = basicContext.EditorBrowsableProcessing;

            if (editorBrowsableProcessing != EditorBrowsableProcessingType.All)
            {
                methods = methods.Where(x => CodeInsightUtil.IsBrowsable(x.Element,
                                                                         showNever: false,
                                                                         showAdvanced: editorBrowsableProcessing == EditorBrowsableProcessingType.Advanced)).ToList();
            }
            if (methods.IsEmpty())
            {
                return(null);
            }
            var elements    = methods.Select(_ => new Pair <IDeclaredElement, ISubstitution>(_.Element, _.Substitution));
            var methodsInfo = new MethodsInfo(name, elements, CSharpLanguage.Instance, basicContext.LookupItemsOwner, context);

            methodsInfo.Ranges = context.CompletionRanges;
            methodsInfo.SkipGenericArguments = skipGenericArguments;
            methodsInfo.PutData(CompletionKeys.IsMethodsKey, new object());

            if (methods.All(x => x.Element.IsExtensionMethod))
            {
                methodsInfo.PutKey(CompletionKeys.IsExtensionMethodsKey);
            }

            var lookupItem = LookupItemFactory.CreateLookupItem(methodsInfo).WithPresentation(_gGetMethodsPresentation)
                             .WithBehavior(_ => new NukeTasksBehaviour(_.Info)).WithMatcher(_getMethodsMatcher);
            var qualifiableReference = CSharpLookupItemFactory.GetQualifiableReference(context);
            var qualifier            = qualifiableReference != null?qualifiableReference.GetQualifier() : null;

            var qualifierStaticness = qualifier == null ? new Staticness?() : AccessUtil.GetQualifierStaticness(qualifier);

            if (setFunctionParameters)
            {
                var functions = methodsInfo.AllDeclaredElements.Select(x => x.Element).OfType <IMethod>();
                CSharpLookupItemFactory.Instance.SetFunctionParameters(context,
                                                                       functions,
                                                                       lookupItem,
                                                                       methodsInfo);
            }

            methodsInfo.Placement.OrderString = name;
            return(lookupItem);
        }
        protected ILookupItem GetLookupElement(string replace, TextLookupRanges ranges)
        {
            var info = new TextualInfo(replace, replace)
            {
                ReplaceText = replace, Ranges = ranges
            };
            var item = LookupItemFactory.CreateLookupItem(info)
                       .WithPresentation(_ => new TextPresentation <TextualInfo>(info))
                       .WithBehavior(_ => new TextualBehavior <TextualInfo>(info))
                       .WithMatcher(_ => new TextualMatcher <TextualInfo>(info));

            return(item);
        }
Example #6
0
        protected override void TransformItems(CSharpCodeCompletionContext context, GroupedItemsCollector collector)
        {
            var referenceExpression = context.UnterminatedContext.ToReferenceExpression() ??
                                      context.TerminatedContext.ToReferenceExpression();

            if (referenceExpression == null)
            {
                return;
            }

            var settingsStore = referenceExpression.GetSettingsStore();

            if (!settingsStore.GetValue(PostfixTemplatesSettingsAccessor.ShowLengthCountItems))
            {
                return;
            }

            CSharpDeclaredElementInfo existingInfo = null;

            foreach (var lookupItem in collector.Items)
            {
                var aspectLookupItem = lookupItem as IAspectLookupItem <CSharpDeclaredElementInfo>;
                if (aspectLookupItem != null && IsLengthOrCountProperty(aspectLookupItem.Info))
                {
                    // do nothing if both 'Length' and 'Count' or multiple 'Length'/'Count' items exists
                    if (existingInfo != null)
                    {
                        return;
                    }

                    existingInfo = aspectLookupItem.Info;
                }
            }

            if (existingInfo != null)
            {
                var invertedInfo = new CSharpDeclaredElementInfo(
                    existingInfo.ShortName, existingInfo.PreferredDeclaredElement.NotNull(),
                    context.BasicContext.LookupItemsOwner, context, context.BasicContext);

                invertedInfo.Ranges    = context.CompletionRanges;
                invertedInfo.Placement = new LookupItemPlacement(InvertName(existingInfo));

                var invertedItem = LookupItemFactory.CreateLookupItem(invertedInfo)
                                   .WithPresentation(item => new InvertedItemPresentation(item.Info))
                                   .WithMatcher(item => new InvertedTextualMatcher(item.Info))
                                   .WithBehavior(item => new CSharpDeclaredElementBehavior <CSharpDeclaredElementInfo>(item.Info));

                collector.Add(invertedItem);
            }
        }
        private static LookupItem <TextualInfo> CreateLookupItem([NotNull] IMethodDeclaration methodDeclaration, [NotNull] CSharpCodeCompletionContext context)
        {
            var typeParameterName = GetTypeParameterName(methodDeclaration);
            var textualInfo       = new TextualInfo(typeParameterName, typeParameterName, context.BasicContext)
            {
                Ranges = context.CompletionRanges
            };

            var lookupItem = LookupItemFactory.CreateLookupItem(textualInfo)
                             .WithPresentation(item =>
            {
                var presentation = new PostfixTemplatePresentation(typeParameterName);
                var grayText     = TextStyle.FromForeColor(Color.Gray);
                presentation.DisplayName.Append("*", grayText);
                presentation.DisplayTypeName = new RichText("(create type parameter)", grayText);
                return(presentation);
            })
                             .WithMatcher(item => new TextualMatcher <TextualInfo>(item.Info, IdentifierMatchingStyle.Default))
                             .WithBehavior(item => new TypeParameterFromUsageBehavior(item.Info));

            return(lookupItem);
        }
Example #8
0
        private ILookupItem CreateMethodItem(CSharpCodeCompletionContext context,
                                             UnityEventFunction eventFunction, IClassLikeDeclaration declaration,
                                             bool hasReturnType, AccessRights accessRights,
                                             MemberGenerationContext generationContext)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            // Only show the modifier in the list text if it's not already specified and there isn't a return type, in
            // which case we default to `private`. E.g. if someone types `OnAnim`, then show `private void OnAnimate...`
            // but if they type `void OnAnim`, they don't want a modifier, and if they type `public void OnAnim` then
            // they want to use `public`
            var showModifier = false;

            if (!hasReturnType && accessRights == AccessRights.NONE)
            {
                showModifier = true;
                accessRights = AccessRights.PRIVATE;
            }

            // Note that we can't keep this declaration - it will become invalid as the user types to narrow down the
            // search and modifies the PSI file. This only affects ReSharper, Rider has different code completion
            // mechanism
            var factory           = CSharpElementFactory.GetInstance(declaration, false);
            var methodDeclaration = eventFunction.CreateDeclaration(factory, declaration, accessRights);

            if (methodDeclaration.DeclaredElement == null)
            {
                return(null);
            }

            // This is effectively the same as GenerateMemberPresentation, but without the overhead that comes
            // with the flexibility of formatting any time of declared element. We just hard code the format
            var predefinedType = context.PsiModule.GetPredefinedType();
            var parameters     = string.Empty;

            if (eventFunction.Parameters.Length > 0)
            {
                var sb = new StringBuilder();
                for (var i = 0; i < eventFunction.Parameters.Length; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }

                    var parameter = eventFunction.Parameters[i];
                    var type      = predefinedType.TryGetType(parameter.ClrTypeName, NullableAnnotation.Unknown);
                    var typeName  = type?.GetPresentableName(CSharpLanguage.Instance) ??
                                    parameter.ClrTypeName.ShortName;
                    sb.AppendFormat("{0}{1}{2}", parameter.IsByRef ? "out" : string.Empty,
                                    typeName, parameter.IsArray ? "[]" : string.Empty);
                }
                parameters = sb.ToString();
            }
            var text            = $"{eventFunction.Name}({parameters})";
            var parameterOffset = eventFunction.Name.Length;

            var modifier = showModifier
                ? CSharpDeclaredElementPresenter.Instance.Format(accessRights) + " "
                : string.Empty;

            var psiIconManager = context.BasicContext.LookupItemsOwner.Services.PsiIconManager;

            // Note that because this is a text based lookup item, then it won't be included if the normal C# method
            // filter is applied. We can't make it a method based lookup item because the DeclaredElement isn't valid in
            // this situation - it's not a real method, and a DeclaredElementInfo would try to store a pointer to it,
            // and be unable to recreate it when it's needed.
            var textualInfo = new UnityEventFunctionTextualInfo(generationContext.MemberReplaceRanges, text, text)
            {
                Ranges = context.CompletionRanges
            };

            var lookupItem = LookupItemFactory.CreateLookupItem(textualInfo)
                             .WithPresentation(item =>
            {
                var displayName = new RichText($"{modifier}{text} {{ ... }}");

                // GenerateMemberPresentation marks everything as bold, and the parameters + block syntax as not important
                var parameterStartOffset = modifier.Length + parameterOffset;
                LookupUtil.MarkAsNotImportant(displayName,
                                              TextRange.FromLength(parameterStartOffset, displayName.Length - parameterStartOffset));
                LookupUtil.AddEmphasize(displayName, new TextRange(modifier.Length, displayName.Length));

                var image = psiIconManager.GetImage(CLRDeclaredElementType.METHOD);
                psiIconManager.AttachExtensions(image, GetAccessExtensions(accessRights));
                var marker = item.Info.Ranges.CreateVisualReplaceRangeMarker();
                return(new SimplePresentation(displayName, image, marker));
            })
                             .WithBehavior(_ => new UnityEventFunctionBehavior(textualInfo, eventFunction, accessRights))
                             .WithMatcher(_ =>
                                          new ShiftedDeclaredElementMatcher(eventFunction.Name, modifier.Length, textualInfo));

            var description = GetDescription(context, methodDeclaration);

            return(new WrappedLookupItem(lookupItem, description));
        }
Example #9
0
        private static bool AddEnumerationMembers(
            [NotNull] CSharpCodeCompletionContext context, [NotNull] IDeclaredType enumerationType, [NotNull] GroupedItemsCollector collector)
        {
            var enumTypeElement = enumerationType.GetTypeElement() as IEnum;

            if (enumTypeElement == null)
            {
                return(false);
            }

            var enumSubstitution      = enumerationType.GetSubstitution();
            var enumMembersWithValues = new List <Pair <DeclaredElementInstance, string> >(); // todo: [R#] List<T1, T2>

            var isFlagsEnum = enumTypeElement.HasAttributeInstance(PredefinedType.FLAGS_ATTRIBUTE_CLASS, false);

            foreach (var enumMember in enumTypeElement.EnumMembers)
            {
                var enumValue = enumMember.ConstantValue.Value;
                var enumCase  = new DeclaredElementInstance(enumMember, enumSubstitution);

                if (isFlagsEnum)
                {
                    var convertible = enumValue as IConvertible;
                    if (convertible != null)
                    {
                        enumMembersWithValues.Add(Pair.Of(enumCase, GetBinaryRepresentation(convertible)));
                    }
                }
                else
                {
                    var formattable = enumValue as IFormattable;
                    if (formattable != null)
                    {
                        enumMembersWithValues.Add(Pair.Of(enumCase, formattable.ToString("D", CultureInfo.InvariantCulture)));
                    }
                }
            }

            if (enumMembersWithValues.Count == 0)
            {
                return(false);
            }

            var maxLength = enumMembersWithValues.Max(x => x.Second.Length);
            var index     = 0;

            foreach (var enumMember in enumMembersWithValues)
            {
                var elementInstance = enumMember.First;
                var elementValue    = isFlagsEnum ? enumMember.Second.PadLeft(maxLength, '0') : enumMember.Second;

                var info = new EnumCaseInfo(elementInstance, context, isFlagsEnum, elementValue);
                info.Placement.OrderString = "___ENUM_MEMBER_" + index.ToString("D16");
                info.Ranges = context.CompletionRanges;

                index++;

                var lookupItem = LookupItemFactory.CreateLookupItem(info)
                                 .WithPresentation(item =>
                {
                    var presentation = new DeclaredElementPresentation <CSharpDeclaredElementInfo>(item.Info, PresenterStyles.DefaultPresenterStyle);

                    var caseValue = item.Info.CaseValue;
                    if (caseValue.Length <= 32)
                    {
                        presentation.DisplayTypeName = new RichText("= " + caseValue, EnumValueStyle);
                    }

                    return(presentation);
                })
                                 .WithMatcher(item => new DeclaredElementMatcher(item.Info, IdentifierMatchingStyle.Default))
                                 .WithBehavior(item => new EnumCaseCheckBehavior(item.Info));

                collector.Add(lookupItem);
            }

            return(true);
        }
        private static ILookupItem CreateMethodItem(CSharpCodeCompletionContext context,
                                                    UnityEventFunction eventFunction, IClassLikeDeclaration declaration, bool addModifier)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            var method = eventFunction.CreateDeclaration(CSharpElementFactory.GetInstance(declaration, false), declaration);

            if (method.DeclaredElement == null)
            {
                return(null);
            }

            var instance = new DeclaredElementInstance(method.DeclaredElement);

            var declaredElementInfo = new DeclaredElementInfoWithoutParameterInfo(method.DeclaredName, instance, CSharpLanguage.Instance,
                                                                                  context.BasicContext.LookupItemsOwner, context)
            {
                Ranges = context.CompletionRanges
            };

            // This is effectively the same as GenerateMemberPresentation, but without the overhead that comes
            // with the flexibility of formatting any time of declared element. We just hard code the format
            var predefinedType = context.PsiModule.GetPredefinedType();
            var parameters     = string.Empty;

            if (eventFunction.Parameters.Length > 0)
            {
                var sb = new StringBuilder();
                for (var i = 0; i < eventFunction.Parameters.Length; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }

                    var parameter = eventFunction.Parameters[i];
                    var type      = predefinedType.TryGetType(parameter.ClrTypeName);
                    var typeName  = type?.GetPresentableName(CSharpLanguage.Instance) ??
                                    parameter.ClrTypeName.ShortName;
                    sb.AppendFormat("{0}{1}{2}", parameter.IsByRef ? "out" : string.Empty,
                                    typeName, parameter.IsArray ? "[]" : string.Empty);
                }
                parameters = sb.ToString();
            }
            var text            = $"{eventFunction.Name}({parameters})";
            var parameterOffset = eventFunction.Name.Length;
            var modifier        = addModifier ? "private " : string.Empty;

            var psiIconManager = context.BasicContext.LookupItemsOwner.Services.PsiIconManager;

            return(LookupItemFactory.CreateLookupItem(declaredElementInfo)
                   .WithPresentation(item =>
            {
                var displayName = new RichText($"{modifier}{text} {{ ... }}");

                // GenerateMemberPresentation marks everything as bold, and the parameters + block syntax as not important
                var parameterStartOffset = modifier.Length + parameterOffset;
                LookupUtil.MarkAsNotImportant(displayName,
                                              TextRange.FromLength(parameterStartOffset, displayName.Length - parameterStartOffset));
                LookupUtil.AddEmphasize(displayName, new TextRange(modifier.Length, displayName.Length));

                var image = psiIconManager.GetImage(CLRDeclaredElementType.METHOD, PsiIconExtension.Private);
                var marker = item.Info.Ranges.CreateVisualReplaceRangeMarker();
                return new SimplePresentation(displayName, image, marker);
            })
                   .WithBehavior(_ => new UnityEventFunctionBehavior(declaredElementInfo, eventFunction))
                   .WithMatcher(_ =>
                                new ShiftedDeclaredElementMatcher(text, modifier.Length, declaredElementInfo,
                                                                  context.BasicContext.IdentifierMatchingStyle)));
        }
Example #11
0
        private ILookupItem CreateMethodItem(CSharpCodeCompletionContext context,
                                             UnityEventFunction eventFunction, IClassLikeDeclaration declaration,
                                             bool hasReturnType, AccessRights accessRights)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            // Only show the modifier in the list text if it's not already specified and there isn't a return type, in
            // which case we default to `private`. E.g. if someone types `OnAnim`, then show `private void OnAnimate...`
            // but if they type `void OnAnim`, they don't want a modifier, and if they type `public void OnAnim` then
            // they want to use `public`
            var showModifier = false;

            if (!hasReturnType && accessRights == AccessRights.NONE)
            {
                showModifier = true;
                accessRights = AccessRights.PRIVATE;
            }

            var factory           = CSharpElementFactory.GetInstance(declaration, false);
            var methodDeclaration = eventFunction.CreateDeclaration(factory, declaration, accessRights);

            if (methodDeclaration.DeclaredElement == null)
            {
                return(null);
            }

            var instance = new DeclaredElementInstance(methodDeclaration.DeclaredElement);

            var declaredElementInfo = new DeclaredElementInfoWithoutParameterInfo(methodDeclaration.DeclaredName,
                                                                                  instance, CSharpLanguage.Instance, context.BasicContext.LookupItemsOwner, context)
            {
                Ranges = context.CompletionRanges
            };

            // This is effectively the same as GenerateMemberPresentation, but without the overhead that comes
            // with the flexibility of formatting any time of declared element. We just hard code the format
            var predefinedType = context.PsiModule.GetPredefinedType();
            var parameters     = string.Empty;

            if (eventFunction.Parameters.Length > 0)
            {
                var sb = new StringBuilder();
                for (var i = 0; i < eventFunction.Parameters.Length; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }

                    var parameter = eventFunction.Parameters[i];
                    var type      = predefinedType.TryGetType(parameter.ClrTypeName, NullableAnnotation.Unknown);
                    var typeName  = type?.GetPresentableName(CSharpLanguage.Instance) ??
                                    parameter.ClrTypeName.ShortName;
                    sb.AppendFormat("{0}{1}{2}", parameter.IsByRef ? "out" : string.Empty,
                                    typeName, parameter.IsArray ? "[]" : string.Empty);
                }
                parameters = sb.ToString();
            }
            var text            = $"{eventFunction.Name}({parameters})";
            var parameterOffset = eventFunction.Name.Length;

            var modifier = showModifier
                ? CSharpDeclaredElementPresenter.Instance.Format(accessRights) + " "
                : string.Empty;

            var psiIconManager = context.BasicContext.LookupItemsOwner.Services.PsiIconManager;

            return(LookupItemFactory.CreateLookupItem(declaredElementInfo)
                   .WithPresentation(item =>
            {
                var displayName = new RichText($"{modifier}{text} {{ ... }}");

                // GenerateMemberPresentation marks everything as bold, and the parameters + block syntax as not important
                var parameterStartOffset = modifier.Length + parameterOffset;
                LookupUtil.MarkAsNotImportant(displayName,
                                              TextRange.FromLength(parameterStartOffset, displayName.Length - parameterStartOffset));
                LookupUtil.AddEmphasize(displayName, new TextRange(modifier.Length, displayName.Length));

                var image = psiIconManager.GetImage(methodDeclaration.DeclaredElement,
                                                    methodDeclaration.DeclaredElement.PresentationLanguage, true);
                var marker = item.Info.Ranges.CreateVisualReplaceRangeMarker();
                return new SimplePresentation(displayName, image, marker);
            })
                   .WithBehavior(_ => new UnityEventFunctionBehavior(myShellLocks, declaredElementInfo, eventFunction, accessRights))
                   .WithMatcher(_ =>
                                new ShiftedDeclaredElementMatcher(eventFunction.Name, modifier.Length, declaredElementInfo,
                                                                  context.BasicContext.IdentifierMatchingStyle)));
        }