private static boolean isParameterUsedRecursively( @NotNull PsiElement element, @NotNull List<PsiReference> array) { if (!(element instanceof PsiParameter)) return false; PsiParameter parameter = (PsiParameter) element; PsiElement scope = parameter.getDeclarationScope(); if (!(scope instanceof PsiMethod)) return false; PsiMethod method = (PsiMethod) scope; int paramIndex = ArrayUtilRt.find(method.getParameterList().getParameters(), parameter); for (PsiReference reference : array) { if (!(reference instanceof PsiElement)) return false; PsiElement argument = (PsiElement) reference; PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) new PsiMatcherImpl(argument) .dot(PsiMatchers.hasClass(PsiReferenceExpression.class)) .parent(PsiMatchers.hasClass(PsiExpressionList.class)) .parent(PsiMatchers.hasClass(PsiMethodCallExpression.class)) .getElement(); if (methodCallExpression == null) return false; PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); if (method != methodExpression.resolve()) return false; PsiExpressionList argumentList = methodCallExpression.getArgumentList(); PsiExpression[] arguments = argumentList.getExpressions(); int argumentIndex = ArrayUtilRt.find(arguments, argument); if (paramIndex != argumentIndex) return false; } return true; }
static String createContainsExpressionText( @NotNull PsiMethodCallExpression call, @NotNull PsiJavaToken sign, boolean flipped) { final IElementType tokenType = sign.getTokenType(); final PsiReferenceExpression methodExpression = call.getMethodExpression(); final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); final String qualifierText; if (qualifierExpression == null) { qualifierText = ""; } else { qualifierText = qualifierExpression.getText(); } final PsiExpressionList argumentList = call.getArgumentList(); final PsiExpression expression = argumentList.getExpressions()[0]; @NonNls final String newExpressionText = qualifierText + ".contains(" + expression.getText() + ')'; if (tokenType.equals(JavaTokenType.EQEQ)) { return '!' + newExpressionText; } else if (!flipped && (tokenType.equals(JavaTokenType.LT) || tokenType.equals(JavaTokenType.LE))) { return '!' + newExpressionText; } else if (flipped && (tokenType.equals(JavaTokenType.GT) || tokenType.equals(JavaTokenType.GE))) { return '!' + newExpressionText; } return newExpressionText; }
protected void changeSelfUsage(SelfUsageInfo usageInfo) throws IncorrectOperationException { PsiElement parent = usageInfo.getElement().getParent(); LOG.assertTrue(parent instanceof PsiMethodCallExpression); PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parent; final PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression(); if (qualifier != null) qualifier.delete(); PsiElementFactory factory = JavaPsiFacade.getInstance(methodCall.getProject()).getElementFactory(); PsiExpressionList args = methodCall.getArgumentList(); PsiElement addParameterAfter = null; if (mySettings.isMakeClassParameter()) { PsiElement arg = factory.createExpressionFromText(mySettings.getClassParameterName(), null); addParameterAfter = args.addAfter(arg, null); } if (mySettings.isMakeFieldParameters()) { List<Settings.FieldParameter> parameters = mySettings.getParameterOrderList(); for (Settings.FieldParameter fieldParameter : parameters) { PsiElement arg = factory.createExpressionFromText(fieldParameter.name, null); if (addParameterAfter == null) { addParameterAfter = args.addAfter(arg, null); } else { addParameterAfter = args.addAfter(arg, addParameterAfter); } } } }
private void findUsagesForMethod(PsiMethod method, List<FixableUsageInfo> usages) { final PsiManager psiManager = method.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope); for (PsiReference reference : calls) { final PsiElement referenceElement = reference.getElement(); final PsiElement parent = referenceElement.getParent(); if (parent instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression) parent; if (isInMovedElement(call)) { continue; } final PsiReferenceExpression methodExpression = call.getMethodExpression(); final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier == null || qualifier instanceof PsiThisExpression) { usages.add(new ReplaceThisCallWithDelegateCall(call, delegateFieldName)); } delegationRequired = true; } } if (!delegationRequired && MethodInheritanceUtils.hasSiblingMethods(method)) { delegationRequired = true; } if (delegationRequired) { usages.add(new MakeMethodDelegate(method, delegateFieldName)); } else { usages.add(new RemoveMethod(method)); } }
@Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final String methodName = methodExpression.getReferenceName(); @NonNls final String signal = "signal"; if (!signal.equals(methodName)) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); if (argumentList.getExpressions().length != 0) { return; } final PsiMethod method = expression.resolveMethod(); if (method == null) { return; } final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { return; } if (!ClassUtils.isSubclass(containingClass, "java.util.concurrent.locks.Condition")) { return; } registerMethodCallError(expression); }
@Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); @NonNls final String referenceName = methodExpression.getReferenceName(); if (!"toString".equals(referenceName) || ExpressionUtils.isConversionToStringNecessary(expression)) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 0) { return; } final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier != null) { if (qualifier.getType() instanceof PsiArrayType) { // do not warn on nonsensical code return; } else if (qualifier instanceof PsiSuperExpression) { return; } } registerMethodCallError(expression, calculateReplacementText(qualifier)); }
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { try { PsiBinaryExpression binaryExpression = (PsiBinaryExpression) descriptor.getPsiElement(); IElementType opSign = binaryExpression.getOperationSign().getTokenType(); PsiExpression lExpr = binaryExpression.getLOperand(); PsiExpression rExpr = binaryExpression.getROperand(); if (rExpr == null) return; PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); PsiMethodCallExpression equalsCall = (PsiMethodCallExpression) factory.createExpressionFromText("a.equals(b)", null); equalsCall.getMethodExpression().getQualifierExpression().replace(lExpr); equalsCall.getArgumentList().getExpressions()[0].replace(rExpr); PsiExpression result = (PsiExpression) binaryExpression.replace(equalsCall); if (opSign == JavaTokenType.NE) { PsiPrefixExpression negation = (PsiPrefixExpression) factory.createExpressionFromText("!a", null); negation.getOperand().replace(result); result.replace(negation); } } catch (IncorrectOperationException e) { LOG.error(e); } }
private void processUsagesForMethod( final boolean deleteMethodHierarchy, PsiMethod method, int[] paramPermutation, String getterName, PsiMethod delegatedMethod, List<FixableUsageInfo> usages) { for (PsiReference reference : ReferencesSearch.search(method)) { final PsiElement referenceElement = reference.getElement(); final PsiMethodCallExpression call = (PsiMethodCallExpression) referenceElement.getParent(); final String access; if (call.getMethodExpression().getQualifierExpression() == null) { access = field.getName(); } else { access = getterName + "()"; if (getter == null) { getter = GenerateMembersUtil.generateGetterPrototype(field); } } usages.add( new InlineDelegatingCall(call, paramPermutation, access, delegatedMethod.getName())); } if (deleteMethodHierarchy) { usages.add(new DeleteMethod(method)); } }
@Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) { super.visitMethodCallExpression(call); final PsiReferenceExpression methodExpression = call.getMethodExpression(); final PsiElement qualifier = methodExpression.getQualifier(); if (!(qualifier instanceof PsiReferenceExpression)) { return; } final PsiMethod method = call.resolveMethod(); if (method == null) { return; } if (!method.hasModifierProperty(PsiModifier.STATIC)) { return; } final PsiElement referent = ((PsiReference) qualifier).resolve(); if (!(referent instanceof PsiClass)) { return; } final PsiClass referencedClass = (PsiClass) referent; final PsiClass declaringClass = method.getContainingClass(); if (declaringClass == null) { return; } if (declaringClass.equals(referencedClass)) { return; } final PsiClass containingClass = ClassUtils.getContainingClass(call); if (!ClassUtils.isClassVisibleFromClass(containingClass, declaringClass)) { return; } registerMethodCallError(call, declaringClass, referencedClass); }
public static String buildCollectionText(PsiForStatement forStatement) { PsiStatement body = forStatement.getBody(); while (body instanceof PsiBlockStatement) { final PsiBlockStatement blockStatement = (PsiBlockStatement) body; final PsiCodeBlock codeBlock = blockStatement.getCodeBlock(); final PsiStatement[] statements = codeBlock.getStatements(); if (statements.length == 2) { body = statements[1]; } else if (statements.length == 1) { body = statements[0]; } else { return null; } } if (!(body instanceof PsiExpressionStatement)) { return null; } final PsiExpressionStatement expressionStatement = (PsiExpressionStatement) body; final PsiExpression expression = expressionStatement.getExpression(); if (!(expression instanceof PsiMethodCallExpression)) { return null; } final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiElement qualifier = methodExpression.getQualifier(); if (qualifier == null) { // fixme for when the array is added to 'this' return null; } return qualifier.getText(); }
@Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); @NonNls final String methodName = methodExpression.getReferenceName(); if (methodName == null) { return; } if (!methodName.startsWith("get") && !methodName.startsWith("update")) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length == 0) { return; } final PsiExpression argument = arguments[0]; if (!TypeUtils.expressionHasType(argument, PsiKeyword.INT)) { return; } if (!PsiUtil.isConstantExpression(argument)) { return; } final Integer val = (Integer) ConstantExpressionUtil.computeCastTo(argument, PsiType.INT); if (val == null || val.intValue() != 0) { return; } final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (!TypeUtils.expressionHasTypeOrSubtype(qualifier, "java.sql.ResultSet")) { return; } registerError(argument); }
@Nullable private static PsiType guessElementTypeFromReference( MethodPatternMap methodPatternMap, PsiElement ref, TextRange rangeToIgnore) { PsiElement refParent = ref.getParent(); if (refParent instanceof PsiReferenceExpression) { PsiReferenceExpression parentExpr = (PsiReferenceExpression) refParent; if (ref.equals(parentExpr.getQualifierExpression()) && parentExpr.getParent() instanceof PsiMethodCallExpression) { String methodName = parentExpr.getReferenceName(); PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parentExpr.getParent(); PsiExpression[] args = methodCall.getArgumentList().getExpressions(); MethodPattern pattern = methodPatternMap.findPattern(methodName, args.length); if (pattern != null) { if (pattern.parameterIndex < 0) { // return value if (methodCall.getParent() instanceof PsiTypeCastExpression && (rangeToIgnore == null || !rangeToIgnore.contains(methodCall.getTextRange()))) { return ((PsiTypeCastExpression) methodCall.getParent()).getType(); } } else { return args[pattern.parameterIndex].getType(); } } } } return null; }
private static boolean isIndexOfCall(@NotNull PsiMethodCallExpression expression) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final String methodName = methodExpression.getReferenceName(); if (!HardcodedMethodConstants.INDEX_OF.equals(methodName)) { return false; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 1) { return false; } final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier == null) { return false; } final PsiType qualifierType = qualifier.getType(); if (qualifierType == null) { return false; } final Project project = expression.getProject(); final GlobalSearchScope projectScope = GlobalSearchScope.allScope(project); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass javaUtilListClass = psiFacade.findClass(CommonClassNames.JAVA_UTIL_LIST, projectScope); if (javaUtilListClass == null) { return false; } final PsiElementFactory factory = psiFacade.getElementFactory(); final PsiClassType javaUtilListType = factory.createType(javaUtilListClass); return javaUtilListType.isAssignableFrom(qualifierType); }
@Nullable private static PsiMethodCallExpression checkMethodResolvable( PsiMethodCallExpression methodCall, PsiMethod targetMethod, PsiReferenceExpression context, PsiClass aClass) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(targetMethod.getProject()).getElementFactory(); final PsiElement resolved = methodCall.getMethodExpression().resolve(); if (resolved != targetMethod) { PsiClass containingClass; if (resolved instanceof PsiMethod) { containingClass = ((PsiMethod) resolved).getContainingClass(); } else if (resolved instanceof PsiClass) { containingClass = (PsiClass) resolved; } else { return null; } if (containingClass != null && containingClass.isInheritor(aClass, false)) { final PsiExpression newMethodExpression = factory.createExpressionFromText("super." + targetMethod.getName(), context); methodCall.getMethodExpression().replace(newMethodExpression); } else { methodCall = null; } } return methodCall; }
@Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiIdentifier name = (PsiIdentifier) descriptor.getPsiElement(); final PsiReferenceExpression expression = (PsiReferenceExpression) name.getParent(); if (expression == null) { return; } final PsiMethodCallExpression call = (PsiMethodCallExpression) expression.getParent(); final String methodName = expression.getReferenceName(); if (call == null) { return; } final PsiMethod method = call.resolveMethod(); if (method == null) { return; } final PsiClass containingClass = method.getContainingClass(); final PsiExpressionList argumentList = call.getArgumentList(); if (containingClass == null) { return; } final String containingClassName = containingClass.getQualifiedName(); final String argText = argumentList.getText(); PsiReplacementUtil.replaceExpressionAndShorten( call, containingClassName + '.' + methodName + argText); }
private static boolean isCollectCall(PsiStatement body, final PsiParameter parameter) { PsiIfStatement ifStatement = extractIfStatement(body); final PsiMethodCallExpression methodCallExpression = extractAddCall(body, ifStatement); if (methodCallExpression != null) { final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); PsiClass qualifierClass = null; if (qualifierExpression instanceof PsiReferenceExpression) { if (ReferencesSearch.search(parameter, new LocalSearchScope(qualifierExpression)) .findFirst() != null) { return false; } final PsiElement resolve = ((PsiReferenceExpression) qualifierExpression).resolve(); if (resolve instanceof PsiVariable) { if (ReferencesSearch.search( resolve, new LocalSearchScope(methodCallExpression.getArgumentList())) .findFirst() != null) { return false; } } qualifierClass = PsiUtil.resolveClassInType(qualifierExpression.getType()); } else if (qualifierExpression == null) { final PsiClass enclosingClass = PsiTreeUtil.getParentOfType(body, PsiClass.class); if (PsiUtil.getEnclosingStaticElement(body, enclosingClass) == null) { qualifierClass = enclosingClass; } } if (qualifierClass != null && InheritanceUtil.isInheritor( qualifierClass, false, CommonClassNames.JAVA_UTIL_COLLECTION)) { while (ifStatement != null && PsiTreeUtil.isAncestor(body, ifStatement, false)) { final PsiExpression condition = ifStatement.getCondition(); if (condition != null && isConditionDependsOnUpdatedCollections(condition, qualifierExpression)) return false; ifStatement = PsiTreeUtil.getParentOfType(ifStatement, PsiIfStatement.class); } final PsiElement resolve = methodExpression.resolve(); if (resolve instanceof PsiMethod && "add".equals(((PsiMethod) resolve).getName()) && ((PsiMethod) resolve).getParameterList().getParametersCount() == 1) { final PsiExpression[] args = methodCallExpression.getArgumentList().getExpressions(); if (args.length == 1) { if (args[0] instanceof PsiCallExpression) { final PsiMethod method = ((PsiCallExpression) args[0]).resolveMethod(); return method != null && !method.hasTypeParameters() && !isThrowsCompatible(method); } return true; } } } } return false; }
@Override protected boolean isValidElement(PsiElement element) { PsiMethodCallExpression methodCall = (PsiMethodCallExpression) element; PsiMethod method = (PsiMethod) methodCall.getMethodExpression().resolve(); PsiExpressionList argumentList = methodCall.getArgumentList(); List<PsiClass> classes = getTargetClasses(element); return !classes.isEmpty() && !CreateFromUsageUtils.shouldCreateConstructor(classes.get(0), argumentList, method); }
public static int findFieldAssignmentAnchor( final PsiStatement[] statements, final @Nullable Ref<Pair<PsiField, Boolean>> anchorRef, final PsiClass targetClass, final PsiParameter myParameter) { int i = 0; for (; i < statements.length; i++) { PsiStatement psiStatement = statements[i]; if (psiStatement instanceof PsiExpressionStatement) { PsiExpressionStatement expressionStatement = (PsiExpressionStatement) psiStatement; PsiExpression expression = expressionStatement.getExpression(); if (expression instanceof PsiMethodCallExpression) { PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; String text = methodCallExpression.getMethodExpression().getText(); if (text.equals("super") || text.equals("this")) { continue; } } else if (expression instanceof PsiAssignmentExpression) { PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) expression; PsiExpression lExpression = assignmentExpression.getLExpression(); PsiExpression rExpression = assignmentExpression.getRExpression(); if (!(lExpression instanceof PsiReferenceExpression)) break; if (!(rExpression instanceof PsiReferenceExpression)) break; PsiReferenceExpression lReference = (PsiReferenceExpression) lExpression; PsiReferenceExpression rReference = (PsiReferenceExpression) rExpression; PsiElement lElement = lReference.resolve(); PsiElement rElement = rReference.resolve(); if (!(lElement instanceof PsiField) || ((PsiField) lElement).getContainingClass() != targetClass) break; if (!(rElement instanceof PsiParameter)) break; if (myParameter.getTextRange().getStartOffset() < rElement.getTextRange().getStartOffset()) { if (anchorRef != null) { anchorRef.set(Pair.create((PsiField) lElement, Boolean.TRUE)); } break; } if (anchorRef != null) { anchorRef.set(Pair.create((PsiField) lElement, Boolean.FALSE)); } continue; } } break; } return i; }
private static void removeParensFromMethodCallExpression( @NotNull PsiMethodCallExpression methodCallExpression, boolean ignoreClarifyingParentheses) { final PsiReferenceExpression target = methodCallExpression.getMethodExpression(); final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); removeParentheses(target, ignoreClarifyingParentheses); for (final PsiExpression argument : arguments) { removeParentheses(argument, ignoreClarifyingParentheses); } }
static boolean isComplexArrayExpression(PsiExpression expression) { expression = ParenthesesUtils.stripParentheses(expression); if (expression == null) { return false; } if (expression instanceof PsiNewExpression) { final PsiNewExpression newExpression = (PsiNewExpression) expression; final PsiArrayInitializerExpression arrayInitializer = newExpression.getArrayInitializer(); return isComplexArrayExpression(arrayInitializer); } else if (expression instanceof PsiArrayInitializerExpression) { final PsiArrayInitializerExpression arrayInitializerExpression = (PsiArrayInitializerExpression) expression; for (PsiExpression initializer : arrayInitializerExpression.getInitializers()) { if (isComplexArrayExpression(initializer)) { return true; } } return false; } else if (expression instanceof PsiReferenceExpression) { return expression.getType() instanceof PsiArrayType; } else if (expression instanceof PsiArrayAccessExpression) { return true; } else if (expression instanceof PsiTypeCastExpression) { final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) expression; return isComplexArrayExpression(typeCastExpression.getOperand()); } else if (expression instanceof PsiConditionalExpression) { final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression) expression; return isComplexArrayExpression(conditionalExpression.getThenExpression()) || isComplexArrayExpression(conditionalExpression.getElseExpression()); } else if (expression instanceof PsiMethodCallExpression) { final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; final PsiMethod method = methodCallExpression.resolveMethod(); if (method == null) { return true; } if (CloneUtils.isClone(method)) { return false; } @NonNls final String name = method.getName(); if ("copyOf".equals(name) || "copyOfRange".equals(name)) { final PsiClass aClass = method.getContainingClass(); if (aClass != null && CommonClassNames.JAVA_UTIL_ARRAYS.equals(aClass.getQualifiedName())) { return false; } } else if ("toArray".equals(name) && InheritanceUtil.isInheritor(method.getContainingClass(), "java.util.Collection")) { return false; } return true; } return true; }
private static boolean isAddAllCall(PsiForeachStatement statement, PsiStatement body) { final PsiIfStatement ifStatement = extractIfStatement(body); if (ifStatement == null) { final PsiParameter parameter = statement.getIterationParameter(); final PsiMethodCallExpression methodCallExpression = extractAddCall(body, null); LOG.assertTrue(methodCallExpression != null); return isIdentityMapping( parameter, methodCallExpression.getArgumentList().getExpressions()[0]); } return false; }
@Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (argumentsContainCatchParameter || !visited.add(expression)) { return; } super.visitReferenceExpression(expression); final PsiElement target = expression.resolve(); if (!parameter.equals(target)) { if (target instanceof PsiLocalVariable) { final PsiLocalVariable variable = (PsiLocalVariable) target; final Query<PsiReference> query = ReferencesSearch.search(variable, variable.getUseScope(), false); query.forEach( reference -> { final PsiElement element = reference.getElement(); final PsiElement parent = PsiTreeUtil.skipParentsOfType(element, PsiParenthesizedExpression.class); if (!(parent instanceof PsiReferenceExpression)) { return true; } final PsiElement grandParent = parent.getParent(); if (!(grandParent instanceof PsiMethodCallExpression)) { return true; } final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent; final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); for (PsiExpression argument : arguments) { argument.accept(ReferenceFinder.this); } return true; }); final PsiExpression initializer = variable.getInitializer(); if (initializer != null) { initializer.accept(this); } } return; } if (ignoreGetMessage) { argumentsContainCatchParameter = true; } else { final PsiElement parent = expression.getParent(); if (parent instanceof PsiReferenceExpression) { final PsiElement grandParent = parent.getParent(); if (grandParent instanceof PsiMethodCallExpression) { return; } } argumentsContainCatchParameter = true; } }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) descriptor.getPsiElement().getParent().getParent(); final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier == null) { PsiReplacementUtil.replaceExpression(methodCallExpression, "this"); } else { methodCallExpression.replace(qualifier); } }
private static boolean methodCallExpressionsAreEquivalent( @NotNull PsiMethodCallExpression methodExp1, @NotNull PsiMethodCallExpression methodExp2) { final PsiReferenceExpression methodExpression1 = methodExp1.getMethodExpression(); final PsiReferenceExpression methodExpression2 = methodExp2.getMethodExpression(); if (!expressionsAreEquivalent(methodExpression1, methodExpression2)) { return false; } final PsiExpressionList argumentList1 = methodExp1.getArgumentList(); final PsiExpression[] args1 = argumentList1.getExpressions(); final PsiExpressionList argumentList2 = methodExp2.getArgumentList(); final PsiExpression[] args2 = argumentList2.getExpressions(); return expressionListsAreEquivalent(args1, args2); }
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) { final UsageInfo[] usages = refUsages.get(); MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); final Set<PsiMember> members = new HashSet<PsiMember>(); members.add(myMethod); if (myTargetVariable instanceof PsiField) members.add((PsiMember) myTargetVariable); if (!myTargetClass.isInterface()) { RefactoringConflictsUtil.analyzeAccessibilityConflicts( members, myTargetClass, conflicts, myNewVisibility); } else { for (final UsageInfo usage : usages) { if (usage instanceof InheritorUsageInfo) { RefactoringConflictsUtil.analyzeAccessibilityConflicts( members, ((InheritorUsageInfo) usage).getInheritor(), conflicts, myNewVisibility); } } } if (myTargetVariable instanceof PsiParameter) { PsiParameter parameter = (PsiParameter) myTargetVariable; for (final UsageInfo usageInfo : usages) { if (usageInfo instanceof MethodCallUsageInfo) { final PsiMethodCallExpression methodCall = ((MethodCallUsageInfo) usageInfo).getMethodCallExpression(); final PsiExpression[] expressions = methodCall.getArgumentList().getExpressions(); final int index = myMethod.getParameterList().getParameterIndex(parameter); if (index < expressions.length) { PsiExpression instanceValue = expressions[index]; instanceValue = RefactoringUtil.unparenthesizeExpression(instanceValue); if (instanceValue instanceof PsiLiteralExpression && ((PsiLiteralExpression) instanceValue).getValue() == null) { String message = RefactoringBundle.message( "0.contains.call.with.null.argument.for.parameter.1", RefactoringUIUtil.getDescription( ConflictsUtil.getContainer(methodCall), true), CommonRefactoringUtil.htmlEmphasize(parameter.getName())); conflicts.putValue(instanceValue, message); } } } } } try { ConflictsUtil.checkMethodConflicts(myTargetClass, myMethod, getPatternMethod(), conflicts); } catch (IncorrectOperationException e) { } return showConflicts(conflicts, usages); }
@Override @Nullable public PsiType fun(final PsiMethodCallExpression call) { PsiReferenceExpression methodExpression = call.getMethodExpression(); PsiType theOnly = null; final JavaResolveResult[] results = methodExpression.multiResolve(false); LanguageLevel languageLevel = PsiUtil.getLanguageLevel(call); final PsiElement callParent = PsiUtil.skipParenthesizedExprUp(call.getParent()); final PsiExpressionList parentArgList; if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) { parentArgList = callParent instanceof PsiConditionalExpression && !PsiPolyExpressionUtil.isPolyExpression((PsiExpression) callParent) ? null : PsiTreeUtil.getParentOfType(call, PsiExpressionList.class); } else { parentArgList = null; } final MethodCandidateInfo.CurrentCandidateProperties properties = MethodCandidateInfo.getCurrentMethod(parentArgList); final boolean genericMethodCall = properties != null && properties.getInfo().isToInferApplicability(); for (int i = 0; i < results.length; i++) { final JavaResolveResult candidateInfo = results[i]; if (genericMethodCall && PsiPolyExpressionUtil.isMethodCallPolyExpression( call, (PsiMethod) candidateInfo.getElement())) { if (callParent instanceof PsiAssignmentExpression) { return null; } LOG.error("poly expression evaluation during overload resolution"); } final PsiType type = getResultType(call, methodExpression, candidateInfo, languageLevel); if (type == null) { return null; } if (i == 0) { theOnly = type; } else if (!theOnly.equals(type)) { return null; } } return PsiClassImplUtil.correctType(theOnly, call.getResolveScope()); }
@Override protected final void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); final PsiTypeElement castTypeElement; final PsiReferenceExpression reference; if (element instanceof PsiTypeCastExpression) { final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression) element; castTypeElement = typeCastExpression.getCastType(); final PsiExpression operand = typeCastExpression.getOperand(); if (!(operand instanceof PsiReferenceExpression)) { return; } reference = (PsiReferenceExpression) operand; } else if (element instanceof PsiMethodCallExpression) { final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) element; final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (!(qualifier instanceof PsiClassObjectAccessExpression)) { return; } final PsiClassObjectAccessExpression classObjectAccessExpression = (PsiClassObjectAccessExpression) qualifier; castTypeElement = classObjectAccessExpression.getOperand(); final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 1) { return; } final PsiExpression argument = arguments[0]; if (!(argument instanceof PsiReferenceExpression)) { return; } reference = (PsiReferenceExpression) argument; } else { return; } if (castTypeElement == null) { return; } final PsiInstanceOfExpression conflictingInstanceof = InstanceOfUtils.getConflictingInstanceof(castTypeElement.getType(), reference, element); final PsiTypeElement instanceofTypeElement = conflictingInstanceof.getCheckType(); if (instanceofTypeElement == null) { return; } final PsiElement newElement = replace(castTypeElement, instanceofTypeElement); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); codeStyleManager.shortenClassReferences(newElement); }
private List<MethodContract> handleCallDelegation( PsiMethodCallExpression expression, final boolean negated) { final PsiMethod targetMethod = expression.resolveMethod(); if (targetMethod == null) return Collections.emptyList(); final PsiExpression[] arguments = expression.getArgumentList().getExpressions(); return RecursionManager.doPreventingRecursion( myMethod, true, new Computable<List<MethodContract>>() { @Override public List<MethodContract> compute() { List<MethodContract> delegateContracts = ControlFlowAnalyzer.getMethodContracts(targetMethod); return ContainerUtil.mapNotNull( delegateContracts, new NullableFunction<MethodContract, MethodContract>() { @Nullable @Override public MethodContract fun(MethodContract delegateContract) { ValueConstraint[] answer = MethodContract.createConstraintArray( myMethod.getParameterList().getParametersCount()); for (int i = 0; i < delegateContract.arguments.length; i++) { if (i >= arguments.length) return null; ValueConstraint argConstraint = delegateContract.arguments[i]; if (argConstraint != ANY_VALUE) { int paramIndex = resolveParameter(arguments[i]); if (paramIndex < 0) { if (argConstraint != getLiteralConstraint(arguments[i])) { return null; } } else { answer = withConstraint(answer, paramIndex, argConstraint); } } } return answer == null ? null : new MethodContract( answer, negated ? negateConstraint(delegateContract.returnValue) : delegateContract.returnValue); } }); } }); }
@Nullable private static LookupElementWeigher recursion( CompletionParameters parameters, final ExpectedTypeInfo[] expectedInfos) { final PsiElement position = parameters.getPosition(); final PsiMethodCallExpression expression = PsiTreeUtil.getParentOfType(position, PsiMethodCallExpression.class, true, PsiClass.class); final PsiReferenceExpression reference = expression != null ? expression.getMethodExpression() : PsiTreeUtil.getParentOfType(position, PsiReferenceExpression.class); if (reference == null) return null; return new RecursionWeigher(position, reference, expression, expectedInfos); }
private boolean isListGetLookup(PsiElement element, String indexName, PsiVariable listVariable) { if (!(element instanceof PsiExpression)) { return false; } final PsiExpression expression = (PsiExpression)element; if (!expressionIsListGetLookup(expression)) { return false; } final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) ParenthesesUtils.stripParentheses(expression); if (methodCallExpression == null) { return false; } final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] expressions = argumentList.getExpressions(); if (expressions.length != 1) { return false; } if (!indexName.equals(expressions[0].getText())) { return false; } if (qualifierExpression == null || qualifierExpression instanceof PsiThisExpression || qualifierExpression instanceof PsiSuperExpression) { return listVariable == null; } if (!(qualifierExpression instanceof PsiReferenceExpression)) { return false; } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)qualifierExpression; final PsiExpression qualifier = referenceExpression.getQualifierExpression(); if (qualifier != null && !(qualifier instanceof PsiThisExpression) && !(qualifier instanceof PsiSuperExpression)) { return false; } final PsiElement target = referenceExpression.resolve(); return listVariable.equals(target); }