use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class JavaIntroduceVariableTest method doTest.
protected static void doTest(String expression, VariableKind kind, PsiType type, String... results) throws Exception {
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(getProject());
final PsiExpression expr = factory.createExpressionFromText(expression, null);
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(getProject());
final SuggestedNameInfo info = codeStyleManager.suggestVariableName(kind, null, expr, type);
assert info.names.length >= results.length : msg("Can't find some variants", info.names, results);
for (int i = 0; i < results.length; i++) {
if (!results[i].equals(info.names[i])) {
throw new Exception(msg("", info.names, results));
}
}
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class GenerateConstructorHandler method generateConstructorPrototype.
public static PsiMethod generateConstructorPrototype(PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields) throws IncorrectOperationException {
PsiManager manager = aClass.getManager();
Project project = aClass.getProject();
JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), project);
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
String className = aClass.getName();
assert className != null : aClass;
PsiMethod constructor = factory.createConstructor(className, aClass);
GenerateMembersUtil.setVisibility(aClass, constructor);
if (baseConstructor != null) {
PsiJavaCodeReferenceElement[] throwRefs = baseConstructor.getThrowsList().getReferenceElements();
for (PsiJavaCodeReferenceElement ref : throwRefs) {
constructor.getThrowsList().add(ref);
}
if (copyJavaDoc) {
final PsiDocComment docComment = ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
if (docComment != null) {
constructor.addAfter(docComment, null);
}
}
}
boolean isNotEnum = false;
if (baseConstructor != null) {
PsiClass superClass = aClass.getSuperClass();
LOG.assertTrue(superClass != null);
if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
isNotEnum = true;
if (baseConstructor instanceof PsiCompiledElement) {
// to get some parameter names
PsiClass dummyClass = JVMElementFactories.requireFactory(baseConstructor.getLanguage(), project).createClass("Dummy");
baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
}
PsiParameter[] params = baseConstructor.getParameterList().getParameters();
for (PsiParameter param : params) {
String name = param.getName();
assert name != null : param;
PsiParameter newParam = factory.createParameter(name, param.getType(), aClass);
GenerateMembersUtil.copyOrReplaceModifierList(param, aClass, newParam);
constructor.getParameterList().add(newParam);
}
}
}
JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(project);
final PsiMethod dummyConstructor = factory.createConstructor(className);
dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
List<PsiParameter> fieldParams = new ArrayList<>();
for (PsiField field : fields) {
String fieldName = field.getName();
assert fieldName != null : field;
String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);
NullableNotNullManager.getInstance(project).copyNotNullAnnotation(field, parm);
if (constructor.isVarArgs()) {
final PsiParameterList parameterList = constructor.getParameterList();
parameterList.addBefore(parm, parameterList.getParameters()[parameterList.getParametersCount() - 1]);
final PsiParameterList dummyParameterList = dummyConstructor.getParameterList();
dummyParameterList.addBefore(parm.copy(), dummyParameterList.getParameters()[dummyParameterList.getParametersCount() - 1]);
} else {
constructor.getParameterList().add(parm);
dummyConstructor.getParameterList().add(parm.copy());
}
fieldParams.add(parm);
}
ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
if (generator != null) {
StringBuilder buffer = new StringBuilder();
generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
if (isNotEnum) {
generator.generateSuperCallIfNeeded(buffer, baseConstructor.getParameterList().getParameters());
}
final PsiParameter[] parameters = fieldParams.toArray(new PsiParameter[fieldParams.size()]);
final List<String> existingNames = ContainerUtil.map(dummyConstructor.getParameterList().getParameters(), parameter -> parameter.getName());
if (generator instanceof ConstructorBodyGeneratorEx) {
((ConstructorBodyGeneratorEx) generator).generateFieldInitialization(buffer, fields, parameters, existingNames);
} else {
generator.generateFieldInitialization(buffer, fields, parameters);
}
generator.finish(buffer);
PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
PsiCodeBlock original = constructor.getBody(), replacement = stub.getBody();
assert original != null : constructor;
assert replacement != null : stub;
original.replace(replacement);
}
constructor = (PsiMethod) codeStyleManager.reformat(constructor);
return constructor;
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class ExtractMethodObjectProcessor method createField.
private PsiField createField(PsiParameter parameter, PsiMethod constructor, boolean isFinal) {
final String parameterName = parameter.getName();
PsiType type = parameter.getType();
if (type instanceof PsiEllipsisType)
type = ((PsiEllipsisType) type).toArrayType();
try {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(getMethod().getProject());
final String fieldName = styleManager.suggestVariableName(VariableKind.FIELD, styleManager.variableNameToPropertyName(parameterName, VariableKind.PARAMETER), null, type).names[0];
PsiField field = myElementFactory.createField(fieldName, type);
final PsiModifierList modifierList = field.getModifierList();
LOG.assertTrue(modifierList != null);
final NullableNotNullManager manager = NullableNotNullManager.getInstance(myProject);
if (manager.isNullable(parameter, false)) {
modifierList.addAfter(myElementFactory.createAnnotationFromText("@" + manager.getDefaultNullable(), field), null);
}
modifierList.setModifierProperty(PsiModifier.FINAL, isFinal);
final PsiCodeBlock methodBody = constructor.getBody();
LOG.assertTrue(methodBody != null);
@NonNls final String stmtText;
if (Comparing.strEqual(parameterName, fieldName)) {
stmtText = "this." + fieldName + " = " + parameterName + ";";
} else {
stmtText = fieldName + " = " + parameterName + ";";
}
PsiStatement assignmentStmt = myElementFactory.createStatementFromText(stmtText, methodBody);
assignmentStmt = (PsiStatement) CodeStyleManager.getInstance(constructor.getProject()).reformat(assignmentStmt);
methodBody.add(assignmentStmt);
field = (PsiField) myInnerClass.add(field);
return field;
} catch (IncorrectOperationException e) {
LOG.error(e);
}
return null;
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class DefaultQuickFixProvider method registerPriorityActions.
private static void registerPriorityActions(@NotNull QuickFixActionRegistrar registrar, @NotNull TextRange fixRange, @NotNull PsiReferenceExpression refExpr) {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject());
final Map<VariableKind, IntentionAction> map = new EnumMap<>(VariableKind.class);
map.put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr));
map.put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr));
if (!refExpr.isQualified()) {
map.put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr));
map.put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr));
}
final VariableKind kind = getKind(styleManager, refExpr);
if (map.containsKey(kind)) {
map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind)));
}
for (IntentionAction action : map.values()) {
registrar.register(fixRange, action, null);
}
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class AddExceptionToCatchFix method addCatchStatement.
private static PsiCodeBlock addCatchStatement(PsiTryStatement tryStatement, PsiClassType exceptionType, PsiFile file) throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getInstance(tryStatement.getProject()).getElementFactory();
if (tryStatement.getTryBlock() == null) {
addTryBlock(tryStatement, factory);
}
JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(tryStatement.getProject());
String name = styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, exceptionType).names[0];
name = styleManager.suggestUniqueVariableName(name, tryStatement, false);
PsiCatchSection catchSection = factory.createCatchSection(exceptionType, name, file);
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock == null) {
tryStatement.add(catchSection);
} else {
tryStatement.addBefore(catchSection, getFinallySectionStart(finallyBlock));
}
PsiParameter[] parameters = tryStatement.getCatchBlockParameters();
PsiTypeElement typeElement = parameters[parameters.length - 1].getTypeElement();
if (typeElement != null) {
JavaCodeStyleManager.getInstance(file.getProject()).shortenClassReferences(typeElement);
}
PsiCodeBlock[] catchBlocks = tryStatement.getCatchBlocks();
return catchBlocks[catchBlocks.length - 1];
}
Aggregations