Search in sources :

Example 1 with UniqueNameGenerator

use of com.intellij.util.text.UniqueNameGenerator 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 2 with UniqueNameGenerator

use of com.intellij.util.text.UniqueNameGenerator in project intellij-community by JetBrains.

the class MigrationMapSet method saveMaps.

public void saveMaps() throws IOException {
    File dir = getMapDirectory();
    if (dir == null) {
        return;
    }
    File[] files = getMapFiles(dir);
    @NonNls String[] filePaths = new String[myMaps.size()];
    Document[] documents = new Document[myMaps.size()];
    UniqueNameGenerator namesProvider = new UniqueNameGenerator();
    for (int i = 0; i < myMaps.size(); i++) {
        MigrationMap map = myMaps.get(i);
        filePaths[i] = dir + File.separator + namesProvider.generateUniqueName(map.getFileName()) + ".xml";
        documents[i] = saveMap(map);
    }
    JDOMUtil.updateFileSet(files, filePaths, documents, CodeStyleSettingsManager.getSettings(null).getLineSeparator());
    if (!myDeletedMaps.isEmpty()) {
        FileUtil.writeToFile(new File(dir, "deleted.txt"), StringUtil.join(myDeletedMaps, "\n"));
    }
}
Also used : NonNls(org.jetbrains.annotations.NonNls) Document(org.jdom.Document) File(java.io.File) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator)

Example 3 with UniqueNameGenerator

use of com.intellij.util.text.UniqueNameGenerator in project intellij-community by JetBrains.

the class MainConfigurationStateSplitter method splitState.

@Override
public final List<Pair<Element, String>> splitState(@NotNull Element state) {
    UniqueNameGenerator generator = new UniqueNameGenerator();
    List<Pair<Element, String>> result = new SmartList<>();
    for (Iterator<Element> iterator = state.getChildren(getSubStateTagName()).iterator(); iterator.hasNext(); ) {
        Element element = iterator.next();
        iterator.remove();
        result.add(createItem(getSubStateFileName(element), generator, element));
    }
    if (!JDOMUtil.isEmpty(state)) {
        result.add(createItem(getComponentStateFileName(), generator, state));
    }
    return result;
}
Also used : Element(org.jdom.Element) SmartList(com.intellij.util.SmartList) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator) Pair(com.intellij.openapi.util.Pair)

Example 4 with UniqueNameGenerator

use of com.intellij.util.text.UniqueNameGenerator in project intellij-community by JetBrains.

the class LambdaRefactoringUtil method createLambdaWithoutFormalParameters.

private static String createLambdaWithoutFormalParameters(PsiMethodReferenceExpression referenceExpression) {
    PsiType functionalInterfaceType = referenceExpression.getFunctionalInterfaceType();
    final PsiElement resolve = referenceExpression.resolve();
    if (resolve == null) {
        return null;
    }
    final PsiClassType.ClassResolveResult functionalInterfaceResolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
    final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
    if (interfaceMethod == null) {
        return null;
    }
    final PsiSubstitutor psiSubstitutor = LambdaUtil.getSubstitutor(interfaceMethod, functionalInterfaceResolveResult);
    final MethodSignature signature = interfaceMethod.getSignature(psiSubstitutor);
    final boolean isReceiver;
    if (resolve instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) resolve;
        isReceiver = PsiMethodReferenceUtil.isResolvedBySecondSearch(referenceExpression, signature, method.isVarArgs(), method.hasModifierProperty(PsiModifier.STATIC), method.getParameterList().getParametersCount());
    } else {
        isReceiver = false;
    }
    final PsiParameter[] psiParameters = resolve instanceof PsiMethod ? ((PsiMethod) resolve).getParameterList().getParameters() : null;
    final PsiParameterList parameterList = interfaceMethod.getParameterList();
    final PsiParameter[] parameters = parameterList.getParameters();
    final Map<PsiParameter, String> map = new HashMap<>();
    final UniqueNameGenerator nameGenerator = new UniqueNameGenerator();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(referenceExpression.getProject());
    Function<PsiParameter, String> paramPresentationFunction = parameter -> {
        final int parameterIndex = parameterList.getParameterIndex(parameter);
        String baseName;
        if (isReceiver && parameterIndex == 0) {
            final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType()));
            baseName = nameInfo.names.length > 0 ? nameInfo.names[0] : parameter.getName();
        } else {
            String initialName;
            if (psiParameters != null) {
                final int idx = parameterIndex - (isReceiver ? 1 : 0);
                initialName = psiParameters.length > 0 ? psiParameters[idx < psiParameters.length ? idx : psiParameters.length - 1].getName() : parameter.getName();
            } else {
                initialName = parameter.getName();
            }
            LOG.assertTrue(initialName != null);
            if ("_".equals(initialName)) {
                SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType()));
                if (nameInfo.names.length > 0) {
                    initialName = nameInfo.names[0];
                }
            }
            baseName = codeStyleManager.variableNameToPropertyName(initialName, VariableKind.PARAMETER);
        }
        if (baseName != null) {
            String parameterName = nameGenerator.generateUniqueName(codeStyleManager.suggestUniqueVariableName(baseName, referenceExpression, true));
            map.put(parameter, parameterName);
            return parameterName;
        }
        return "";
    };
    StringBuilder buf = new StringBuilder();
    if (parameters.length == 1) {
        buf.append(paramPresentationFunction.fun(parameters[0]));
    } else {
        buf.append("(").append(StringUtil.join(parameters, paramPresentationFunction, ", ")).append(")");
    }
    buf.append(" -> ");
    final JavaResolveResult resolveResult = referenceExpression.advancedResolve(false);
    final PsiElement resolveElement = resolveResult.getElement();
    if (resolveElement instanceof PsiMember) {
        final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(referenceExpression.getProject());
        buf.append("{");
        if (!PsiType.VOID.equals(interfaceMethod.getReturnType())) {
            buf.append("return ");
        }
        final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(referenceExpression);
        final PsiElement qualifier = referenceExpression.getQualifier();
        PsiClass containingClass = qualifierResolveResult.getContainingClass();
        final boolean onArrayRef = elementFactory.getArrayClass(PsiUtil.getLanguageLevel(referenceExpression)) == containingClass;
        final PsiElement referenceNameElement = referenceExpression.getReferenceNameElement();
        if (isReceiver) {
            buf.append(map.get(parameters[0])).append(".");
        } else {
            if (!(referenceNameElement instanceof PsiKeyword)) {
                if (qualifier instanceof PsiTypeElement) {
                    final PsiJavaCodeReferenceElement referenceElement = ((PsiTypeElement) qualifier).getInnermostComponentReferenceElement();
                    LOG.assertTrue(referenceElement != null);
                    if (!PsiTreeUtil.isAncestor(containingClass, referenceExpression, false)) {
                        buf.append(referenceElement.getReferenceName()).append(".");
                    }
                } else if (qualifier != null && !isQualifierUnnecessary(qualifier, containingClass)) {
                    buf.append(qualifier.getText()).append(".");
                }
            }
        }
        //new or method name
        buf.append(referenceExpression.getReferenceName());
        if (referenceNameElement instanceof PsiKeyword) {
            //class name
            buf.append(" ");
            if (onArrayRef) {
                if (qualifier instanceof PsiTypeElement) {
                    final PsiType type = ((PsiTypeElement) qualifier).getType();
                    int dim = type.getArrayDimensions();
                    buf.append(type.getDeepComponentType().getCanonicalText());
                    buf.append("[");
                    buf.append(map.get(parameters[0]));
                    buf.append("]");
                    while (--dim > 0) {
                        buf.append("[]");
                    }
                }
            } else {
                buf.append(((PsiMember) resolveElement).getName());
                final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
                LOG.assertTrue(containingClass != null);
                if (containingClass.hasTypeParameters() && !PsiUtil.isRawSubstitutor(containingClass, substitutor)) {
                    buf.append("<").append(StringUtil.join(containingClass.getTypeParameters(), parameter -> {
                        final PsiType psiType = substitutor.substitute(parameter);
                        LOG.assertTrue(psiType != null);
                        return psiType.getCanonicalText();
                    }, ", ")).append(">");
                }
            }
        }
        if (!onArrayRef || isReceiver) {
            //param list
            buf.append("(");
            boolean first = true;
            for (int i = isReceiver ? 1 : 0; i < parameters.length; i++) {
                PsiParameter parameter = parameters[i];
                if (!first) {
                    buf.append(", ");
                } else {
                    first = false;
                }
                buf.append(map.get(parameter));
            }
            buf.append(")");
        }
        buf.append(";}");
    }
    return buf.toString();
}
Also used : PsiTypesUtil(com.intellij.psi.util.PsiTypesUtil) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) IntroduceVariableHandler(com.intellij.refactoring.introduceVariable.IntroduceVariableHandler) ElementToWorkOn(com.intellij.refactoring.introduceField.ElementToWorkOn) HashMap(java.util.HashMap) SideEffectChecker(com.siyeh.ig.psiutils.SideEffectChecker) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) ArrayList(java.util.ArrayList) DefaultParameterTypeInferencePolicy(com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) Map(java.util.Map) PsiUtil(com.intellij.psi.util.PsiUtil) Messages(com.intellij.openapi.ui.Messages) Logger(com.intellij.openapi.diagnostic.Logger) StringUtil(com.intellij.openapi.util.text.StringUtil) MethodCandidateInfo(com.intellij.psi.infos.MethodCandidateInfo) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator) Editor(com.intellij.openapi.editor.Editor) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) MethodSignature(com.intellij.psi.util.MethodSignature) VariableKind(com.intellij.psi.codeStyle.VariableKind) RedundantLambdaCodeBlockInspection(com.intellij.codeInspection.RedundantLambdaCodeBlockInspection) Function(com.intellij.util.Function) ApplicationManager(com.intellij.openapi.application.ApplicationManager) FunctionalInterfaceParameterizationUtil(com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) HashMap(java.util.HashMap) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) MethodSignature(com.intellij.psi.util.MethodSignature) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator)

Example 5 with UniqueNameGenerator

use of com.intellij.util.text.UniqueNameGenerator in project intellij-community by JetBrains.

the class GenerateMembersUtil method overriddenParameters.

public static PsiParameter[] overriddenParameters(PsiParameter[] parameters, @NotNull JVMElementFactory factory, @NotNull JavaCodeStyleManager codeStyleManager, @NotNull PsiSubstitutor substitutor, PsiElement target) {
    PsiParameter[] result = new PsiParameter[parameters.length];
    UniqueNameGenerator generator = new UniqueNameGenerator();
    for (int i = 0; i < parameters.length; i++) {
        PsiParameter parameter = parameters[i];
        final PsiType parameterType = parameter.getType();
        final PsiType substituted = substituteType(substitutor, parameterType, (PsiMethod) parameter.getDeclarationScope());
        String paramName = parameter.getName();
        boolean isBaseNameGenerated = true;
        final boolean isSubstituted = substituted.equals(parameterType);
        if (!isSubstituted && isBaseNameGenerated(codeStyleManager, TypeConversionUtil.erasure(parameterType), paramName)) {
            isBaseNameGenerated = false;
        }
        if (paramName == null || isBaseNameGenerated && !isSubstituted && isBaseNameGenerated(codeStyleManager, parameterType, paramName) || !factory.isValidParameterName(paramName)) {
            String[] names = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, substituted).names;
            if (names.length > 0) {
                paramName = generator.generateUniqueName(names[0]);
            } else {
                paramName = generator.generateUniqueName("p");
            }
        } else if (!generator.value(paramName)) {
            paramName = generator.generateUniqueName(paramName);
        }
        generator.addExistingName(paramName);
        result[i] = factory.createParameter(paramName, GenericsUtil.getVariableTypeByExpressionType(substituted), target);
    }
    return result;
}
Also used : UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator)

Aggregations

UniqueNameGenerator (com.intellij.util.text.UniqueNameGenerator)10 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)4 Logger (com.intellij.openapi.diagnostic.Logger)3 NotNull (org.jetbrains.annotations.NotNull)3 ApplicationManager (com.intellij.openapi.application.ApplicationManager)2 Project (com.intellij.openapi.project.Project)2 Pair (com.intellij.openapi.util.Pair)2 StringUtil (com.intellij.openapi.util.text.StringUtil)2 com.intellij.psi (com.intellij.psi)2 SuggestedNameInfo (com.intellij.psi.codeStyle.SuggestedNameInfo)2 VariableKind (com.intellij.psi.codeStyle.VariableKind)2 MethodCandidateInfo (com.intellij.psi.infos.MethodCandidateInfo)2 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)2 PsiUtil (com.intellij.psi.util.PsiUtil)2 VariableData (com.intellij.refactoring.util.VariableData)2 Function (com.intellij.util.Function)2 SmartList (com.intellij.util.SmartList)2 Element (org.jdom.Element)2 Nullable (org.jetbrains.annotations.Nullable)2 JavaPsiEquivalenceUtil (com.intellij.codeInsight.JavaPsiEquivalenceUtil)1