private void getVariantsFromQualifier(@NotNull GrExpression qualifier) { Project project = qualifier.getProject(); PsiType qualifierType = qualifier.getType(); final ResolveState state = ResolveState.initial(); if (qualifierType == null || qualifierType == PsiType.VOID) { if (qualifier instanceof GrReferenceExpression) { PsiElement resolved = ((GrReferenceExpression) qualifier).resolve(); if (resolved instanceof PsiPackage || resolved instanceof PsiVariable) { resolved.processDeclarations(myProcessor, state, null, myRefExpr); return; } } getVariantsFromQualifierType(TypesUtil.getJavaLangObject(qualifier), project); } else if (qualifierType instanceof PsiIntersectionType) { for (PsiType conjunct : ((PsiIntersectionType) qualifierType).getConjuncts()) { getVariantsFromQualifierType(conjunct, project); } } else if (qualifierType instanceof GrTraitType) { GrTypeDefinition definition = ((GrTraitType) qualifierType).getMockTypeDefinition(); if (definition != null) { PsiClassType classType = JavaPsiFacade.getElementFactory(project).createType(definition); getVariantsFromQualifierType(classType, project); } else { getVariantsFromQualifierType(((GrTraitType) qualifierType).getExprType(), project); for (PsiClassType traitType : ((GrTraitType) qualifierType).getTraitTypes()) { getVariantsFromQualifierType(traitType, project); } } } else { getVariantsFromQualifierType(qualifierType, project); if (qualifier instanceof GrReferenceExpression && !PsiUtil.isSuperReference(qualifier) && !PsiUtil.isInstanceThisRef(qualifier)) { PsiElement resolved = ((GrReferenceExpression) qualifier).resolve(); if (resolved instanceof PsiClass) { // //omitted .class GlobalSearchScope scope = myRefExpr.getResolveScope(); PsiClass javaLangClass = PsiUtil.getJavaLangClass(resolved, scope); if (javaLangClass != null) { PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; PsiTypeParameter[] typeParameters = javaLangClass.getTypeParameters(); if (typeParameters.length == 1) { substitutor = substitutor.put(typeParameters[0], qualifierType); } PsiType javaLangClassType = JavaPsiFacade.getElementFactory(myRefExpr.getProject()) .createType(javaLangClass, substitutor); ResolveUtil.processAllDeclarations(javaLangClassType, myProcessor, state, myRefExpr); } } } } }
private void doMoveClass(PsiSubstitutor substitutor, MemberInfo info) { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); PsiClass aClass = (PsiClass) info.getMember(); if (Boolean.FALSE.equals(info.getOverrides())) { final PsiReferenceList sourceReferenceList = info.getSourceReferenceList(); LOG.assertTrue(sourceReferenceList != null); PsiJavaCodeReferenceElement ref = mySourceClass.equals(sourceReferenceList.getParent()) ? RefactoringUtil.removeFromReferenceList(sourceReferenceList, aClass) : RefactoringUtil.findReferenceToClass(sourceReferenceList, aClass); if (ref != null && !myTargetSuperClass.isInheritor(aClass, false)) { RefactoringUtil.replaceMovedMemberTypeParameters( ref, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory); final PsiReferenceList referenceList = myIsTargetInterface ? myTargetSuperClass.getExtendsList() : myTargetSuperClass.getImplementsList(); assert referenceList != null; referenceList.add(ref); } } else { RefactoringUtil.replaceMovedMemberTypeParameters( aClass, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory); fixReferencesToStatic(aClass); final PsiMember movedElement = (PsiMember) myTargetSuperClass.add( convertClassToLanguage(aClass, myTargetSuperClass.getLanguage())); myMembersAfterMove.add(movedElement); aClass.delete(); } }
private static PsiSubstitutor obtainFinalSubstitutor( PsiClass superClass, PsiSubstitutor superSubstitutor, PsiSubstitutor derivedSubstitutor, boolean inRawContext) { if (inRawContext) { Set<PsiTypeParameter> typeParams = superSubstitutor.getSubstitutionMap().keySet(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(superClass.getProject()); superSubstitutor = factory.createRawSubstitutor( derivedSubstitutor, typeParams.toArray(new PsiTypeParameter[typeParams.size()])); } Map<PsiTypeParameter, PsiType> map = null; for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(superClass)) { PsiType type = superSubstitutor.substitute(typeParameter); final PsiType t = derivedSubstitutor.substitute(type); if (map == null) { map = new THashMap<PsiTypeParameter, PsiType>(); } map.put(typeParameter, t); } return map == null ? PsiSubstitutor.EMPTY : JavaPsiFacade.getInstance(superClass.getProject()) .getElementFactory() .createSubstitutor(map); }
private static void addDefaultConstructor( JavaChangeInfo changeInfo, PsiClass aClass, final UsageInfo[] usages) throws IncorrectOperationException { if (!(aClass instanceof PsiAnonymousClass)) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(aClass.getProject()); PsiMethod defaultConstructor = factory.createMethodFromText(aClass.getName() + "(){}", aClass); defaultConstructor = (PsiMethod) CodeStyleManager.getInstance(aClass.getProject()).reformat(defaultConstructor); defaultConstructor = (PsiMethod) aClass.add(defaultConstructor); PsiUtil.setModifierProperty( defaultConstructor, VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true); addSuperCall(changeInfo, defaultConstructor, null, usages); } else { final PsiElement parent = aClass.getParent(); if (parent instanceof PsiNewExpression) { final PsiExpressionList argumentList = ((PsiNewExpression) parent).getArgumentList(); final PsiClass baseClass = changeInfo.getMethod().getContainingClass(); final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY); fixActualArgumentsList(argumentList, changeInfo, true, substitutor); } } }
private static PsiAnnotationMemberValue[] readFromClass( @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) { PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName); PsiType fromClassType = fromClassAttr instanceof PsiClassObjectAccessExpression ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType() : null; PsiClass fromClass = fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null; if (fromClass == null) return null; String fqn = fromClass.getQualifiedName(); if (fqn == null) return null; List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>(); for (PsiField field : fromClass.getFields()) { if (!field.hasModifierProperty(PsiModifier.PUBLIC) || !field.hasModifierProperty(PsiModifier.STATIC) || !field.hasModifierProperty(PsiModifier.FINAL)) continue; PsiType fieldType = field.getType(); if (!Comparing.equal(fieldType, type)) continue; PsiAssignmentExpression e = (PsiAssignmentExpression) JavaPsiFacade.getElementFactory(field.getProject()) .createExpressionFromText("x=" + fqn + "." + field.getName(), field); PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression(); constants.add(refToField); } if (constants.isEmpty()) return null; return constants.toArray(new PsiAnnotationMemberValue[constants.size()]); }
@NotNull private static PsiSubstitutor replaceVariables(Collection<InferenceVariable> inferenceVariables) { final List<InferenceVariable> targetVars = new ArrayList<InferenceVariable>(); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; final InferenceVariable[] oldVars = inferenceVariables.toArray(new InferenceVariable[inferenceVariables.size()]); for (InferenceVariable variable : oldVars) { final InferenceVariable newVariable = new InferenceVariable( variable.getCallContext(), variable.getParameter(), variable.getName()); substitutor = substitutor.put( variable, JavaPsiFacade.getElementFactory(variable.getProject()).createType(newVariable)); targetVars.add(newVariable); if (variable.isThrownBound()) { newVariable.setThrownBound(); } } for (int i = 0; i < targetVars.size(); i++) { InferenceVariable var = targetVars.get(i); for (InferenceBound boundType : InferenceBound.values()) { for (PsiType bound : oldVars[i].getBounds(boundType)) { var.addBound(substitutor.substitute(bound), boundType, null); } } } return substitutor; }
private static boolean canBePrivate( PsiMethod method, Collection<PsiReference> references, Collection<? extends PsiElement> deleted, final PsiElement[] allElementsToDelete) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { return false; } PsiManager manager = method.getManager(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject()); final PsiElementFactory factory = facade.getElementFactory(); final PsiModifierList privateModifierList; try { final PsiMethod newMethod = factory.createMethod("x3", PsiType.VOID); privateModifierList = newMethod.getModifierList(); privateModifierList.setModifierProperty(PsiModifier.PRIVATE, true); } catch (IncorrectOperationException e) { LOG.assertTrue(false); return false; } for (PsiReference reference : references) { final PsiElement element = reference.getElement(); if (!isInside(element, allElementsToDelete) && !isInside(element, deleted) && !facade .getResolveHelper() .isAccessible(method, privateModifierList, element, null, null)) { return false; } } return true; }
private static void notNull(Project project, PsiField field, PsiParameter parameter) { final String notNull = NullableNotNullManager.getInstance(field.getProject()).getNotNull(field); if (notNull != null) { final PsiAnnotation annotation = JavaPsiFacade.getElementFactory(project).createAnnotationFromText("@" + notNull, field); parameter.getModifierList().addBefore(annotation, null); } }
private static boolean changeClassTypeArgument( PsiMethod myMethod, Project project, PsiType superReturnType, PsiClass superClass, Editor editor, PsiType returnType) { if (superClass == null || !superClass.hasTypeParameters()) return true; final PsiClass superReturnTypeClass = PsiUtil.resolveClassInType(superReturnType); if (superReturnTypeClass == null || !(superReturnTypeClass instanceof PsiTypeParameter || superReturnTypeClass.hasTypeParameters())) return true; final PsiClass derivedClass = myMethod.getContainingClass(); if (derivedClass == null) return true; final PsiReferenceParameterList referenceParameterList = findTypeArgumentsList(superClass, derivedClass); if (referenceParameterList == null) return true; final PsiElement resolve = ((PsiJavaCodeReferenceElement) referenceParameterList.getParent()).resolve(); if (!(resolve instanceof PsiClass)) return true; final PsiClass baseClass = (PsiClass) resolve; if (returnType instanceof PsiPrimitiveType) { returnType = ((PsiPrimitiveType) returnType).getBoxedType(derivedClass); } final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, baseClass, PsiSubstitutor.EMPTY); final PsiType superReturnTypeInBaseClassType = superClassSubstitutor.substitute(superReturnType); final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(project).getResolveHelper(); final PsiSubstitutor psiSubstitutor = resolveHelper.inferTypeArguments( PsiTypesUtil.filterUnusedTypeParameters( superReturnTypeInBaseClassType, baseClass.getTypeParameters()), new PsiType[] {superReturnTypeInBaseClassType}, new PsiType[] {returnType}, PsiUtil.getLanguageLevel(superClass)); final TypeMigrationRules rules = new TypeMigrationRules(); final PsiSubstitutor compoundSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, derivedClass, PsiSubstitutor.EMPTY) .putAll(psiSubstitutor); rules.setBoundScope(new LocalSearchScope(derivedClass)); TypeMigrationProcessor.runHighlightingTypeMigration( project, editor, rules, referenceParameterList, JavaPsiFacade.getElementFactory(project).createType(baseClass, compoundSubstitutor)); return false; }
private static void generateDelegate(JavaChangeInfo changeInfo) throws IncorrectOperationException { final PsiMethod delegate = (PsiMethod) changeInfo.getMethod().copy(); final PsiClass targetClass = changeInfo.getMethod().getContainingClass(); LOG.assertTrue(!targetClass.isInterface()); PsiElementFactory factory = JavaPsiFacade.getElementFactory(targetClass.getProject()); ChangeSignatureProcessor.makeEmptyBody(factory, delegate); final PsiCallExpression callExpression = ChangeSignatureProcessor.addDelegatingCallTemplate(delegate, changeInfo.getNewName()); addDelegateArguments(changeInfo, factory, callExpression); targetClass.addBefore(delegate, changeInfo.getMethod()); }
@Override public void visitSuperExpression(PsiSuperExpression expression) { super.visitSuperExpression(expression); final PsiJavaCodeReferenceElement qualifier = expression.getQualifier(); if (qualifier != null && qualifier.isReferenceTo(mySourceClass)) { try { expression.replace( JavaPsiFacade.getElementFactory(myProject) .createExpressionFromText(myTargetSuperClass.getName() + ".this", null)); } catch (IncorrectOperationException e) { LOG.error(e); } } }
private static PsiExpression getLiteralExpression( PsiExpression context, PsiManager manager, @NotNull String text) { Map<String, PsiExpression> cache = LITERAL_EXPRESSION_CACHE.get(manager); if (cache == null) { cache = new ConcurrentSoftValueHashMap<String, PsiExpression>(); cache = manager.putUserDataIfAbsent(LITERAL_EXPRESSION_CACHE, cache); } PsiExpression expression = cache.get(text); if (expression == null) { expression = JavaPsiFacade.getElementFactory(manager.getProject()) .createExpressionFromText(text, context); cache.put(text, expression); } return expression; }
@Override public DfaInstructionState[] visitAssign( AssignInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) { final Instruction nextInstruction = runner.getInstruction(instruction.getIndex() + 1); final DfaValue dfaSource = memState.pop(); final DfaValue dfaDest = memState.pop(); if (dfaDest instanceof DfaVariableValue) { DfaVariableValue var = (DfaVariableValue) dfaDest; final PsiExpression rightValue = instruction.getRExpression(); final PsiElement parent = rightValue == null ? null : rightValue.getParent(); final IElementType type = parent instanceof PsiAssignmentExpression ? ((PsiAssignmentExpression) parent).getOperationTokenType() : JavaTokenType.EQ; // store current value - to use in case of '+=' final PsiExpression prevValue = ((ValuableDataFlowRunner.ValuableDfaVariableState) ((ValuableDataFlowRunner.MyDfaMemoryState) memState).getVariableState(var)) .myExpression; memState.setVarValue(var, dfaSource); // state may have been changed so re-retrieve it final ValuableDataFlowRunner.ValuableDfaVariableState curState = (ValuableDataFlowRunner.ValuableDfaVariableState) ((ValuableDataFlowRunner.MyDfaMemoryState) memState).getVariableState(var); final PsiExpression curValue = curState.myExpression; final PsiExpression nextValue; if (type == JavaTokenType.PLUSEQ && prevValue != null) { PsiExpression tmpExpression; try { tmpExpression = JavaPsiFacade.getElementFactory(myContext.getProject()) .createExpressionFromText( prevValue.getText() + "+" + rightValue.getText(), rightValue); } catch (Exception e) { tmpExpression = curValue == null ? rightValue : curValue; } nextValue = tmpExpression; } else { nextValue = curValue == null ? rightValue : curValue; } curState.myExpression = nextValue; } memState.push(dfaDest); return new DfaInstructionState[] {new DfaInstructionState(nextInstruction, memState)}; }
private static void fixExceptions(PsiElement ref, PsiClassType[] newExceptions) throws IncorrectOperationException { // methods' throws lists are already modified, may use ExceptionUtil.collectUnhandledExceptions newExceptions = filterCheckedExceptions(newExceptions); PsiElement context = PsiTreeUtil.getParentOfType(ref, PsiTryStatement.class, PsiMethod.class); if (context instanceof PsiTryStatement) { PsiTryStatement tryStatement = (PsiTryStatement) context; PsiCodeBlock tryBlock = tryStatement.getTryBlock(); // Remove unused catches Collection<PsiClassType> classes = ExceptionUtil.collectUnhandledExceptions(tryBlock, tryBlock); PsiParameter[] catchParameters = tryStatement.getCatchBlockParameters(); for (PsiParameter parameter : catchParameters) { final PsiType caughtType = parameter.getType(); if (!(caughtType instanceof PsiClassType)) continue; if (ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType) caughtType)) continue; if (!isCatchParameterRedundant((PsiClassType) caughtType, classes)) continue; parameter.getParent().delete(); // delete catch section } PsiClassType[] exceptionsToAdd = filterUnhandledExceptions(newExceptions, tryBlock); addExceptions(exceptionsToAdd, tryStatement); adjustPossibleEmptyTryStatement(tryStatement); } else { newExceptions = filterUnhandledExceptions(newExceptions, ref); if (newExceptions.length > 0) { // Add new try statement PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(ref.getProject()); PsiTryStatement tryStatement = (PsiTryStatement) elementFactory.createStatementFromText("try {} catch (Exception e) {}", null); PsiStatement anchor = PsiTreeUtil.getParentOfType(ref, PsiStatement.class); LOG.assertTrue(anchor != null); tryStatement.getTryBlock().add(anchor); tryStatement = (PsiTryStatement) anchor.getParent().addAfter(tryStatement, anchor); addExceptions(newExceptions, tryStatement); anchor.delete(); tryStatement.getCatchSections()[0].delete(); // Delete dummy catch section } } }
private class ExplicitSuperDeleter extends JavaRecursiveElementWalkingVisitor { private final PsiExpression myThisExpression = JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("this", null); @Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (expression.getQualifierExpression() instanceof PsiSuperExpression) { PsiElement resolved = expression.resolve(); if (resolved == null || resolved instanceof PsiMethod && shouldFixSuper((PsiMethod) resolved)) { expression.getQualifierExpression().delete(); } } } @Override public void visitSuperExpression(PsiSuperExpression expression) { expression.replace(myThisExpression); } @Override public void visitClass(PsiClass aClass) { // do nothing } private boolean shouldFixSuper(PsiMethod method) { for (PsiMember element : myMembersAfterMove) { if (element instanceof PsiMethod) { PsiMethod member = (PsiMethod) element; // if there is such member among moved members, super qualifier // should not be removed final PsiManager manager = method.getManager(); if (manager.areElementsEquivalent( member.getContainingClass(), method.getContainingClass()) && MethodSignatureUtil.areSignaturesEqual(member, method)) { return false; } } } final PsiMethod methodFromSuper = myTargetSuperClass.findMethodBySignature(method, false); return methodFromSuper == null; } }
@Nullable public static PsiType getQualifiedMemberReferenceType( @Nullable PsiType qualifierType, @NotNull final PsiMember member) { final Ref<PsiSubstitutor> subst = Ref.create(PsiSubstitutor.EMPTY); class MyProcessor extends BaseScopeProcessor implements NameHint, ElementClassHint { @Override public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) { if (element == member) { subst.set(state.get(PsiSubstitutor.KEY)); } return true; } @Override public String getName(@NotNull ResolveState state) { return member.getName(); } @Override public boolean shouldProcess(DeclarationKind kind) { return member instanceof PsiEnumConstant ? kind == DeclarationKind.ENUM_CONST : member instanceof PsiField ? kind == DeclarationKind.FIELD : kind == DeclarationKind.METHOD; } @Override public <T> T getHint(@NotNull Key<T> hintKey) { return hintKey == NameHint.KEY || hintKey == ElementClassHint.KEY ? (T) this : null; } } PsiScopesUtil.processTypeDeclarations(qualifierType, member, new MyProcessor()); PsiType rawType = member instanceof PsiField ? ((PsiField) member).getType() : member instanceof PsiMethod ? ((PsiMethod) member).getReturnType() : JavaPsiFacade.getElementFactory(member.getProject()) .createType((PsiClass) member); return subst.get().substitute(rawType); }
public static void addImportIfNeeded(@NotNull PsiClass aClass, @NotNull PsiElement context) { final PsiFile file = context.getContainingFile(); if (!(file instanceof PsiJavaFile)) { return; } final PsiJavaFile javaFile = (PsiJavaFile) file; final PsiClass outerClass = aClass.getContainingClass(); if (outerClass == null) { if (PsiTreeUtil.isAncestor(javaFile, aClass, true)) { return; } } else if (PsiTreeUtil.isAncestor(outerClass, context, true)) { final PsiElement brace = outerClass.getLBrace(); if (brace != null && brace.getTextOffset() < context.getTextOffset()) { return; } } final String qualifiedName = aClass.getQualifiedName(); if (qualifiedName == null) { return; } final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return; } final String containingPackageName = javaFile.getPackageName(); @NonNls final String packageName = ClassUtil.extractPackageName(qualifiedName); if (containingPackageName.equals(packageName) || importList.findSingleClassImportStatement(qualifiedName) != null) { return; } if (importList.findOnDemandImportStatement(packageName) != null && !hasDefaultImportConflict(qualifiedName, javaFile) && !hasOnDemandImportConflict(qualifiedName, javaFile)) { return; } final Project project = importList.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); final PsiImportStatement importStatement = elementFactory.createImportStatement(aClass); importList.add(importStatement); }
private PsiSubstitutor upDownSuperClassSubstitutor() { PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; for (PsiTypeParameter parameter : PsiUtil.typeParametersIterable(mySourceClass)) { substitutor = substitutor.put(parameter, null); } final Map<PsiTypeParameter, PsiType> substitutionMap = TypeConversionUtil.getSuperClassSubstitutor( myTargetSuperClass, mySourceClass, PsiSubstitutor.EMPTY) .getSubstitutionMap(); for (PsiTypeParameter parameter : substitutionMap.keySet()) { final PsiType type = substitutionMap.get(parameter); final PsiClass resolvedClass = PsiUtil.resolveClassInType(type); if (resolvedClass instanceof PsiTypeParameter) { substitutor = substitutor.put( (PsiTypeParameter) resolvedClass, JavaPsiFacade.getElementFactory(myProject).createType(parameter)); } } return substitutor; }
private static void addSuperCall( JavaChangeInfo changeInfo, PsiMethod constructor, PsiMethod callee, final UsageInfo[] usages) throws IncorrectOperationException { final PsiElementFactory factory = JavaPsiFacade.getElementFactory(constructor.getProject()); PsiExpressionStatement superCall = (PsiExpressionStatement) factory.createStatementFromText("super();", constructor); PsiCodeBlock body = constructor.getBody(); assert body != null; PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { superCall = (PsiExpressionStatement) body.addBefore(superCall, statements[0]); } else { superCall = (PsiExpressionStatement) body.add(superCall); } PsiMethodCallExpression callExpression = (PsiMethodCallExpression) superCall.getExpression(); final PsiClass aClass = constructor.getContainingClass(); final PsiClass baseClass = changeInfo.getMethod().getContainingClass(); final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY); processMethodUsage( callExpression.getMethodExpression(), changeInfo, true, false, callee, substitutor, usages); }
private void addMethodConflicts(MultiMap<PsiElement, String> conflicts) { String newMethodName = myChangeInfo.getNewName(); if (!(myChangeInfo instanceof JavaChangeInfo)) { return; } try { PsiMethod prototype; final PsiMethod method = myChangeInfo.getMethod(); if (!StdLanguages.JAVA.equals(method.getLanguage())) return; PsiManager manager = method.getManager(); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final CanonicalTypes.Type returnType = myChangeInfo.getNewReturnType(); if (returnType != null) { prototype = factory.createMethod(newMethodName, returnType.getType(method, manager)); } else { prototype = factory.createConstructor(); prototype.setName(newMethodName); } JavaParameterInfo[] parameters = myChangeInfo.getNewParameters(); for (JavaParameterInfo info : parameters) { PsiType parameterType = info.createType(method, manager); if (parameterType == null) { parameterType = JavaPsiFacade.getElementFactory(method.getProject()) .createTypeFromText(CommonClassNames.JAVA_LANG_OBJECT, method); } PsiParameter param = factory.createParameter(info.getName(), parameterType); prototype.getParameterList().add(param); } ConflictsUtil.checkMethodConflicts( method.getContainingClass(), method, prototype, conflicts); } catch (IncorrectOperationException e) { LOG.error(e); } }
private void doMoveField(PsiSubstitutor substitutor, MemberInfo info) { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); PsiField field = (PsiField) info.getMember(); if (field instanceof HaxeVarDeclarationPart) { field = (HaxeVarDeclaration) field.getParent(); } field.normalizeDeclaration(); RefactoringUtil.replaceMovedMemberTypeParameters( field, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory); fixReferencesToStatic(field); if (myIsTargetInterface) { PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true); } final PsiMember movedElement = (PsiMember) myTargetSuperClass.addBefore( convertFieldToLanguage(field, myTargetSuperClass.getLanguage()), myTargetSuperClass.getRBrace()); myMembersAfterMove.add(movedElement); field.delete(); }
public static Set<LookupElement> processJavaReference( PsiElement element, PsiJavaReference javaReference, ElementFilter elementFilter, JavaCompletionProcessor.Options options, final PrefixMatcher matcher, CompletionParameters parameters) { final Set<LookupElement> set = new LinkedHashSet<LookupElement>(); final Condition<String> nameCondition = new Condition<String>() { @Override public boolean value(String s) { return matcher.prefixMatches(s); } }; PsiMethodCallExpression call = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class); boolean checkInitialized = parameters.getInvocationCount() <= 1 && call != null && PsiKeyword.SUPER.equals(call.getMethodExpression().getText()); final JavaCompletionProcessor processor = new JavaCompletionProcessor( element, elementFilter, options.withInitialized(checkInitialized), nameCondition); final PsiType plainQualifier = processor.getQualifierType(); PsiType qualifierType = plainQualifier; PsiType runtimeQualifier = getQualifierCastType(javaReference, parameters); if (runtimeQualifier != null) { PsiType composite = qualifierType == null ? runtimeQualifier : PsiIntersectionType.createIntersection(qualifierType, runtimeQualifier); PsiElement ctx = createContextWithXxxVariable(element, composite); javaReference = (PsiReferenceExpression) JavaPsiFacade.getElementFactory(element.getProject()) .createExpressionFromText("xxx.xxx", ctx); qualifierType = runtimeQualifier; processor.setQualifierType(qualifierType); } javaReference.processVariants(processor); final PsiTypeLookupItem castItem = runtimeQualifier == null ? null : PsiTypeLookupItem.createLookupItem( runtimeQualifier, (PsiReferenceExpression) javaReference); final boolean pkgContext = inSomePackage(element); final Set<PsiMember> mentioned = new THashSet<PsiMember>(); for (CompletionElement completionElement : processor.getResults()) { for (LookupElement item : createLookupElements(completionElement, javaReference)) { item.putUserData(QUALIFIER_TYPE_ATTR, qualifierType); final Object o = item.getObject(); if (o instanceof PsiClass && !isSourceLevelAccessible(element, (PsiClass) o, pkgContext)) { continue; } if (o instanceof PsiMember) { if (isInExcludedPackage((PsiMember) o, true)) { continue; } mentioned.add(CompletionUtil.getOriginalOrSelf((PsiMember) o)); } set.add( highlightIfNeeded( qualifierType, castQualifier(item, castItem, plainQualifier, processor), o, element)); } } if (javaReference instanceof PsiJavaCodeReferenceElement && !((PsiJavaCodeReferenceElement) javaReference).isQualified()) { final StaticMemberProcessor memberProcessor = new JavaStaticMemberProcessor(parameters); memberProcessor.processMembersOfRegisteredClasses( matcher, new PairConsumer<PsiMember, PsiClass>() { @Override public void consume(PsiMember member, PsiClass psiClass) { if (!mentioned.contains(member) && processor.satisfies(member, ResolveState.initial())) { set.add(memberProcessor.createLookupElement(member, psiClass, true)); } } }); } return set; }
public static boolean processDeclarations( @NotNull GrTypeDefinition grType, @NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { if (place instanceof GrCodeReferenceElement && lastParent instanceof GrModifierList) { final PsiElement possibleAnnotation = PsiTreeUtil.skipParentsOfType(place, GrCodeReferenceElement.class); if (possibleAnnotation instanceof GrAnnotation && possibleAnnotation.getParent() == lastParent) { return true; // don't process class members while resolving annotation which annotates // current class } } for (final PsiTypeParameter typeParameter : grType.getTypeParameters()) { if (!processElement(processor, typeParameter, state)) return false; } NameHint nameHint = processor.getHint(NameHint.KEY); String name = nameHint == null ? null : nameHint.getName(state); ClassHint classHint = processor.getHint(ClassHint.KEY); final PsiSubstitutor substitutor = state.get(PsiSubstitutor.KEY); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getProject()); boolean processInstanceMethods = (shouldProcessMethods(classHint) || shouldProcessProperties(classHint)) && shouldProcessInstanceMembers(grType, lastParent); LanguageLevel level = PsiUtil.getLanguageLevel(place); if (shouldProcessProperties(classHint)) { Map<String, CandidateInfo> fieldsMap = CollectClassMembersUtil.getAllFields(grType); if (name != null) { CandidateInfo fieldInfo = fieldsMap.get(name); if (fieldInfo != null) { if (!processField( grType, processor, state, place, processInstanceMethods, substitutor, factory, level, fieldInfo)) { return false; } } else if (grType.isTrait() && lastParent != null) { PsiField field = findFieldByName(grType, name, false, true); if (field != null && field.hasModifierProperty(PsiModifier.PUBLIC)) { if (!processField( grType, processor, state, place, processInstanceMethods, substitutor, factory, level, new CandidateInfo(field, PsiSubstitutor.EMPTY))) { return false; } } } } else { for (CandidateInfo info : fieldsMap.values()) { if (!processField( grType, processor, state, place, processInstanceMethods, substitutor, factory, level, info)) { return false; } } if (grType.isTrait() && lastParent != null) { for (PsiField field : CollectClassMembersUtil.getFields(grType, true)) { if (field.hasModifierProperty(PsiModifier.PUBLIC)) { if (!processField( grType, processor, state, place, processInstanceMethods, substitutor, factory, level, new CandidateInfo(field, PsiSubstitutor.EMPTY))) { return false; } } } } } } if (shouldProcessMethods(classHint)) { Map<String, List<CandidateInfo>> methodsMap = CollectClassMembersUtil.getAllMethods(grType, true); boolean isPlaceGroovy = place.getLanguage() == GroovyFileType.GROOVY_LANGUAGE; if (name == null) { for (List<CandidateInfo> list : methodsMap.values()) { for (CandidateInfo info : list) { if (!processMethod( grType, processor, state, place, processInstanceMethods, substitutor, factory, level, isPlaceGroovy, info)) { return false; } } } } else { List<CandidateInfo> byName = methodsMap.get(name); if (byName != null) { for (CandidateInfo info : byName) { if (!processMethod( grType, processor, state, place, processInstanceMethods, substitutor, factory, level, isPlaceGroovy, info)) { return false; } } } } } final GrTypeDefinitionBody body = grType.getBody(); if (body != null) { if (shouldProcessClasses(classHint)) { for (PsiClass innerClass : getInnerClassesForResolve(grType, lastParent, place)) { final String innerClassName = innerClass.getName(); if (nameHint != null && !innerClassName.equals(nameHint.getName(state))) { continue; } if (!processor.execute(innerClass, state)) { return false; } } } } return true; }
private static AllowedValues parseBeanInfo(@NotNull PsiModifierListOwner owner) { PsiMethod method = null; if (owner instanceof PsiParameter) { PsiParameter parameter = (PsiParameter) owner; PsiElement scope = parameter.getDeclarationScope(); if (!(scope instanceof PsiMethod)) return null; PsiElement nav = scope.getNavigationElement(); if (!(nav instanceof PsiMethod)) return null; method = (PsiMethod) nav; if (method.isConstructor()) { // not a property, try the @ConstructorProperties({"prop"}) PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, "java.beans.ConstructorProperties"); if (annotation == null) return null; PsiAnnotationMemberValue value = annotation.findAttributeValue("value"); if (!(value instanceof PsiArrayInitializerMemberValue)) return null; PsiAnnotationMemberValue[] initializers = ((PsiArrayInitializerMemberValue) value).getInitializers(); PsiElement parent = parameter.getParent(); if (!(parent instanceof PsiParameterList)) return null; int index = ((PsiParameterList) parent).getParameterIndex(parameter); if (index >= initializers.length) return null; PsiAnnotationMemberValue initializer = initializers[index]; if (!(initializer instanceof PsiLiteralExpression)) return null; Object val = ((PsiLiteralExpression) initializer).getValue(); if (!(val instanceof String)) return null; PsiMethod setter = PropertyUtil.findPropertySetter( method.getContainingClass(), (String) val, false, false); if (setter == null) return null; // try the @beaninfo of the corresponding setter method = (PsiMethod) setter.getNavigationElement(); } } else if (owner instanceof PsiMethod) { PsiElement nav = owner.getNavigationElement(); if (!(nav instanceof PsiMethod)) return null; method = (PsiMethod) nav; } if (method == null) return null; PsiClass aClass = method.getContainingClass(); if (aClass == null) return null; if (PropertyUtil.isSimplePropertyGetter(method)) { List<PsiMethod> setters = PropertyUtil.getSetters(aClass, PropertyUtil.getPropertyNameByGetter(method)); if (setters.size() != 1) return null; method = setters.get(0); } if (!PropertyUtil.isSimplePropertySetter(method)) return null; PsiDocComment doc = method.getDocComment(); if (doc == null) return null; PsiDocTag beaninfo = doc.findTagByName("beaninfo"); if (beaninfo == null) return null; String data = StringUtil.join( beaninfo.getDataElements(), new Function<PsiElement, String>() { @Override public String fun(PsiElement element) { return element.getText(); } }, "\n"); int enumIndex = StringUtil.indexOfSubstringEnd(data, "enum:"); if (enumIndex == -1) return null; data = data.substring(enumIndex); int colon = data.indexOf(":"); int last = colon == -1 ? data.length() : data.substring(0, colon).lastIndexOf("\n"); data = data.substring(0, last); List<PsiAnnotationMemberValue> values = new ArrayList<PsiAnnotationMemberValue>(); for (String line : StringUtil.splitByLines(data)) { List<String> words = StringUtil.split(line, " ", true, true); if (words.size() != 2) continue; String ref = words.get(1); PsiExpression constRef = JavaPsiFacade.getElementFactory(aClass.getProject()) .createExpressionFromText(ref, aClass); if (!(constRef instanceof PsiReferenceExpression)) continue; PsiReferenceExpression expr = (PsiReferenceExpression) constRef; values.add(expr); } if (values.isEmpty()) return null; PsiAnnotationMemberValue[] array = values.toArray(new PsiAnnotationMemberValue[values.size()]); return new AllowedValues(array, false); }
private static boolean addParameterToConstructor( final Project project, final PsiFile file, final Editor editor, final PsiMethod constructor, final PsiField[] fields) throws IncorrectOperationException { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); ParameterInfoImpl[] newParamInfos = new ParameterInfoImpl[parameters.length + fields.length]; final List<PsiVariable> params = new ArrayList<PsiVariable>(Arrays.asList(parameters)); Collections.addAll(params, fields); Collections.sort(params, new FieldParameterComparator(parameterList)); int i = 0; final HashMap<PsiField, String> usedFields = new HashMap<PsiField, String>(); for (PsiVariable param : params) { final PsiType paramType = param.getType(); if (param instanceof PsiParameter) { newParamInfos[i++] = new ParameterInfoImpl( parameterList.getParameterIndex((PsiParameter) param), param.getName(), paramType, param.getName()); } else { final String uniqueParameterName = getUniqueParameterName(parameters, param, usedFields); usedFields.put((PsiField) param, uniqueParameterName); newParamInfos[i++] = new ParameterInfoImpl(-1, uniqueParameterName, paramType, uniqueParameterName); } } final SmartPointerManager manager = SmartPointerManager.getInstance(project); final SmartPsiElementPointer constructorPointer = manager.createSmartPsiElementPointer(constructor); final PsiMethod fromText = JavaPsiFacade.getElementFactory(project) .createMethodFromText(createDummyMethod(constructor, newParamInfos), constructor); final PsiClass containingClass = constructor.getContainingClass(); if (containingClass == null) return false; final int minUsagesNumber = containingClass.findMethodsBySignature(fromText, false).length > 0 ? 0 : 1; final List<ParameterInfoImpl> parameterInfos = ChangeMethodSignatureFromUsageFix.performChange( project, editor, file, constructor, minUsagesNumber, newParamInfos, true, true); final ParameterInfoImpl[] resultParams = parameterInfos != null ? parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()]) : newParamInfos; return ApplicationManager.getApplication() .runWriteAction( new Computable<Boolean>() { @Override public Boolean compute() { return doCreate( project, editor, parameters, constructorPointer, resultParams, usedFields); } }); }
private void doMoveMethod(PsiSubstitutor substitutor, MemberInfo info) { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); PsiMethod method = (PsiMethod) info.getMember(); PsiMethod sibling = method; PsiMethod anchor = null; while (sibling != null) { sibling = PsiTreeUtil.getNextSiblingOfType(sibling, PsiMethod.class); if (sibling != null) { anchor = MethodSignatureUtil.findMethodInSuperClassBySignatureInDerived( method.getContainingClass(), myTargetSuperClass, sibling.getSignature(PsiSubstitutor.EMPTY), false); if (anchor != null) { break; } } } PsiMethod methodCopy = (PsiMethod) method.copy(); Language language = myTargetSuperClass.getLanguage(); final PsiMethod superClassMethod = myTargetSuperClass.findMethodBySignature(methodCopy, false); if (superClassMethod != null && superClassMethod.findDeepestSuperMethods().length == 0 || method.findSuperMethods(myTargetSuperClass).length == 0) { deleteOverrideAnnotationIfFound(methodCopy); } boolean isOriginalMethodAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT) || method.hasModifierProperty(PsiModifier.DEFAULT); boolean isOriginalMethodPrototype = method instanceof HaxeFunctionPrototypeDeclarationWithAttributes; if (myIsTargetInterface || info.isToAbstract()) { ChangeContextUtil.clearContextInfo(method); if (!info.isToAbstract() && !method.hasModifierProperty(PsiModifier.ABSTRACT) && PsiUtil.isLanguageLevel8OrHigher(myTargetSuperClass)) { // pull as default RefactoringUtil.makeMethodDefault(methodCopy); isOriginalMethodAbstract = true; } else { RefactoringUtil.makeMethodAbstract(myTargetSuperClass, methodCopy); } RefactoringUtil.replaceMovedMemberTypeParameters( methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory); myJavaDocPolicy.processCopiedJavaDoc( methodCopy.getDocComment(), method.getDocComment(), isOriginalMethodAbstract); final PsiMember movedElement; if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { movedElement = (PsiMember) superClassMethod.replace(convertMethodToLanguage(methodCopy, language)); } else { methodCopy = HaxeElementGenerator.createFunctionPrototypeDeclarationWithAttributes( myProject, methodCopy.getText().trim() + ";"); movedElement = anchor != null ? (PsiMember) myTargetSuperClass.addBefore(methodCopy, anchor) : (PsiMember) myTargetSuperClass.addBefore(methodCopy, myTargetSuperClass.getRBrace()); reformat(movedElement); } CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(method.getProject()); if (styleSettings.INSERT_OVERRIDE_ANNOTATION) { if (PsiUtil.isLanguageLevel5OrHigher(mySourceClass) && !myIsTargetInterface || PsiUtil.isLanguageLevel6OrHigher(mySourceClass)) { new AddAnnotationFix(Override.class.getName(), method) .invoke(method.getProject(), null, mySourceClass.getContainingFile()); } } if (!PsiUtil.isLanguageLevel6OrHigher(mySourceClass) && myIsTargetInterface) { if (isOriginalMethodAbstract) { for (PsiMethod oMethod : OverridingMethodsSearch.search(method)) { deleteOverrideAnnotationIfFound(oMethod); } } deleteOverrideAnnotationIfFound(method); } myMembersAfterMove.add(movedElement); // if (isOriginalMethodAbstract) { method.delete(); // } } else { if (isOriginalMethodAbstract) { PsiUtil.setModifierProperty(myTargetSuperClass, PsiModifier.ABSTRACT, true); } RefactoringUtil.replaceMovedMemberTypeParameters( methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory); fixReferencesToStatic(methodCopy); if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { superClassMethod.replace(convertMethodToLanguage(methodCopy, language)); } else { final PsiMember movedElement = anchor != null ? (PsiMember) myTargetSuperClass.addBefore( convertMethodToLanguage(methodCopy, language), anchor) : (PsiMember) myTargetSuperClass.addBefore( convertMethodToLanguage(methodCopy, language), myTargetSuperClass.getRBrace()); reformat(movedElement); myMembersAfterMove.add(movedElement); } method.delete(); } }
/** * @param sideEffects if null, delete usages, otherwise collect side effects * @return true if there are at least one unrecoverable side effect found, false if no side * effects, null if read usage found (may happen if interval between fix creation in invoke() * call was long enough) * @throws com.intellij.util.IncorrectOperationException */ static Boolean processUsage( PsiElement element, PsiVariable variable, List<PsiElement> sideEffects, int deleteMode) throws IncorrectOperationException { if (!element.isValid()) return null; PsiElementFactory factory = JavaPsiFacade.getInstance(variable.getProject()).getElementFactory(); while (element != null) { if (element instanceof PsiAssignmentExpression) { PsiAssignmentExpression expression = (PsiAssignmentExpression) element; PsiExpression lExpression = expression.getLExpression(); // there should not be read access to the variable, otherwise it is not unused if (!(lExpression instanceof PsiReferenceExpression) || variable != ((PsiReferenceExpression) lExpression).resolve()) { return null; } PsiExpression rExpression = expression.getRExpression(); rExpression = PsiUtil.deparenthesizeExpression(rExpression); if (rExpression == null) return true; // replace assignment with expression and resimplify boolean sideEffectFound = checkSideEffects(rExpression, variable, sideEffects); if (!(element.getParent() instanceof PsiExpressionStatement) || PsiUtil.isStatement(rExpression)) { if (deleteMode == MAKE_STATEMENT || deleteMode == DELETE_ALL && !(element.getParent() instanceof PsiExpressionStatement)) { element = replaceElementWithExpression(rExpression, factory, element); while (element.getParent() instanceof PsiParenthesizedExpression) { element = element.getParent().replace(element); } List<PsiElement> references = new ArrayList<PsiElement>(); collectReferences(element, variable, references); deleteReferences(variable, references, deleteMode); } else if (deleteMode == DELETE_ALL) { deleteWholeStatement(element, factory); } return true; } else { if (deleteMode != CANCEL) { deleteWholeStatement(element, factory); } return !sideEffectFound; } } else if (element instanceof PsiExpressionStatement && deleteMode != CANCEL) { final PsiElement parent = element.getParent(); if (parent instanceof PsiIfStatement || parent instanceof PsiLoopStatement && ((PsiLoopStatement) parent).getBody() == element) { element.replace( JavaPsiFacade.getElementFactory(element.getProject()) .createStatementFromText(";", element)); } else { element.delete(); } break; } else if (element instanceof PsiVariable && element == variable) { PsiExpression expression = variable.getInitializer(); if (expression != null) { expression = PsiUtil.deparenthesizeExpression(expression); } boolean sideEffectsFound = checkSideEffects(expression, variable, sideEffects); if (expression != null && PsiUtil.isStatement(expression) && variable instanceof PsiLocalVariable && !(variable.getParent() instanceof PsiDeclarationStatement && ((PsiDeclarationStatement) variable.getParent()).getDeclaredElements().length > 1)) { if (deleteMode == MAKE_STATEMENT) { element = element.replace(createStatementIfNeeded(expression, factory, element)); List<PsiElement> references = new ArrayList<PsiElement>(); collectReferences(element, variable, references); deleteReferences(variable, references, deleteMode); } else if (deleteMode == DELETE_ALL) { element.delete(); } return true; } else { if (deleteMode != CANCEL) { if (element instanceof PsiField) { ((PsiField) element).normalizeDeclaration(); } element.delete(); } return !sideEffectsFound; } } element = element.getParent(); } return true; }
public static boolean addStaticImport( @NotNull String qualifierClass, @NonNls @NotNull String memberName, @NotNull PsiElement context) { if (!nameCanBeStaticallyImported(qualifierClass, memberName, context)) { return false; } final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); if (InheritanceUtil.isInheritor(containingClass, qualifierClass)) { return true; } final PsiFile psiFile = context.getContainingFile(); if (!(psiFile instanceof PsiJavaFile)) { return false; } final PsiJavaFile javaFile = (PsiJavaFile) psiFile; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return false; } final PsiImportStatementBase existingImportStatement = importList.findSingleImportStatement(memberName); if (existingImportStatement != null) { if (existingImportStatement instanceof PsiImportStaticStatement) { final PsiImportStaticStatement importStaticStatement = (PsiImportStaticStatement) existingImportStatement; if (!memberName.equals(importStaticStatement.getReferenceName())) { return false; } final PsiClass targetClass = importStaticStatement.resolveTargetClass(); return targetClass != null && qualifierClass.equals(targetClass.getQualifiedName()); } return false; } final PsiImportStaticStatement onDemandImportStatement = findOnDemandImportStaticStatement(importList, qualifierClass); if (onDemandImportStatement != null && !hasOnDemandImportStaticConflict(qualifierClass, memberName, context)) { return true; } final Project project = context.getProject(); final GlobalSearchScope scope = context.getResolveScope(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass aClass = psiFacade.findClass(qualifierClass, scope); if (aClass == null) { return false; } final String qualifiedName = aClass.getQualifiedName(); if (qualifiedName == null) { return false; } final List<PsiImportStaticStatement> imports = getMatchingImports(importList, qualifiedName); final int onDemandCount = JavaCodeStyleSettingsFacade.getInstance(project).getNamesCountToUseImportOnDemand(); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); if (imports.size() < onDemandCount) { importList.add(elementFactory.createImportStaticStatement(aClass, memberName)); } else { for (PsiImportStaticStatement importStatement : imports) { importStatement.delete(); } importList.add(elementFactory.createImportStaticStatement(aClass, "*")); } return true; }
private void tryToMoveInitializers( PsiMethod constructor, HashSet<PsiMethod> subConstructors, LinkedHashSet<PsiField> movedFields) throws IncorrectOperationException { final LinkedHashMap<PsiField, Initializer> fieldsToInitializers = new LinkedHashMap<PsiField, Initializer>(); boolean anyFound = false; for (PsiField field : movedFields) { PsiStatement commonInitializer = null; final ArrayList<PsiElement> fieldInitializersToRemove = new ArrayList<PsiElement>(); for (PsiMethod subConstructor : subConstructors) { commonInitializer = hasCommonInitializer( commonInitializer, subConstructor, field, fieldInitializersToRemove); if (commonInitializer == null) break; } if (commonInitializer != null) { final ParametersAndMovedFieldsUsedCollector visitor = new ParametersAndMovedFieldsUsedCollector(movedFields); commonInitializer.accept(visitor); fieldsToInitializers.put( field, new Initializer( commonInitializer, visitor.getUsedFields(), visitor.getUsedParameters(), fieldInitializersToRemove)); anyFound = true; } } if (!anyFound) return; { final Set<PsiField> initializedFields = fieldsToInitializers.keySet(); Set<PsiField> unmovable = RefactoringUtil.transitiveClosure( new RefactoringUtil.Graph<PsiField>() { public Set<PsiField> getVertices() { return initializedFields; } public Set<PsiField> getTargets(PsiField source) { return fieldsToInitializers.get(source).movedFieldsUsed; } }, new Condition<PsiField>() { public boolean value(PsiField object) { return !initializedFields.contains(object); } }); for (PsiField psiField : unmovable) { fieldsToInitializers.remove(psiField); } } final PsiElementFactory factory = JavaPsiFacade.getElementFactory(myProject); if (constructor == null) { constructor = (PsiMethod) myTargetSuperClass.add(factory.createConstructor()); final String visibilityModifier = VisibilityUtil.getVisibilityModifier(myTargetSuperClass.getModifierList()); PsiUtil.setModifierProperty(constructor, visibilityModifier, true); } ArrayList<PsiField> initializedFields = new ArrayList<PsiField>(fieldsToInitializers.keySet()); Collections.sort( initializedFields, new Comparator<PsiField>() { public int compare(PsiField field1, PsiField field2) { Initializer i1 = fieldsToInitializers.get(field1); Initializer i2 = fieldsToInitializers.get(field2); if (i1.movedFieldsUsed.contains(field2)) return 1; if (i2.movedFieldsUsed.contains(field1)) return -1; return 0; } }); for (final PsiField initializedField : initializedFields) { Initializer initializer = fieldsToInitializers.get(initializedField); // correct constructor parameters and subConstructors super calls final PsiParameterList parameterList = constructor.getParameterList(); for (final PsiParameter parameter : initializer.usedParameters) { parameterList.add(parameter); } for (final PsiMethod subConstructor : subConstructors) { modifySuperCall(subConstructor, initializer.usedParameters); } PsiStatement assignmentStatement = (PsiStatement) constructor.getBody().add(initializer.initializer); PsiManager manager = PsiManager.getInstance(myProject); ChangeContextUtil.decodeContextInfo( assignmentStatement, myTargetSuperClass, RefactoringChangeUtil.createThisExpression(manager, null)); for (PsiElement psiElement : initializer.statementsToRemove) { psiElement.delete(); } } }
/** * Adds import if it is needed. * * @return false when the FQ-name have to be used in code (e.g. when conflicting imports already * exist) */ public boolean addImport(@NotNull PsiJavaFile file, @NotNull PsiClass refClass) { final JavaPsiFacade facade = JavaPsiFacade.getInstance(file.getProject()); PsiElementFactory factory = facade.getElementFactory(); PsiResolveHelper helper = facade.getResolveHelper(); String className = refClass.getQualifiedName(); if (className == null) return true; String packageName = getPackageOrClassName(className); String shortName = PsiNameHelper.getShortClassName(className); PsiClass conflictSingleRef = findSingleImportByShortName(file, shortName); if (conflictSingleRef != null) { return className.equals(conflictSingleRef.getQualifiedName()); } PsiClass curRefClass = helper.resolveReferencedClass(shortName, file); if (file.getManager().areElementsEquivalent(refClass, curRefClass)) { return true; } boolean useOnDemand = true; if (packageName.length() == 0) { useOnDemand = false; } PsiElement conflictPackageRef = findImportOnDemand(file, packageName); if (conflictPackageRef != null) { useOnDemand = false; } List<PsiElement> classesToReimport = new ArrayList<PsiElement>(); List<PsiJavaCodeReferenceElement> importRefs = getImportsFromPackage(file, packageName); if (useOnDemand) { if (mySettings.USE_SINGLE_CLASS_IMPORTS && importRefs.size() + 1 < mySettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND && !mySettings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.contains(packageName)) { useOnDemand = false; } // name of class we try to import is the same as of the class defined in this file if (curRefClass != null) { useOnDemand = true; } // check conflicts if (useOnDemand) { PsiElement[] onDemandRefs = file.getOnDemandImports(false, true); if (onDemandRefs.length > 0) { PsiPackage aPackage = facade.findPackage(packageName); if (aPackage != null) { PsiDirectory[] dirs = aPackage.getDirectories(); for (PsiDirectory dir : dirs) { PsiFile[] files = dir.getFiles(); // do not iterate classes - too slow when not loaded for (PsiFile aFile : files) { if (aFile instanceof PsiJavaFile) { String name = aFile.getVirtualFile().getNameWithoutExtension(); for (PsiElement ref : onDemandRefs) { String refName = ref instanceof PsiClass ? ((PsiClass) ref).getQualifiedName() : ((PsiPackage) ref).getQualifiedName(); String conflictClassName = refName + "." + name; GlobalSearchScope resolveScope = file.getResolveScope(); PsiClass conflictClass = facade.findClass(conflictClassName, resolveScope); if (conflictClass != null && helper.isAccessible(conflictClass, file, null)) { String conflictClassName2 = aPackage.getQualifiedName() + "." + name; PsiClass conflictClass2 = facade.findClass(conflictClassName2, resolveScope); if (conflictClass2 != null && helper.isAccessible(conflictClass2, file, null)) { if (ReferencesSearch.search( conflictClass, new LocalSearchScope(file), false) .findFirst() != null) { classesToReimport.add(conflictClass); } } } } } } } } } } } try { PsiImportList importList = file.getImportList(); PsiImportStatement statement; if (useOnDemand) { statement = factory.createImportStatementOnDemand(packageName); } else { statement = factory.createImportStatement(refClass); } importList.add(statement); if (useOnDemand) { for (PsiJavaCodeReferenceElement ref : importRefs) { LOG.assertTrue(ref.getParent() instanceof PsiImportStatement); if (!ref.isValid()) continue; // todo[dsl] Q? classesToReimport.add(ref.resolve()); PsiImportStatement importStatement = (PsiImportStatement) ref.getParent(); importStatement.delete(); } } for (PsiElement aClassesToReimport : classesToReimport) { PsiClass aClass = (PsiClass) aClassesToReimport; if (aClass != null) { addImport(file, aClass); } } } catch (IncorrectOperationException e) { LOG.error(e); } return true; }