PsiElementVisitor (@NotNull ProblemsHolder holder, boolean isOnTheFly) { return new JavaElementVisitor() { @Override public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) { if (!COMPARE_METHOD.test(call)) return; checkComparison(call); PsiElement parent = PsiUtil.skipParenthesizedExprUp(call.getParent()); if (parent instanceof PsiLocalVariable var) { PsiCodeBlock block = PsiTreeUtil.getParentOfType(var, PsiCodeBlock.class); PsiExpression initializer = var.getInitializer(); if (block != null && initializer != null) { for (PsiElement element : DefUseUtil.getRefs(block, var, initializer)) { checkComparison(element); } } } } private void checkComparison(PsiElement compareExpression) { PsiBinaryExpression binOp = ObjectUtils.tryCast(PsiUtil.skipParenthesizedExprUp(compareExpression.getParent()), PsiBinaryExpression.class); if (binOp == null) return; PsiJavaToken sign = binOp.getOperationSign(); IElementType tokenType = sign.getTokenType(); RelationType relation = DfaPsiUtil.getRelationByToken(tokenType); if (relation == null) return; PsiExpression constOperand = PsiTreeUtil.isAncestor(binOp.getLOperand(), compareExpression, false) ? binOp.getROperand() : binOp.getLOperand(); if (constOperand == null) return; Object constantExpression = ExpressionUtils.computeConstantExpression(constOperand); if (!(constantExpression instanceof Integer)) return; int value = ((Integer)constantExpression).intValue(); if (value == 0) return; boolean yodaCondition = constOperand == binOp.getLOperand(); if (yodaCondition) { relation = relation.getFlipped(); } LongRangeSet rangeSet = LongRangeSet.point(value).fromRelation(relation); if (coversPartially(rangeSet, NEGATIVE_INTEGERS)) { register(sign, yodaCondition, rangeSet.intersects(POSITIVE_INTEGERS) ? null : RelationType.LT); } else if (coversPartially(rangeSet, POSITIVE_INTEGERS)) { register(sign, yodaCondition, rangeSet.intersects(NEGATIVE_INTEGERS) ? null : RelationType.GT); } } private static boolean coversPartially(LongRangeSet testedRange, LongRangeSet coveredRange) { LongRangeSet intersection = testedRange.meet(coveredRange); return !intersection.isEmpty() && !coveredRange.subtract(intersection).isEmpty(); } private void register(PsiJavaToken sign, boolean yodaCondition, RelationType relationType) { LocalQuickFix[] fixes = relationType == null ? LocalQuickFix.EMPTY_ARRAY : new LocalQuickFix[]{new ComparatorComparisonFix(yodaCondition, relationType)}; holder.registerProblem(sign, JavaBundle.message("inspection.comparator.result.comparison.problem.display.name"), fixes); } }; }