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);
}
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"));
}
}
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;
}
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();
}
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;
}
Aggregations