use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class PsiDiamondTypeImpl method generateStaticFactory.
@Nullable
private static PsiMethod generateStaticFactory(@Nullable PsiMethod constructor, PsiClass containingClass, PsiTypeParameter[] params, PsiJavaCodeReferenceElement reference) {
final StringBuilder buf = new StringBuilder();
final String modifier = VisibilityUtil.getVisibilityModifier(constructor != null ? constructor.getModifierList() : containingClass.getModifierList());
if (!PsiModifier.PACKAGE_LOCAL.equals(modifier)) {
buf.append(modifier);
buf.append(" ");
}
buf.append("static ");
buf.append("<");
//it's possible that constructor type parameters and class type parameters are same named:
//it's important that class type parameters names are preserved(they are first in the list),
//though constructor parameters would be renamed in case of conflicts
final UniqueNameGenerator generator = new UniqueNameGenerator();
buf.append(StringUtil.join(params, psiTypeParameter -> {
String extendsList = "";
if (psiTypeParameter.getLanguage().isKindOf(JavaLanguage.INSTANCE)) {
final PsiClassType[] extendsListTypes = psiTypeParameter.getExtendsListTypes();
if (extendsListTypes.length > 0) {
final Function<PsiClassType, String> canonicalTypePresentationFun = type -> type.getCanonicalText();
extendsList = " extends " + StringUtil.join(extendsListTypes, canonicalTypePresentationFun, "&");
}
}
return generator.generateUniqueName(psiTypeParameter.getName()) + extendsList;
}, ", "));
buf.append(">");
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(containingClass.getProject());
String qualifiedName = containingClass.getQualifiedName();
PsiElement qualifier = reference != null ? reference.getQualifier() : null;
if (qualifier instanceof PsiJavaCodeReferenceElement) {
final JavaResolveResult resolveResult = ((PsiJavaCodeReferenceElement) qualifier).advancedResolve(false);
final PsiElement element = resolveResult.getElement();
if (element instanceof PsiClass) {
final String outerClassSubstitutedQName = elementFactory.createType((PsiClass) element, resolveResult.getSubstitutor()).getInternalCanonicalText();
qualifiedName = outerClassSubstitutedQName + "." + containingClass.getName();
}
} else if (reference != null && qualifier == null && containingClass.getContainingClass() != null) {
qualifiedName = null;
}
buf.append(qualifiedName != null ? qualifiedName : containingClass.getName());
final PsiTypeParameter[] parameters = containingClass.getTypeParameters();
buf.append("<");
buf.append(StringUtil.join(parameters, psiTypeParameter -> psiTypeParameter.getName(), ", "));
buf.append("> ");
String staticFactoryName = "staticFactory";
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(containingClass.getProject());
staticFactoryName = styleManager.suggestUniqueVariableName(staticFactoryName, containingClass, false);
buf.append(staticFactoryName);
if (constructor == null) {
buf.append("()");
} else {
buf.append("(").append(StringUtil.join(constructor.getParameterList().getParameters(), new Function<PsiParameter, String>() {
int myIdx;
@Override
public String fun(PsiParameter psiParameter) {
return psiParameter.getType().getCanonicalText() + " p" + myIdx++;
}
}, ",")).append(")");
}
buf.append("{}");
try {
return elementFactory.createMethodFromText(buf.toString(), constructor != null ? constructor : containingClass);
} catch (IncorrectOperationException e) {
return null;
}
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class PropertyUtil method generateSetterPrototype.
/**
* Consider using {@link com.intellij.codeInsight.generation.GenerateMembersUtil#generateSetterPrototype(com.intellij.psi.PsiField)}
* or {@link com.intellij.codeInsight.generation.GenerateMembersUtil#generateSimpleSetterPrototype(com.intellij.psi.PsiField)}
* to add @Override annotation
*/
@Nullable
public static PsiMethod generateSetterPrototype(@NotNull PsiField field, @NotNull PsiClass containingClass, boolean returnSelf) {
Project project = field.getProject();
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();
String name = field.getName();
boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
VariableKind kind = codeStyleManager.getVariableKind(field);
String propertyName = codeStyleManager.variableNameToPropertyName(name, kind);
String setName = suggestSetterName(field);
try {
PsiMethod setMethod = factory.createMethodFromText(factory.createMethod(setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID).getText(), field);
String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
PsiParameter param = factory.createParameter(parameterName, field.getType());
NullableNotNullManager.getInstance(project).copyNullableOrNotNullAnnotation(field, param);
setMethod.getParameterList().add(param);
PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true);
PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic);
@NonNls StringBuilder buffer = new StringBuilder();
buffer.append("{\n");
if (name.equals(parameterName)) {
if (!isStatic) {
buffer.append("this.");
} else {
String className = containingClass.getName();
if (className != null) {
buffer.append(className);
buffer.append(".");
}
}
}
buffer.append(name);
buffer.append("=");
buffer.append(parameterName);
buffer.append(";\n");
if (returnSelf) {
buffer.append("return this;\n");
}
buffer.append("}");
PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null);
setMethod.getBody().replace(body);
setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod);
return setMethod;
} catch (IncorrectOperationException e) {
LOG.error(e);
return null;
}
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class PropertyUtil method suggestPropertyName.
public static String suggestPropertyName(@NotNull PsiField field, @NotNull String fieldName) {
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(field.getProject());
VariableKind kind = codeStyleManager.getVariableKind(field);
String name = codeStyleManager.variableNameToPropertyName(fieldName, kind);
if (!field.hasModifierProperty(PsiModifier.STATIC) && isBoolean(field.getType())) {
if (name.startsWith(IS_PREFIX) && name.length() > IS_PREFIX.length() && Character.isUpperCase(name.charAt(IS_PREFIX.length()))) {
name = Introspector.decapitalize(name.substring(IS_PREFIX.length()));
}
}
return name;
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class FluentIterableConversionUtil method chooseName.
public static String chooseName(@NotNull PsiExpression context, @Nullable PsiType type) {
final UniqueNameGenerator nameGenerator = new UniqueNameGenerator();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(context.getProject());
final String name = codeStyleManager.suggestUniqueVariableName(codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, type).names[0], context, false);
return nameGenerator.generateUniqueName(name);
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class GuavaFluentIterableConversionRule method getOneMethodDescriptor.
@Nullable
private static TypeConversionDescriptorBase getOneMethodDescriptor(@NotNull String methodName, @NotNull PsiMethod method, @NotNull PsiType from, @Nullable PsiType to, @Nullable PsiExpression context) {
TypeConversionDescriptor descriptorBase = null;
PsiType conversionType = null;
boolean needSpecifyType = true;
if (methodName.equals("of")) {
descriptorBase = new TypeConversionDescriptor("'FluentIterable*.of($arr$)", "java.util.Arrays.stream($arr$)");
} else if (methodName.equals("from")) {
descriptorBase = new TypeConversionDescriptor("'FluentIterable*.from($it$)", null) {
@Override
public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression;
PsiExpression argument = PseudoLambdaReplaceTemplate.replaceTypeParameters(methodCall.getArgumentList().getExpressions()[0]);
if (argument == null) {
return expression;
}
boolean isCollection = InheritanceUtil.isInheritor(PsiTypesUtil.getPsiClass(argument.getType()), CommonClassNames.JAVA_UTIL_COLLECTION);
setReplaceByString(isCollection ? "($it$).stream()" : "java.util.stream.StreamSupport.stream(($it$).spliterator(), false)");
final PsiExpression replaced = super.replace(expression, evaluator);
ParenthesesUtils.removeParentheses(replaced, false);
return replaced;
}
};
} else if (methodName.equals("filter")) {
descriptorBase = FluentIterableConversionUtil.getFilterDescriptor(method, context);
} else if (methodName.equals("isEmpty")) {
descriptorBase = new TypeConversionDescriptor("$q$.isEmpty()", null) {
@Override
public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
final PsiElement parent = expression.getParent();
boolean isDoubleNegation = false;
if (parent instanceof PsiExpression && DoubleNegationInspection.isNegation((PsiExpression) parent)) {
isDoubleNegation = true;
expression = (PsiExpression) parent.replace(expression);
}
setReplaceByString((isDoubleNegation ? "" : "!") + "$q$.findAny().isPresent()");
return super.replace(expression, evaluator);
}
};
needSpecifyType = false;
} else if (methodName.equals("transformAndConcat")) {
descriptorBase = new FluentIterableConversionUtil.TransformAndConcatConversionRule();
} else if (methodName.equals("toArray")) {
descriptorBase = FluentIterableConversionUtil.getToArrayDescriptor(from, context);
needSpecifyType = false;
} else if (methodName.equals("copyInto")) {
descriptorBase = new FluentIterableConversionUtil.CopyIntoConversionDescriptor();
needSpecifyType = false;
} else if (methodName.equals("append")) {
descriptorBase = createDescriptorForAppend(method, context);
} else if (methodName.equals("get")) {
descriptorBase = new TypeConversionDescriptor("$it$.get($p$)", null) {
@Override
public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression;
final PsiExpression[] arguments = methodCall.getArgumentList().getExpressions();
setReplaceByString("$it$.skip($p$).findFirst().get()");
if (arguments.length == 1 && arguments[0] instanceof PsiLiteralExpression) {
final Object value = ((PsiLiteralExpression) arguments[0]).getValue();
if (value != null && value.equals(0)) {
setReplaceByString("$it$.findFirst().get()");
}
}
return super.replace(expression, evaluator);
}
};
needSpecifyType = false;
} else if (methodName.equals("contains")) {
descriptorBase = new TypeConversionDescriptor("$it$.contains($o$)", null) {
@Override
public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
final PsiExpression qualifier = methodCallExpression.getMethodExpression().getQualifierExpression();
LOG.assertTrue(qualifier != null);
final PsiClassType qualifierType = (PsiClassType) qualifier.getType();
LOG.assertTrue(qualifierType != null);
final PsiType[] parameters = qualifierType.getParameters();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
final SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, parameters.length == 1 ? parameters[0] : null, false);
final String suggestedName = codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, expression, false).names[0];
setReplaceByString("$it$.anyMatch(" + suggestedName + " -> java.util.Objects.equals(" + suggestedName + ", $o$))");
return super.replace(expression, evaluator);
}
};
needSpecifyType = false;
} else if (methodName.equals("last")) {
descriptorBase = new TypeConversionDescriptor("$it$.last()", null) {
@Override
public PsiExpression replace(PsiExpression expression, @NotNull TypeEvaluator evaluator) {
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
String varA = suggestName("a", codeStyleManager, expression);
String varB = suggestName("b", codeStyleManager, expression);
setReplaceByString("$it$.reduce((" + varA + ", " + varB + ") -> " + varB + ")");
return super.replace(expression, evaluator);
}
private String suggestName(String baseName, JavaCodeStyleManager codeStyleManager, PsiElement place) {
final SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, baseName, null, null, false);
return codeStyleManager.suggestUniqueVariableName(suggestedNameInfo, place, false).names[0];
}
};
} else {
final TypeConversionDescriptorFactory base = DESCRIPTORS_MAP.get(methodName);
if (base != null) {
final TypeConversionDescriptor descriptor = base.create();
needSpecifyType = base.isChainedMethod();
if (needSpecifyType && !base.isFluentIterableReturnType()) {
conversionType = GuavaConversionUtil.addTypeParameters(GuavaOptionalConversionRule.JAVA_OPTIONAL, context.getType(), context);
}
descriptorBase = descriptor;
}
}
if (descriptorBase == null) {
return FluentIterableConversionUtil.createToCollectionDescriptor(methodName, context);
}
if (needSpecifyType) {
if (conversionType == null) {
PsiMethodCallExpression methodCall = (PsiMethodCallExpression) (context instanceof PsiMethodCallExpression ? context : context.getParent());
conversionType = GuavaConversionUtil.addTypeParameters(GuavaTypeConversionDescriptor.isIterable(methodCall) ? CommonClassNames.JAVA_LANG_ITERABLE : StreamApiConstants.JAVA_UTIL_STREAM_STREAM, context.getType(), context);
}
descriptorBase.withConversionType(conversionType);
}
return descriptorBase;
}
Aggregations