Example #1
0
        public static string GetUniqueName <T>([NotNull] T node, [CanBeNull] string baseName,
                                               NamedElementKinds elementKind, Action <INamesCollection> collectionModifier = null, Func <IDeclaredElement, bool> isConflictingElement = null) where T : ICSharpTreeNode
        {
            node.GetPsiServices().Locks.AssertMainThread();

            isConflictingElement = isConflictingElement ?? JetFunc <IDeclaredElement> .True;
            var namingManager   = node.GetPsiServices().Naming;
            var policyProvider  = namingManager.Policy.GetPolicyProvider(node.Language, node.GetSourceFile());
            var namingRule      = policyProvider.GetPolicy(elementKind).NamingRule;
            var namesCollection = namingManager.Suggestion.CreateEmptyCollection(PluralityKinds.Unknown, CSharpLanguage.Instance, true, policyProvider);

            if (baseName != null)
            {
                var name     = namingManager.Parsing.Parse(baseName, namingRule, policyProvider);
                var nameRoot = name.GetRootOrDefault(baseName);
                namesCollection.Add(nameRoot, new EntryOptions(PluralityKinds.Plural, SubrootPolicy.Decompose, emphasis: Emphasis.Good));
            }

            collectionModifier?.Invoke(namesCollection);
            var suggestionOptions = new SuggestionOptions
            {
                DefaultName          = baseName,
                UniqueNameContext    = node,
                IsConflictingElement = isConflictingElement
            };
            var namesSuggestion = namesCollection.Prepare(elementKind, ScopeKind.Common, suggestionOptions);

            return(namesSuggestion.FirstName());
        }
        /// <summary>
        /// Execution of refactoring starts here. Data from context is initialized.
        /// </summary>
        public override bool Initialize(IDataContext context)
        {
            IParameter parameter;
            IMethod    method;

            if (!IsAvailableInternal(context, out parameter, out method))
            {
                return(false);
            }

            // Never reference DeclaredElements, References, Types, etc. from workflow. Use pointers!
            // Code can be edited during execution end elements (types, references) can be invalidated.
            MethodPointer    = method.CreateElementPointer();
            ParameterPointer = parameter.CreateElementPointer();

            // use also:
            // PsiManager.GetInstance(Solution).CreateReferencePointer(...);
            // PsiManager.GetInstance(Solution).CreateTreeElementPointer(...);

            // following code produces name for type parameter using parameter name...
            NamingManager namingManager     = method.GetPsiServices().Naming;
            var           suggestionOptions = new SuggestionOptions {
                DefaultName = "T"
            };

            TypeParameterName = namingManager.Suggestion.GetDerivedName(parameter, NamedElementKinds.TypeParameters,
                                                                        ScopeKind.Common, parameter.PresentationLanguage, suggestionOptions, null);
            return(true);
        }
Example #3
0
        private bool IsDefaultValue(SuggestionOptions val)
        {
            var defaultSuggestionOptions = new SuggestionOptions();
            defaultSuggestionOptions.Distance = StringDistanceTypes.None;

            return val.Equals(defaultSuggestionOptions);
        }
            private static IList <string> SuggestIteratorVariableNames([NotNull] IForStatement statement)
            {
                var declarationMember   = statement.Initializer.Declaration.Declarators[0];
                var iteratorDeclaration = (ILocalVariableDeclaration)declarationMember;
                var namingManager       = statement.GetPsiServices().Naming;

                var policyProvider = namingManager.Policy.GetPolicyProvider(iteratorDeclaration.Language, iteratorDeclaration.GetSourceFile());
                var collection     = namingManager.Suggestion.CreateEmptyCollection(PluralityKinds.Single, iteratorDeclaration.Language, true, policyProvider);

                var variableType = iteratorDeclaration.DeclaredElement.Type;

                if (variableType.IsResolved)
                {
                    collection.Add(variableType, new EntryOptions {
                        PluralityKind = PluralityKinds.Single,
                        SubrootPolicy = SubrootPolicy.Decompose
                    });
                }

                var suggestionOptions = new SuggestionOptions {
                    UniqueNameContext = statement, DefaultName = "i"
                };

                collection.Prepare(iteratorDeclaration.DeclaredElement, suggestionOptions);

                return(collection.AllNames());
            }
 /// <summary>
 /// Register a field to be sorted
 /// </summary>
 protected void Suggestion(Expression <Func <TReduceResult, object> > field, SuggestionOptions suggestion = null)
 {
     IndexSuggestions.Add(field, suggestion ?? new SuggestionOptions
     {
         Accuracy = 0.5f,
         Distance = StringDistanceTypes.Levenshtein
     });
 }
        public static string GetMethodNameAndParameterFromStepPattern(GherkinStepKind stepKind, string pattern, IPsiServices psiServices, IPsiSourceFile psiSourceFile, List <string> parameterNames)
        {
            var options        = new SuggestionOptions();
            var cleanPattern   = ReplacePatternCaptureWithParameterName(pattern, parameterNames);
            var patternNoSpace = stepKind + TextHelper.ToPascalCase(cleanPattern);
            var methodName     = psiServices.Naming.Suggestion.GetDerivedName(patternNoSpace, NamedElementKinds.Method, ScopeKind.Common, CSharpLanguage.Instance, options, psiSourceFile);

            return(methodName);
        }
        private string GetOptionsParameterName(SuggestionOptions options)
        {
            string optionsParameterName = null;

            if (options != null && options != SuggestionOptions.Default)
            {
                optionsParameterName = AddQueryParameter(options);
            }

            return(optionsParameterName);
        }
        public static (string name, string pattern, string[] parameterTypes) GetMethodNameAndParameterFromStepText(GherkinStepKind stepKind, string stepText, IPsiServices psiServices, IPsiSourceFile psiSourceFile)
        {
            var options = new SuggestionOptions();

            var(cleanPattern, parameters) = CleanPattern(stepText.Trim());
            var patternNoSpace = stepKind + TextHelper.ToPascalCase(cleanPattern.Replace("\"(.*)\"", "X"));
            var methodName     = psiServices.Naming.Suggestion.GetDerivedName(patternNoSpace, NamedElementKinds.Method, ScopeKind.Common, CSharpLanguage.Instance, options, psiSourceFile);
            var parameterTypes = parameters.Select(parameter => int.TryParse(parameter, out _) ? "System.Int32" : "System.String").ToArray();

            return(methodName, cleanPattern, parameterTypes);
        }
        private static void ProcessReferenceName(CSharpCodeCompletionContext context, GroupedItemsCollector collector, IReferenceName referenceName, NamedElementKinds elementKinds, ScopeKind localSelfScoped)
        {
            if (referenceName == null)
            {
                return;
            }
            var referenceNameResolveResult = referenceName.Reference.Resolve();
            var referencedElementAsString  = referenceNameResolveResult.DeclaredElement.ConvertToString();

            if (referencedElementAsString == "Class:Moq.Mock`1")
            {
                var typeArgumentList = referenceName.TypeArgumentList;
                var typeArguments    = typeArgumentList.TypeArguments;
                if (typeArguments.Count == 1)
                {
                    var typeArgument = typeArguments[0];
                    var scalarType   = typeArgument.GetScalarType();
                    if (scalarType == null)
                    {
                        return;
                    }
                    var    genericTypeResolveResult = scalarType.Resolve();
                    var    namingManager            = typeArgument.GetPsiServices().Naming;
                    var    suggestionOptions        = new SuggestionOptions();
                    string proposedName;
                    if (genericTypeResolveResult.IsEmpty)
                    {
                        proposedName = namingManager.Suggestion.GetDerivedName(typeArgument.GetPresentableName(CSharpLanguage.Instance), elementKinds, localSelfScoped, CSharpLanguage.Instance, suggestionOptions, referenceName.GetSourceFile());
                    }
                    else
                    {
                        proposedName = namingManager.Suggestion.GetDerivedName(genericTypeResolveResult.DeclaredElement, elementKinds, localSelfScoped, CSharpLanguage.Instance, suggestionOptions, referenceName.GetSourceFile());
                    }
#if RESHARPER8
                    collector.AddToTop(context.LookupItemsFactory.CreateTextLookupItem(proposedName));
                    collector.AddToTop(context.LookupItemsFactory.CreateTextLookupItem(proposedName + "Mock"));
#endif
#if RESHARPER9
                    var textLookupItem = new TextLookupItem(proposedName);
                    textLookupItem.InitializeRanges(context.CompletionRanges, context.BasicContext);
                    textLookupItem.PlaceTop();
                    collector.Add(textLookupItem);
#endif

#if RESHARPER9
                    var textLookupItem2 = new TextLookupItem(proposedName + "Mock");
                    textLookupItem2.InitializeRanges(context.CompletionRanges, context.BasicContext);
                    textLookupItem2.PlaceTop();
                    collector.Add(textLookupItem2);
#endif
                }
            }
        }
Example #10
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var block            = _dataProvider.GetSelectedElement <IBlock>();
            var classBody        = _dataProvider.GetSelectedElement <IClassBody>();
            var classDeclaration = classBody?.GetContainingTypeDeclaration() as IClassLikeDeclaration;

            if (classDeclaration == null || block == null)
            {
                return(null);
            }

            if (!(_selectedElement.TypeReference.Resolve()?.DeclaredElement is IClass c))
            {
                return(null);
            }

            var constructor = c.Constructors.ToArray().OrderByDescending(x => x.Parameters.Count).FirstOrDefault(x => !x.IsParameterless);

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

            var parameters       = _parameterProvider.GetParameters(constructor.ToString()).ToArray();
            var naming           = _dataProvider.PsiServices.Naming;
            var mockFieldsByType = GetFields(classBody);

            for (int i = 0; i < constructor.Parameters.Count; i++)
            {
                var shortName  = constructor.Parameters[i].ShortName;
                var typeString = GetGenericMock(parameters[i]);

                if (!mockFieldsByType.TryGetValue(typeString, out var name))
                {
                    var mockType = TypeFactory.CreateTypeByCLRName(typeString, _dataProvider.PsiModule);
                    var field    = _dataProvider.ElementFactory.CreateTypeMemberDeclaration("private $0 $1;", (object)mockType, (object)shortName);
                    var options  = new SuggestionOptions(defaultName: shortName);
                    name = naming.Suggestion.GetDerivedName(field.DeclaredElement, NamedElementKinds.PrivateInstanceFields, ScopeKind.Common, _selectedElement.Language,
                                                            options, _dataProvider.SourceFile);
                    field.SetName(name);
                    classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)field);

                    var statement = _dataProvider.ElementFactory.CreateStatement("$0 = new Mock<$1>();", (object)name, (object)parameters[i]);
                    block.AddStatementBefore(statement, _selectedElement.GetContainingStatement());
                }

                var argument = _dataProvider.ElementFactory.CreateArgument(ParameterKind.VALUE, _dataProvider.ElementFactory.CreateExpression($"{name}.Object"));
                _selectedElement.AddArgumentBefore(argument, null);
            }

            return(null);
        }
Example #11
0
        public SuggestionOptions GetOptions(JsonOperationContext context, BlittableJsonReaderObject parameters)
        {
            if (_options != null)
            {
                return(_options);
            }

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

            BlittableJsonReaderObject optionsJson;

            if (_optionsType == AST.ValueTokenType.Parameter)
            {
                if (parameters == null)
                {
                    throw new ArgumentNullException(nameof(parameters));
                }

                if (parameters.TryGetMember(_optionsAsStringOrParameterName, out var optionsObject) == false)
                {
                    throw new InvalidOperationException($"Parameter '{_optionsAsStringOrParameterName}' containing '{nameof(SuggestionOptions)}' was not present in the list of parameters.");
                }

                optionsJson = optionsObject as BlittableJsonReaderObject;

                if (optionsJson == null)
                {
                    throw new InvalidOperationException($"Parameter '{_optionsAsStringOrParameterName}' should contain JSON object.");
                }
            }
            else if (_optionsType == AST.ValueTokenType.String)
            {
                optionsJson = IndexReadOperation.ParseJsonStringIntoBlittable(_optionsAsStringOrParameterName, context);
            }
            else
            {
                throw new InvalidOperationException($"Unknown options type '{_optionsType}'.");
            }

            var options = (SuggestionOptions)EntityToBlittable.ConvertToEntity(typeof(SuggestionOptions), "suggestion/options", optionsJson, DocumentConventions.Default);

            if (_optionsType == AST.ValueTokenType.String)
            {
                _options = options;
            }

            return(options);
        }
            private static IList <string> SuggestResourceVariableNames([NotNull] IUsingStatement statement)
            {
                var variableDeclaration = statement.Declaration;

                if (variableDeclaration == null)
                {
                    return(EmptyList <string> .InstanceList);
                }

                var localVariable = statement.Declaration.Declarators[0] as ILocalVariableDeclaration;

                if (localVariable == null)
                {
                    return(EmptyList <string> .InstanceList);
                }

                var namingManager = statement.GetPsiServices().Naming;

                var policyProvider = namingManager.Policy.GetPolicyProvider(
                    variableDeclaration.Language, variableDeclaration.GetSourceFile());

                var collection = namingManager.Suggestion.CreateEmptyCollection(
                    PluralityKinds.Single, variableDeclaration.Language, true, policyProvider);

                var initializer = localVariable.Initial as IExpressionInitializer;

                if (initializer != null)
                {
                    collection.Add(initializer.Value, new EntryOptions {
                        SubrootPolicy          = SubrootPolicy.Decompose,
                        PredefinedPrefixPolicy = PredefinedPrefixPolicy.Remove
                    });

                    var variableType = initializer.Value.Type();
                    if (variableType.IsResolved)
                    {
                        collection.Add(variableType, new EntryOptions {
                            SubrootPolicy = SubrootPolicy.Decompose
                        });
                    }
                }

                var suggestionOptions = new SuggestionOptions {
                    UniqueNameContext = statement
                };

                collection.Prepare(localVariable.DeclaredElement, suggestionOptions);

                return(collection.AllNames());
            }
        private string[] QueryOverSingleWord(SuggestionField field, string word, SuggestionOptions options)
        {
            // Perform devirtualization of the distance function when supported.
            switch (options.Distance)
            {
            case StringDistanceTypes.JaroWinkler:
                return(QueryOverSingleWord(field, word, options, new JaroWinklerDistance()));

            case StringDistanceTypes.NGram:
                return(QueryOverSingleWord(field, word, options, new NGramDistance()));

            default:
                return(QueryOverSingleWord(field, word, options, new LevenshteinDistance()));
            }
        }
        private static string GetUniqueName([NotNull] IReferenceExpression referenceExpression, [NotNull] string baseName)
        {
            var namingManager   = referenceExpression.GetPsiServices().Naming;
            var policyProvider  = namingManager.Policy.GetPolicyProvider(referenceExpression.Language, referenceExpression.GetSourceFile());
            var namingRule      = policyProvider.GetPolicy(NamedElementKinds.Locals).NamingRule;
            var name            = namingManager.Parsing.Parse(baseName, namingRule, policyProvider);
            var nameRoot        = name.GetRootOrDefault(baseName);
            var namesCollection = namingManager.Suggestion.CreateEmptyCollection(PluralityKinds.Unknown, CSharpLanguage.Instance, true, policyProvider);

            namesCollection.Add(nameRoot, new EntryOptions(PluralityKinds.Unknown, SubrootPolicy.Decompose, emphasis: Emphasis.Good));
            var suggestionOptions = new SuggestionOptions
            {
                DefaultName       = baseName,
                UniqueNameContext = referenceExpression,
            };
            var namesSuggestion = namesCollection.Prepare(NamedElementKinds.Locals, ScopeKind.Common, suggestionOptions);

            return(namesSuggestion.FirstName());
        }
Example #15
0
            public void InitializeData3()
            {
                string[]       namesArr3  = { "name1", "name2", "name3" };
                FieldStorage[] storesArr3 = { FieldStorage.No, FieldStorage.Yes, FieldStorage.No };
                string[]       analArr3   = { "anal1", "anal2", "anal31" };
                var            sug31      = new SuggestionOptions();

                sug31.Distance = StringDistanceTypes.Levenshtein;
                sug31.Accuracy = (float)0.6;
                var sug32 = new SuggestionOptions();
                var sug33 = new SuggestionOptions();

                sug33.Distance = StringDistanceTypes.Levenshtein;
                sug33.Accuracy = (float)0.5;
                SuggestionOptions[] sugArr3 = { sug31, sug32, sug33 };


                FillDictData(namesArr3, storesArr3, analArr3, sugArr3);
            }
Example #16
0
            public void InitializeData1()
            {
                string[]       namesArr1  = { "name1", "name2", "name3" };
                FieldStorage[] storesArr1 = { FieldStorage.No, FieldStorage.Yes, FieldStorage.Yes };
                string[]       analArr1   = { "anal1", "anal2", "anal3" };
                var            sug1       = new SuggestionOptions();

                sug1.Distance = StringDistanceTypes.Levenshtein;
                sug1.Accuracy = (float)0.6;
                var sug2 = new SuggestionOptions();
                var sug3 = new SuggestionOptions();

                sug3.Distance = StringDistanceTypes.Levenshtein;
                sug3.Accuracy = (float)0.45;
                SuggestionOptions[] sugArr1 = { sug1, sug2, sug3 };


                FillDictData(namesArr1, storesArr1, analArr1, sugArr1);
            }
Example #17
0
            public void InitializeData2()
            {
                string[]       namesArr2  = { "name2", "name3", "name1" };
                FieldStorage[] storesArr2 = { FieldStorage.Yes, FieldStorage.Yes, FieldStorage.No };
                string[]       analArr2   = { "anal2", "anal3", "anal1" };
                var            sug21      = new SuggestionOptions();

                sug21.Distance = StringDistanceTypes.Levenshtein;
                sug21.Accuracy = (float)0.6;
                var sug22 = new SuggestionOptions();
                var sug23 = new SuggestionOptions();

                sug23.Distance = StringDistanceTypes.Levenshtein;
                sug23.Accuracy = (float)0.45;
                SuggestionOptions[] sugArr2 = { sug22, sug23, sug21 };



                FillDictData(namesArr2, storesArr2, analArr2, sugArr2);
            }
Example #18
0
        public SuggestionOptions GetOptions(JsonOperationContext context, BlittableJsonReaderObject parameters)
        {
            if (_options != null)
            {
                return(_options);
            }

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

            var options = FieldOptionsHelper.GetOptions <SuggestionOptions>(_optionsAsStringOrParameterName, _optionsType, parameters, context);

            if (_optionsType == AST.ValueTokenType.String)
            {
                _options = options;
            }

            return(options);
        }
Example #19
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var argumentList     = _selectedElement.ArgumentList;
            var parameters       = _parameterProvider.GetParameters(_constructor.ToString()).ToArray();
            var mockFieldsByType = GetFields(_classBody);
            var shortName        = _constructor.Parameters[_parameterNumber].ShortName;
            var currentParam     = parameters[_parameterNumber];
            var typeString       = GetGenericMock(currentParam);

            if (!mockFieldsByType.TryGetValue(typeString, out var name))
            {
                var mockType = TypeFactory.CreateTypeByCLRName(typeString, _dataProvider.PsiModule);
                var field    = _dataProvider.ElementFactory.CreateTypeMemberDeclaration("private $0 $1;", (object)mockType, (object)shortName);
                var options  = new SuggestionOptions(defaultName: shortName);
                name = _dataProvider.PsiServices.Naming.Suggestion.GetDerivedName(field.DeclaredElement, NamedElementKinds.PrivateInstanceFields, ScopeKind.Common, _selectedElement.Language, options, _dataProvider.SourceFile);
                field.SetName(name);
                _classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)field);

                var statement = _dataProvider.ElementFactory.CreateStatement("$0 = new Mock<$1>();", (object)name, (object)currentParam);
                _block.AddStatementBefore(statement, _selectedElement.GetContainingStatement());
            }

            var argument         = _dataProvider.ElementFactory.CreateArgument(ParameterKind.VALUE, _dataProvider.ElementFactory.CreateExpression($"{name}.Object"));
            var previousArgument = _parameterNumber != 0 ? argumentList.Arguments[_parameterNumber - 1] : null;
            var arg           = _selectedElement.AddArgumentAfter(argument, previousArgument);
            var argumentRange = arg.GetDocumentRange();

            // Remove last comma Hack!
            return(textControl =>
            {
                var range = new TextRange(argumentRange.EndOffset.Offset, argumentRange.EndOffset.Offset + 1);
                if (textControl.Document.GetText(range) == ",")
                {
                    textControl.Document.DeleteText(range);
                }
            });
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var argumentList     = _selectedElement.ArgumentList;
            var parameters       = _csharpMemberProvider.GetConstructorParameters(_constructor.ToString()).ToArray();
            var mockFieldsByType = _csharpMemberProvider.GetClassFields(_classBody, _selectedElement.Language);
            var shortName        = _constructor.Parameters[_parameterNumber].ShortName;
            var currentParam     = parameters[_parameterNumber];
            var typeString       = _csharpMemberProvider.GetGenericMock(currentParam);

            if (!mockFieldsByType.TryGetValue(typeString, out var name))
            {
                var mockType = TypeFactory.CreateTypeByCLRName(typeString, _dataProvider.PsiModule);
                var field    = _dataProvider.ElementFactory.CreateTypeMemberDeclaration("private $0 $1;", (object)mockType, (object)shortName);
                var options  = new SuggestionOptions(defaultName: shortName);
                name = _dataProvider.PsiServices.Naming.Suggestion.GetDerivedName(field.DeclaredElement, NamedElementKinds.PrivateInstanceFields, ScopeKind.Common, _selectedElement.Language, options, _dataProvider.SourceFile);
                field.SetName(name);
                _classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)field);

                var statement = _dataProvider.ElementFactory.CreateStatement("$0 = new Mock<$1>();", (object)name, (object)currentParam);
                _block.AddStatementBefore(statement, _selectedElement.GetContainingStatement());
            }

            return(_csharpMemberProvider.FillCurrentParameterWithMock(name, argumentList, _selectedElement, _parameterNumber, _dataProvider));
        }
    /// <summary>
    /// Execution of refatoring starts here. Data from context is initialized. 
    /// </summary>
    public override bool Initialize(IDataContext context)
    {
      IParameter parameter;
      IMethod method;
      if (!IsAvailableInternal(context, out parameter, out method))
        return false;

      // Never reference DeclaredElements, References, Types, etc. from workflow. Use pointers!
      // Code can be edited during execution end elements (types, references) can be invalidated. 
      MethodPointer = method.CreateElementPointer();
      ParameterPointer = parameter.CreateElementPointer();

      // use also:
      // PsiManager.GetInstance(Solution).CreateReferencePointer(...);
      // PsiManager.GetInstance(Solution).CreateTreeElementPointer(...);

      // following code produces name for type parameter using parameter name...
      NamingManager namingManager = method.GetPsiServices().Naming;
      var suggestionOptions = new SuggestionOptions {DefaultName = "T"};
      
      TypeParameterName = namingManager.Suggestion.GetDerivedName(parameter, NamedElementKinds.TypeParameters,
                                                                  ScopeKind.Common, parameter.PresentationLanguage, suggestionOptions, null);
      return true;
    }
Example #22
0
 public SuggestionOptionsBuilder(SuggestionOptions options)
 {
     _with  = options.With;
     _fuzzy = options.Fuzzy;
     _max   = options.Max;
 }
        private string[] QueryOverMultipleWords(SuggestionField field, List <string> words, SuggestionOptions options)
        {
            options.SortMode = SuggestionSortMode.None;

            var result = new HashSet <string>();

            var pageSize = options.PageSize;

            foreach (var term in words)
            {
                if (pageSize <= 0)
                {
                    break;
                }

                foreach (var suggestion in QueryOverSingleWord(field, term, options))
                {
                    if (result.Add(suggestion) == false)
                    {
                        continue;
                    }

                    pageSize--;
                    if (pageSize <= 0)
                    {
                        break;
                    }
                }
            }

            return(result.ToArray());
        }
        private string[] QueryOverSingleWord <TDistance>(SuggestionField suggestionField, string word, SuggestionOptions options, TDistance sd)
            where TDistance : IStringDistance
        {
            var min         = options.Accuracy ?? SuggestionOptions.DefaultAccuracy;
            var field       = suggestionField.Name;
            var pageSize    = options.PageSize;
            var morePopular = options.SortMode == SuggestionSortMode.Popularity;

            int lengthWord = word.Length;

            var ir = _searcher.IndexReader;

            int freq     = (ir != null && field != null) ? ir.DocFreq(new Term(FWord, word), _state) : 0;
            int goalFreq = (morePopular && ir != null && field != null) ? freq : 0;

            // if the word exists in the real index and we don't care for word frequency, return the word itself
            if (!morePopular && freq > 0)
            {
                return(new[] { word });
            }

            var query = new BooleanQuery();

            var alreadySeen = new HashSet <string>();

            int ng  = GetMin(lengthWord);
            int max = ng + 1;

            var table = GramsTable;

            for (; ng <= max; ng++)
            {
                string[] grams = FormGrams(word, ng);

                if (grams.Length == 0)
                {
                    continue; // hmm
                }

                if (BoostStart > 0)
                {
                    // should we boost prefixes?
                    Add(query, table[ng].Start, grams[0], BoostStart); // matches start of word
                }

                if (BoostEnd > 0)
                {
                    // should we boost suffixes
                    Add(query, table[ng].End, grams[grams.Length - 1], BoostEnd); // matches end of word
                }

                for (int i = 0; i < grams.Length; i++)
                {
                    Add(query, table[ng].Gram, grams[i]);
                }
            }

            int maxHits = 10 * pageSize;

            //    System.out.println("Q: " + query);
            ScoreDoc[] hits = _searcher.Search(query, null, maxHits, _state).ScoreDocs;

            //    System.out.println("HITS: " + hits.length());
            var queue = new SuggestWordQueue(pageSize);

            // go thru more than 'maxr' matches in case the distance filter triggers
            int stop = Math.Min(hits.Length, maxHits);

            var suggestedWord = new SuggestWord();

            for (int i = 0; i < stop; i++)
            {
                suggestedWord.Term = _searcher.Doc(hits[i].Doc, _state).Get(FWord, _state); // get orig word

                // don't suggest a word for itself, that would be silly
                if (suggestedWord.Term.Equals(word, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                // edit distance
                suggestedWord.Score = sd.GetDistance(word, suggestedWord.Term);
                if (suggestedWord.Score < min)
                {
                    continue;
                }

                if (ir != null && field != null)
                {
                    // use the user index
                    suggestedWord.Freq = _searcher.DocFreq(new Term(FWord, suggestedWord.Term), _state); // freq in the index

                    // don't suggest a word that is not present in the field
                    if ((morePopular && goalFreq > suggestedWord.Freq) || suggestedWord.Freq < 1)
                    {
                        continue;
                    }
                }

                if (alreadySeen.Add(suggestedWord.Term) == false) // we already seen this word, no point returning it twice
                {
                    continue;
                }

                queue.InsertWithOverflow(suggestedWord);
                if (queue.Size() == pageSize)
                {
                    // if queue full, maintain the minScore score
                    min = queue.Top().Score;
                }

                suggestedWord = new SuggestWord();
            }

            int size = queue.Size();

            if (size == 0)
            {
                return(EmptyArray);
            }

            // convert to array string
            string[] list = new string[size];
            for (int i = size - 1; i >= 0; i--)
            {
                list[i] = queue.Pop().Term;
            }

            return(list);
        }
        public bool Execute(IProgressIndicator progressIndicator)
        {
            var ctor = _ctor.FindDeclaredElement();
            if (ctor == null)
                return false;
            var definingClass = _class.FindDeclaredElement();
            if (definingClass == null)
                return false;
            if (ctor.Module == null)
                return false;
            var factory = CSharpElementFactory.GetInstance(ctor.Module);
            var ctorDecl = ctor.GetDeclarations().FirstOrDefault();
            if (ctorDecl == null)
            {
                var typeDecl = definingClass.GetDeclarations().FirstOrDefault() as IClassLikeDeclarationNode;
                if (typeDecl == null)
                    return false;
                var typeBody = typeDecl.Body;
                ctorDecl = factory.CreateTypeMemberDeclaration("public $0() {}", typeDecl.DeclaredName);
                if (typeBody.FirstChild == null)
                    return false;
                if (ctorDecl == null)
                    return false;

                ctorDecl = ModificationUtil.AddChildBefore(
                    typeBody,
                    typeBody.FirstChild.NextSibling,
                    ctorDecl.ToTreeNode()).GetContainingElement<IConstructorDeclaration>(true);
            }
            if (ctorDecl == null)
                return false;
            var type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.ToTreeNode());
            if (!type.IsResolved)
                type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.GetPsiModule());
            string recommendedName = null;
            var naming = PsiManager.GetInstance(_solution).Naming;
            if (!type.IsResolved)
            {
                var presentableName = type.GetPresentableName(CSharpLanguageService.CSHARP);
                var indexOfGeneric = presentableName.IndexOf('<');
                if(indexOfGeneric != -1)
                {
                    var interfaceName = presentableName.Substring(1, indexOfGeneric - 1);
                    var genericArgument = presentableName.Substring(indexOfGeneric).Trim('<', '>');
                    recommendedName = naming.Suggestion.GetDerivedName(
                        genericArgument + interfaceName,
                        NamedElementKinds.Parameters,
                        ScopeKind.Common,
                        CSharpLanguageService.CSHARP,
                        new SuggestionOptions());
                }
                var interfaceDecl = factory.CreateTypeMemberDeclaration("public interface IFoo {}");
                if (interfaceDecl == null)
                    return false;
                interfaceDecl.SetName(presentableName);
                interfaceDecl.LanguageService.CodeFormatter.Format(interfaceDecl.ToTreeNode(), CodeFormatProfile.GENERATOR);
                var containingType = ctor.GetContainingType();
                if (containingType == null)
                    return false;
                var containingTypeDecl = containingType.GetDeclarations().First();
                ModificationUtil.AddChildBefore(containingTypeDecl.ToTreeNode(), interfaceDecl.ToTreeNode());
            }
            type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.ToTreeNode());
            if (recommendedName == null)
            {
                var suggestionOptions = new SuggestionOptions();
                recommendedName = naming.Suggestion.GetDerivedName(
                    type.GetPresentableName(CSharpLanguageService.CSHARP),
                    NamedElementKinds.Parameters, ScopeKind.Common,
                    CSharpLanguageService.CSHARP, suggestionOptions);
            }
            var parametersOwner = ctorDecl as ICSharpParametersOwnerDeclaration;
            var references = FindReferences(parametersOwner, progressIndicator);

            if (parametersOwner == null)
                return false;
            parametersOwner.AddParameterDeclarationAfter(
                ParameterKind.VALUE, type, recommendedName,
                parametersOwner.ParameterDeclarations.LastOrDefault());

            foreach (var reference in references)
                ChangeReference(reference, recommendedName, type);

            return true;
        }
Example #26
0
        public override bool Execute(IProgressIndicator progressIndicator)
        {
            var languageService = CSharpLanguage.Instance.LanguageService();

            if (languageService == null)
            {
                return(false);
            }
            var ctor = _ctor.FindDeclaredElement();

            if (ctor == null)
            {
                return(false);
            }
            var definingClass = _class.FindDeclaredElement();

            if (definingClass == null)
            {
                return(false);
            }
            var factory  = CSharpElementFactory.GetInstance(ctor.Module);
            var ctorDecl = ctor.GetDeclarations().FirstOrDefault();

            if (ctorDecl == null)
            {
                var typeDecl = definingClass.GetDeclarations().FirstOrDefault() as IClassLikeDeclaration;
                if (typeDecl == null)
                {
                    return(false);
                }
                var typeBody = typeDecl.Body;
                ctorDecl = factory.CreateTypeMemberDeclaration("public $0() {}", typeDecl.DeclaredName);
                if (typeBody.FirstChild == null)
                {
                    return(false);
                }

                ctorDecl = ModificationUtil.AddChildBefore(
                    typeBody,
                    typeBody.FirstChild.NextSibling,
                    ctorDecl).GetContainingNode <IConstructorDeclaration>(true);
            }
            if (ctorDecl == null)
            {
                return(false);
            }
            var type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl);

            if (!type.IsResolved)
            {
                type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.GetPsiModule());
            }
            string recommendedName = null;

            if (!type.IsResolved)
            {
                var presentableName = type.GetPresentableName(CSharpLanguage.Instance);
                var indexOfGeneric  = presentableName.IndexOf('<');
                if (indexOfGeneric != -1)
                {
                    var interfaceName   = presentableName.Substring(1, indexOfGeneric - 1);
                    var genericArgument = presentableName.Substring(indexOfGeneric).Trim('<', '>');
                    recommendedName = type.GetPsiServices().Naming.Suggestion.GetDerivedName(
                        genericArgument + interfaceName,
                        NamedElementKinds.Parameters,
                        ScopeKind.Common,
                        CSharpLanguage.Instance,
                        new SuggestionOptions(),
                        ctorDecl.GetSourceFile());
                }
                var interfaceDecl = factory.CreateTypeMemberDeclaration("public interface IFoo {}");
                interfaceDecl.SetName(presentableName);
                languageService.CodeFormatter.Format(interfaceDecl, CodeFormatProfile.GENERATOR);
                var containingType = ctor.GetContainingType();
                if (containingType == null)
                {
                    return(false);
                }
                var containingTypeDecl = containingType.GetDeclarations().First();
                ModificationUtil.AddChildBefore(containingTypeDecl, interfaceDecl);
            }
            type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl);
            if (recommendedName == null)
            {
                var suggestionOptions = new SuggestionOptions();
                recommendedName = type.GetPsiServices().Naming.Suggestion.GetDerivedName(
                    type.GetPresentableName(CSharpLanguage.Instance),
                    NamedElementKinds.Parameters,
                    ScopeKind.Common,
                    CSharpLanguage.Instance,
                    suggestionOptions,
                    ctorDecl.GetSourceFile());
            }
            var parametersOwner = ctorDecl as ICSharpParametersOwnerDeclaration;
            var references      = FindReferences(parametersOwner, progressIndicator);

            if (parametersOwner == null)
            {
                return(false);
            }
            parametersOwner.AddParameterDeclarationAfter(
                ParameterKind.VALUE, type, recommendedName,
                parametersOwner.ParameterDeclarations.LastOrDefault());

            foreach (var reference in references)
            {
                ChangeReference(reference, recommendedName, type);
            }

            return(true);
        }