static String suggestUniqueParameterName( JavaCodeStyleManager codeStyleManager, PsiExpression expression, PsiType exprType, Set<String> existingNames) { SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, expression, exprType); @NonNls String[] names = nameInfo.names; if (expression instanceof PsiReferenceExpression) { final PsiElement resolve = ((PsiReferenceExpression) expression).resolve(); if (resolve instanceof PsiVariable) { final VariableKind variableKind = codeStyleManager.getVariableKind((PsiVariable) resolve); final String propertyName = codeStyleManager.variableNameToPropertyName( ((PsiVariable) resolve).getName(), variableKind); final String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); names = ArrayUtil.mergeArrays(new String[] {parameterName}, names); } } if (names.length == 0) names = new String[] {"param"}; int suffix = 0; while (true) { for (String name : names) { String suggested = name + (suffix == 0 ? "" : String.valueOf(suffix)); if (existingNames.add(suggested)) { return suggested; } } suffix++; } }
private static boolean shouldRenameSetterParameter( JavaCodeStyleManager manager, String propertyName, PsiMethod setter) { boolean shouldRenameSetterParameter; String parameterName = manager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiParameter setterParameter = setter.getParameterList().getParameters()[0]; shouldRenameSetterParameter = parameterName.equals(setterParameter.getName()); return shouldRenameSetterParameter; }
public static PsiMethod generateSetterPrototype( PsiField field, final 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(project, field); try { PsiMethod setMethod = factory.createMethod( setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID); String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiParameter param = factory.createParameter(parameterName, field.getType()); annotateWithNullableStuff(field, factory, param); setMethod.getParameterList().add(param); PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic); @NonNls StringBuffer buffer = new StringBuffer(); 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; } }
private PsiMethod generateMethodPrototype(PsiField field) { Project project = field.getProject(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); String propertyName = codeStyleManager.variableNameToPropertyName( field.getName(), codeStyleManager.getVariableKind(field)); String methodName = methodNameGenerator.generateMethodNameFor(propertyName); String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiMethod withMethod = generateMethodFor(field, methodName, parameterName, elementFactory); generateMethodBodyFor(withMethod, propertyName, parameterName, elementFactory); return withMethod; }
public static void addGetterOrSetterWithParameter( @NotNull PsiMethod methodPrototype, @NotNull String newName, @Nullable String newPropertyName, @NotNull String oldParameterName, @NotNull JavaCodeStyleManager manager, @NotNull Map<PsiElement, String> allRenames) { allRenames.put(methodPrototype, newName); if (newPropertyName != null) { final PsiParameter[] parameters = methodPrototype.getParameterList().getParameters(); LOG.assertTrue(parameters.length > 0, methodPrototype.getName()); PsiParameter parameter = parameters[0]; if (shouldRenameSetterParameter(manager, oldParameterName, methodPrototype)) { allRenames.put( parameter, manager.propertyNameToVariableName(newPropertyName, VariableKind.PARAMETER)); } } }
public static PsiMethod generateConstructorPrototype( PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields) throws IncorrectOperationException { PsiManager manager = aClass.getManager(); JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject()); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject()); PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass); String modifier = PsiUtil.getMaximumModifierForMember(aClass, false); if (modifier != null) { PsiUtil.setModifierProperty(constructor, modifier, true); } 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(), baseConstructor.getProject()) .createClass("Dummy"); baseConstructor = (PsiMethod) dummyClass.add(baseConstructor); } PsiParameter[] params = baseConstructor.getParameterList().getParameters(); for (PsiParameter param : params) { PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass); GenerateMembersUtil.copyOrReplaceModifierList(param, newParam); constructor.getParameterList().add(newParam); } } } JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject()); final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName()); dummyConstructor.getParameterList().replace(constructor.getParameterList().copy()); List<PsiParameter> fieldParams = new ArrayList<PsiParameter>(); for (PsiField field : fields) { String fieldName = field.getName(); 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); final NullableNotNullManager nullableManager = NullableNotNullManager.getInstance(field.getProject()); final String notNull = nullableManager.getNotNull(field); if (notNull != null) { parm.getModifierList() .addAfter(factory.createAnnotationFromText("@" + notNull, field), null); } constructor.getParameterList().add(parm); dummyConstructor.getParameterList().add(parm.copy()); fieldParams.add(parm); } ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage()); if (generator != null) { @NonNls StringBuilder buffer = new StringBuilder(); generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY); if (isNotEnum) { generator.generateSuperCallIfNeeded( buffer, baseConstructor.getParameterList().getParameters()); } generator.generateFieldInitialization( buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()])); generator.finish(buffer); PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass); constructor.getBody().replace(stub.getBody()); } constructor = (PsiMethod) codeStyleManager.reformat(constructor); return constructor; }
private static void prepareFieldRenaming( PsiField field, String newName, final Map<PsiElement, String> allRenames) { // search for getters/setters PsiClass aClass = field.getContainingClass(); Project project = field.getProject(); final JavaCodeStyleManager manager = JavaCodeStyleManager.getInstance(project); final String propertyName = PropertyUtil.suggestPropertyName(field, field.getName()); final String newPropertyName = PropertyUtil.suggestPropertyName(field, newName); boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); PsiMethod[] getters = GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic); PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false); boolean shouldRenameSetterParameter = false; if (setter != null) { shouldRenameSetterParameter = shouldRenameSetterParameter(manager, propertyName, setter); } if (getters != null) { List<PsiMethod> validGetters = new ArrayList<>(); for (PsiMethod getter : getters) { String newGetterName = GetterSetterPrototypeProvider.suggestNewGetterName( propertyName, newPropertyName, getter); String getterId = null; if (newGetterName == null) { getterId = getter.getName(); newGetterName = PropertyUtil.suggestGetterName(newPropertyName, field.getType(), getterId); } if (newGetterName.equals(getterId)) { continue; } else { boolean valid = true; for (PsiMethod method : getter.findDeepestSuperMethods()) { if (method instanceof PsiCompiledElement) { valid = false; break; } } if (!valid) continue; } validGetters.add(getter); } getters = validGetters.isEmpty() ? null : validGetters.toArray(new PsiMethod[validGetters.size()]); } String newSetterName = ""; if (setter != null) { newSetterName = PropertyUtil.suggestSetterName(newPropertyName); final String newSetterParameterName = manager.propertyNameToVariableName(newPropertyName, VariableKind.PARAMETER); if (newSetterName.equals(setter.getName())) { setter = null; newSetterName = null; shouldRenameSetterParameter = false; } else if (newSetterParameterName.equals( setter.getParameterList().getParameters()[0].getName())) { shouldRenameSetterParameter = false; } else { for (PsiMethod method : setter.findDeepestSuperMethods()) { if (method instanceof PsiCompiledElement) { setter = null; shouldRenameSetterParameter = false; break; } } } } if ((getters != null || setter != null) && askToRenameAccesors(getters != null ? getters[0] : null, setter, newName, project)) { getters = null; setter = null; shouldRenameSetterParameter = false; } if (getters != null) { for (PsiMethod getter : getters) { String newGetterName = GetterSetterPrototypeProvider.suggestNewGetterName( propertyName, newPropertyName, getter); if (newGetterName == null) { newGetterName = PropertyUtil.suggestGetterName(newPropertyName, field.getType(), getter.getName()); } addOverriddenAndImplemented(getter, newGetterName, null, propertyName, manager, allRenames); } } if (setter != null) { addOverriddenAndImplemented( setter, newSetterName, shouldRenameSetterParameter ? newPropertyName : null, propertyName, manager, allRenames); } }
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { if (!myField.isValid()) return; // weird. should not get here when field becomes invalid final Collection<PsiReference> refs = ReferencesSearch.search(myField).findAll(); if (refs.isEmpty()) return; Set<PsiReference> refsSet = new HashSet<PsiReference>(refs); PsiCodeBlock anchorBlock = findAnchorBlock(refs); if (anchorBlock == null) return; // was assert, but need to fix the case when obsolete inspection highlighting is // left if (!CodeInsightUtil.preparePsiElementsForWrite(anchorBlock)) return; final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); final String propertyName = styleManager.variableNameToPropertyName(myField.getName(), VariableKind.FIELD); String localName = styleManager.propertyNameToVariableName(propertyName, VariableKind.LOCAL_VARIABLE); localName = RefactoringUtil.suggestUniqueVariableName(localName, anchorBlock, myField); PsiElement firstElement = getFirstElement(refs); boolean mayBeFinal = mayBeFinal(refsSet, firstElement); PsiElement newDeclaration = null; try { final PsiElement anchor = getAnchorElement(anchorBlock, firstElement); if (anchor instanceof PsiExpressionStatement && ((PsiExpressionStatement) anchor).getExpression() instanceof PsiAssignmentExpression) { final PsiAssignmentExpression expression = (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression(); if (expression.getOperationTokenType() == JavaTokenType.EQ && expression.getLExpression() instanceof PsiReferenceExpression && ((PsiReference) expression.getLExpression()).isReferenceTo(myField)) { final PsiExpression initializer = expression.getRExpression(); final PsiDeclarationStatement decl = elementFactory.createVariableDeclarationStatement( localName, myField.getType(), initializer); if (!mayBeFinal) { PsiUtil.setModifierProperty( ((PsiModifierListOwner) decl.getDeclaredElements()[0]), PsiModifier.FINAL, false); } newDeclaration = anchor.replace(decl); refsSet.remove(expression.getLExpression()); retargetReferences(elementFactory, localName, refsSet); } else { newDeclaration = addDeclarationWithFieldInitializerAndRetargetReferences( elementFactory, localName, anchorBlock, anchor, refsSet); } } else { newDeclaration = addDeclarationWithFieldInitializerAndRetargetReferences( elementFactory, localName, anchorBlock, anchor, refsSet); } } catch (IncorrectOperationException e) { LOG.error(e); } if (newDeclaration != null) { final PsiFile psiFile = myField.getContainingFile(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null && IJSwingUtilities.hasFocus(editor.getComponent())) { final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == psiFile) { editor.getCaretModel().moveToOffset(newDeclaration.getTextOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } } try { myField.normalizeDeclaration(); myField.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } }