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++; } }
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; } }
@Nullable private static String getLookupObjectName(Object o) { if (o instanceof PsiVariable) { final PsiVariable variable = (PsiVariable) o; JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(variable.getProject()); VariableKind variableKind = codeStyleManager.getVariableKind(variable); return codeStyleManager.variableNameToPropertyName(variable.getName(), variableKind); } if (o instanceof PsiMethod) { return ((PsiMethod) o).getName(); } 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; }
private static String getUniqueParameterName( PsiParameter[] parameters, PsiVariable variable, HashMap<PsiField, String> usedNames) { final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(variable.getProject()); final SuggestedNameInfo nameInfo = styleManager.suggestVariableName( VariableKind.PARAMETER, styleManager.variableNameToPropertyName(variable.getName(), VariableKind.FIELD), null, variable.getType()); String newName = nameInfo.names[0]; int n = 1; while (true) { if (isUnique(parameters, newName, usedNames)) { break; } newName = nameInfo.names[0] + n++; } return newName; }
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; }
public static String suggestPropertyName(Project project, PsiField field) { JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); VariableKind kind = codeStyleManager.getVariableKind(field); return codeStyleManager.variableNameToPropertyName(field.getName(), kind); }
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); } }