Search in sources :

Example 16 with SuggestedNameInfo

use of com.intellij.psi.codeStyle.SuggestedNameInfo in project intellij-community by JetBrains.

the class ExtractMethodSignatureSuggester method detectTopLevelExpressionsToReplaceWithParameters.

@Nullable
private InputVariables detectTopLevelExpressionsToReplaceWithParameters(List<PsiExpression> copies) {
    final PsiParameter[] parameters = myExtractedMethod.getParameterList().getParameters();
    final List<PsiVariable> inputVariables = new ArrayList<>(Arrays.asList(parameters));
    final PsiCodeBlock body = myExtractedMethod.getBody();
    LOG.assertTrue(body != null);
    final PsiStatement[] pattern = body.getStatements();
    final List<PsiExpression> exprs = new ArrayList<>();
    for (PsiStatement statement : pattern) {
        if (statement instanceof PsiExpressionStatement) {
            final PsiExpression expression = ((PsiExpressionStatement) statement).getExpression();
            if (expression instanceof PsiIfStatement || expression instanceof PsiLoopStatement) {
                continue;
            }
        }
        statement.accept(new JavaRecursiveElementWalkingVisitor() {

            @Override
            public void visitCallExpression(PsiCallExpression callExpression) {
                final PsiExpressionList list = callExpression.getArgumentList();
                if (list != null) {
                    for (PsiExpression expression : list.getExpressions()) {
                        if (expression instanceof PsiReferenceExpression) {
                            final PsiElement resolve = ((PsiReferenceExpression) expression).resolve();
                            if (resolve instanceof PsiField) {
                                exprs.add(expression);
                            }
                        } else {
                            exprs.add(expression);
                        }
                    }
                }
            }
        });
    }
    if (exprs.isEmpty()) {
        return null;
    }
    final UniqueNameGenerator uniqueNameGenerator = new UniqueNameGenerator();
    for (PsiParameter parameter : parameters) {
        uniqueNameGenerator.addExistingName(parameter.getName());
    }
    SyntaxTraverser.psiTraverser().withRoot(myExtractedMethod.getBody()).filter(element -> element instanceof PsiVariable).forEach(element -> uniqueNameGenerator.addExistingName(((PsiVariable) element).getName()));
    final THashMap<PsiExpression, String> unique = new THashMap<>(ourEquivalenceStrategy);
    final Map<PsiExpression, String> replacement = new HashMap<>();
    for (PsiExpression expr : exprs) {
        String name = unique.get(expr);
        if (name == null) {
            final PsiType type = GenericsUtil.getVariableTypeByExpressionType(expr.getType());
            if (type == null || type == PsiType.NULL || PsiUtil.resolveClassInType(type) instanceof PsiAnonymousClass || LambdaUtil.notInferredType(type))
                return null;
            copies.add(myElementFactory.createExpressionFromText(expr.getText(), body));
            final SuggestedNameInfo info = JavaCodeStyleManager.getInstance(myProject).suggestVariableName(VariableKind.PARAMETER, null, expr, null);
            final String paramName = info.names.length > 0 ? info.names[0] : "p";
            name = uniqueNameGenerator.generateUniqueName(paramName);
            final PsiParameter parameter = (PsiParameter) myExtractedMethod.getParameterList().add(myElementFactory.createParameter(name, type));
            inputVariables.add(parameter);
            unique.put(expr, name);
        }
        replacement.put(expr, name);
    }
    for (PsiExpression expression : replacement.keySet()) {
        expression.replace(myElementFactory.createExpressionFromText(replacement.get(expression), null));
    }
    return new InputVariables(inputVariables, myExtractedMethod.getProject(), new LocalSearchScope(myExtractedMethod), false);
}
Also used : DiffPanelOptions(com.intellij.openapi.diff.ex.DiffPanelOptions) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) java.util(java.util) ComparisonPolicy(com.intellij.openapi.diff.impl.ComparisonPolicy) THashSet(gnu.trove.THashSet) THashMap(gnu.trove.THashMap) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) VariableData(com.intellij.refactoring.util.VariableData) TObjectHashingStrategy(gnu.trove.TObjectHashingStrategy) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) SimpleContent(com.intellij.openapi.diff.SimpleContent) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) JBUI(com.intellij.util.ui.JBUI) Project(com.intellij.openapi.project.Project) PsiUtil(com.intellij.psi.util.PsiUtil) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Logger(com.intellij.openapi.diagnostic.Logger) SimpleDiffRequest(com.intellij.openapi.diff.SimpleDiffRequest) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) DuplicatesFinder(com.intellij.refactoring.util.duplicates.DuplicatesFinder) HighlightMode(com.intellij.openapi.diff.impl.processing.HighlightMode) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator) MethodDuplicatesHandler(com.intellij.refactoring.util.duplicates.MethodDuplicatesHandler) JavaPsiEquivalenceUtil(com.intellij.codeInsight.JavaPsiEquivalenceUtil) java.awt(java.awt) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) VariableKind(com.intellij.psi.codeStyle.VariableKind) RefactoringUtil(com.intellij.refactoring.util.RefactoringUtil) IdeBorderFactory(com.intellij.ui.IdeBorderFactory) ApplicationManager(com.intellij.openapi.application.ApplicationManager) com.intellij.psi(com.intellij.psi) Match(com.intellij.refactoring.util.duplicates.Match) DiffPanelEx(com.intellij.openapi.diff.ex.DiffPanelEx) DiffManager(com.intellij.openapi.diff.DiffManager) javax.swing(javax.swing) THashMap(gnu.trove.THashMap) THashMap(gnu.trove.THashMap) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator) Nullable(org.jetbrains.annotations.Nullable)

Example 17 with SuggestedNameInfo

use of com.intellij.psi.codeStyle.SuggestedNameInfo in project intellij-community by JetBrains.

the class InheritanceToDelegationDialog method updateTargetClass.

private void updateTargetClass() {
    final PsiClass targetClass = getSelectedTargetClass();
    PsiManager psiManager = myClass.getManager();
    PsiType superType = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(targetClass);
    SuggestedNameInfo suggestedNameInfo = JavaCodeStyleManager.getInstance(psiManager.getProject()).suggestVariableName(VariableKind.FIELD, null, null, superType);
    myFieldNameField.setSuggestions(suggestedNameInfo.names);
    myInnerClassNameField.getComponent().setEnabled(InheritanceToDelegationUtil.isInnerClassNeeded(myClass, targetClass));
    @NonNls final String suggestion = "My" + targetClass.getName();
    myInnerClassNameField.setSuggestions(new String[] { suggestion });
    myDataChangedListener = new NameSuggestionsField.DataChanged() {

        public void dataChanged() {
            validateButtons();
        }
    };
    myInnerClassNameField.addDataChangedListener(myDataChangedListener);
    myFieldNameField.addDataChangedListener(myDataChangedListener);
    myMemberSelectionPanel.getTable().setMemberInfos(myBasesToMemberInfos.get(targetClass));
    myMemberSelectionPanel.getTable().fireExternalDataChange();
}
Also used : NonNls(org.jetbrains.annotations.NonNls) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) NameSuggestionsField(com.intellij.refactoring.ui.NameSuggestionsField)

Example 18 with SuggestedNameInfo

use of com.intellij.psi.codeStyle.SuggestedNameInfo in project intellij-community by JetBrains.

the class MethodParameterFix method getNewParametersInfo.

@NotNull
private ParameterInfoImpl[] getNewParametersInfo(PsiMethod method) throws IncorrectOperationException {
    List<ParameterInfoImpl> result = new ArrayList<>();
    PsiParameter[] parameters = method.getParameterList().getParameters();
    PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(method.getProject());
    SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, myParameterType);
    PsiParameter newParameter = factory.createParameter(nameInfo.names[0], myParameterType);
    if (method.getContainingClass().isInterface()) {
        PsiUtil.setModifierProperty(newParameter, PsiModifier.FINAL, false);
    }
    for (int i = 0; i < parameters.length; i++) {
        PsiParameter parameter = parameters[i];
        if (i == myIndex) {
            newParameter.setName(parameter.getName());
            parameter = newParameter;
        }
        result.add(new ParameterInfoImpl(i, parameter.getName(), parameter.getType()));
    }
    if (parameters.length == myIndex) {
        result.add(new ParameterInfoImpl(-1, newParameter.getName(), newParameter.getType()));
    }
    return result.toArray(new ParameterInfoImpl[result.size()]);
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) ArrayList(java.util.ArrayList) ParameterInfoImpl(com.intellij.refactoring.changeSignature.ParameterInfoImpl) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) NotNull(org.jetbrains.annotations.NotNull)

Example 19 with SuggestedNameInfo

use of com.intellij.psi.codeStyle.SuggestedNameInfo in project intellij-community by JetBrains.

the class IntroduceVariableBase method getSuggestedName.

public static SuggestedNameInfo getSuggestedName(@Nullable PsiType type, @NotNull final PsiExpression expression, final PsiElement anchor) {
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
    final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expression, type);
    final String[] strings = JavaCompletionUtil.completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo);
    final SuggestedNameInfo.Delegate delegate = new SuggestedNameInfo.Delegate(strings, nameInfo);
    return codeStyleManager.suggestUniqueVariableName(delegate, anchor, true);
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo)

Example 20 with SuggestedNameInfo

use of com.intellij.psi.codeStyle.SuggestedNameInfo in project intellij-community by JetBrains.

the class IntroduceParameterHandler method createNameSuggestionGenerator.

protected static NameSuggestionsGenerator createNameSuggestionGenerator(final PsiExpression expr, final String propName, final Project project, final String enteredName) {
    return new NameSuggestionsGenerator() {

        public SuggestedNameInfo getSuggestedNameInfo(PsiType type) {
            final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
            SuggestedNameInfo info = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, propName, expr != null && expr.isValid() ? expr : null, type);
            if (expr != null && expr.isValid()) {
                info = codeStyleManager.suggestUniqueVariableName(info, expr, true);
            }
            final String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName(JavaCompletionUtil.completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, info), expr);
            return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays(new String[] { enteredName }, strings) : strings, info);
        }
    };
}
Also used : NameSuggestionsGenerator(com.intellij.refactoring.ui.NameSuggestionsGenerator) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo)

Aggregations

SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)40 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)22 VariableKind (com.intellij.psi.codeStyle.VariableKind)11 Nullable (org.jetbrains.annotations.Nullable)7 Project (com.intellij.openapi.project.Project)6 NotNull (org.jetbrains.annotations.NotNull)6 ArrayList (java.util.ArrayList)4 LinkedHashSet (java.util.LinkedHashSet)4 NonNls (org.jetbrains.annotations.NonNls)4 LookupElement (com.intellij.codeInsight.lookup.LookupElement)3 Editor (com.intellij.openapi.editor.Editor)3 PsiType (com.intellij.psi.PsiType)3 PreferrableNameSuggestionProvider (com.intellij.refactoring.rename.PreferrableNameSuggestionProvider)3 IncorrectOperationException (com.intellij.util.IncorrectOperationException)3 List (java.util.List)3 ApplicationManager (com.intellij.openapi.application.ApplicationManager)2 Logger (com.intellij.openapi.diagnostic.Logger)2 com.intellij.psi (com.intellij.psi)2 THashSet (gnu.trove.THashSet)2 JavaPsiEquivalenceUtil (com.intellij.codeInsight.JavaPsiEquivalenceUtil)1