Skip to content

Commit b3bebe7

Browse files
Implement PSI diagnostics and language-level validation
1 parent ead8022 commit b3bebe7

12 files changed

Lines changed: 1586 additions & 0 deletions
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* SonarQube Java
3+
* Copyright (C) SonarSource Sàrl
4+
* mailto:info AT sonarsource DOT com
5+
*
6+
* You can redistribute and/or modify this program under the terms of
7+
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12+
* See the Sonar Source-Available License for more details.
13+
*
14+
* You should have received a copy of the Sonar Source-Available License
15+
* along with this program; if not, see https://sonarsource.com/license/ssal/
16+
*/
17+
package org.sonar.java.model;
18+
19+
import com.intellij.psi.JavaTokenType;
20+
import com.intellij.psi.PsiAssignmentExpression;
21+
import com.intellij.psi.PsiField;
22+
import com.intellij.psi.PsiModifier;
23+
import com.intellij.psi.PsiReferenceExpression;
24+
import com.intellij.psi.PsiSuperExpression;
25+
import com.intellij.psi.PsiThisExpression;
26+
import com.intellij.psi.PsiVariable;
27+
import com.intellij.psi.util.PsiUtil;
28+
29+
final class PsiAssignmentDiagnostics {
30+
private PsiAssignmentDiagnostics() {
31+
}
32+
33+
static boolean hasNoEffect(PsiAssignmentExpression expression) {
34+
if (expression.getOperationTokenType() != JavaTokenType.EQ) {
35+
return false;
36+
}
37+
var left = PsiUtil.skipParenthesizedExprDown(expression.getLExpression());
38+
var right = PsiUtil.skipParenthesizedExprDown(expression.getRExpression());
39+
if (right instanceof PsiAssignmentExpression assignment) {
40+
right = assignment.getLExpression();
41+
}
42+
if (!(left instanceof PsiReferenceExpression lhs) || !(right instanceof PsiReferenceExpression rhs)
43+
|| !(lhs.resolve() instanceof PsiVariable variable) || variable.hasModifierProperty(PsiModifier.VOLATILE) || !variable.equals(rhs.resolve())) {
44+
return false;
45+
}
46+
if (variable instanceof PsiField) {
47+
return currentInstance(lhs, variable) && currentInstance(rhs, variable);
48+
}
49+
return true;
50+
}
51+
52+
private static boolean currentInstance(PsiReferenceExpression reference, PsiVariable variable) {
53+
var qualifier = PsiUtil.skipParenthesizedExprDown(reference.getQualifierExpression());
54+
return qualifier == null || qualifier instanceof PsiThisExpression current && current.getQualifier() == null
55+
|| qualifier instanceof PsiSuperExpression current && current.getQualifier() == null
56+
|| variable.hasModifierProperty(PsiModifier.STATIC) && qualifier instanceof PsiReferenceExpression name
57+
&& name.resolve() instanceof com.intellij.psi.PsiClass;
58+
}
59+
}
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/*
2+
* SonarQube Java
3+
* Copyright (C) SonarSource Sàrl
4+
* mailto:info AT sonarsource DOT com
5+
*
6+
* You can redistribute and/or modify this program under the terms of
7+
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12+
* See the Sonar Source-Available License for more details.
13+
*
14+
* You should have received a copy of the Sonar Source-Available License
15+
* along with this program; if not, see https://sonarsource.com/license/ssal/
16+
*/
17+
package org.sonar.java.model;
18+
19+
import com.intellij.psi.JavaPsiFacade;
20+
import com.intellij.psi.PsiArrayType;
21+
import com.intellij.psi.PsiAssignmentExpression;
22+
import com.intellij.psi.PsiCallExpression;
23+
import com.intellij.psi.PsiClassType;
24+
import com.intellij.psi.PsiExpression;
25+
import com.intellij.psi.PsiExpressionList;
26+
import com.intellij.psi.PsiFunctionalExpression;
27+
import com.intellij.psi.PsiMethod;
28+
import com.intellij.psi.PsiMethodCallExpression;
29+
import com.intellij.psi.PsiParenthesizedExpression;
30+
import com.intellij.psi.PsiPrimitiveType;
31+
import com.intellij.psi.PsiReturnStatement;
32+
import com.intellij.psi.PsiTypeCastExpression;
33+
import com.intellij.psi.PsiVariable;
34+
import com.intellij.psi.util.PsiTreeUtil;
35+
import com.intellij.psi.util.PsiUtil;
36+
import com.intellij.psi.util.TypeConversionUtil;
37+
38+
final class PsiCastDiagnostics {
39+
private PsiCastDiagnostics() {
40+
}
41+
42+
static boolean isRedundant(PsiTypeCastExpression cast) {
43+
var operand = PsiUtil.skipParenthesizedExprDown(cast.getOperand());
44+
if (operand == null || operand instanceof PsiFunctionalExpression || cast.getType() == null || operand.getType() == null) {
45+
return false;
46+
}
47+
var from = operand.getType();
48+
var to = cast.getCastType().getType();
49+
if (!resolved(from) || !resolved(to)) {
50+
return false;
51+
}
52+
var anchor = anchor(cast);
53+
var parent = anchor.getParent();
54+
if (parent instanceof com.intellij.psi.PsiReferenceExpression reference && reference.getParent() instanceof PsiMethodCallExpression call
55+
&& call.getArgumentList().isEmpty() && "getClass".equals(reference.getReferenceName())) {
56+
return true;
57+
}
58+
boolean assignable = TypeConversionUtil.isAssignable(to, from);
59+
if (parent instanceof PsiExpressionList arguments && arguments.getParent() instanceof PsiCallExpression call) {
60+
return assignable && sameCall(call, cast);
61+
}
62+
if (operand instanceof PsiMethodCallExpression call) {
63+
var method = call.resolveMethod();
64+
if (method != null && method.hasTypeParameters() && call.getTypeArguments().length == 0
65+
&& method.getReturnType() instanceof PsiClassType result && result.resolve() instanceof com.intellij.psi.PsiTypeParameter parameter
66+
&& java.util.Arrays.stream(method.getParameterList().getParameters()).anyMatch(argument ->
67+
PsiDiagnosticTypes.mentions(argument.getType(), parameter))) {
68+
return false;
69+
}
70+
}
71+
if (to.equals(from)) {
72+
return true;
73+
}
74+
if (parent instanceof com.intellij.psi.PsiArrayAccessExpression && assignable) {
75+
return true;
76+
}
77+
if (parent instanceof com.intellij.psi.PsiPolyadicExpression binary && from instanceof PsiPrimitiveType && to instanceof PsiPrimitiveType) {
78+
var operands = binary.getOperands();
79+
return assignable && java.util.Arrays.stream(operands).filter(expression -> expression != anchor)
80+
.filter(expression -> !(PsiUtil.skipParenthesizedExprDown(expression) instanceof PsiTypeCastExpression))
81+
.anyMatch(expression -> to.equals(expression.getType())) && to.equals(binary.getType());
82+
}
83+
com.intellij.psi.PsiType expected = null;
84+
if (parent instanceof PsiVariable variable) {
85+
expected = variable.getType();
86+
} else if (parent instanceof PsiAssignmentExpression assignment && assignment.getRExpression() == anchor) {
87+
expected = assignment.getLExpression().getType();
88+
} else if (parent instanceof PsiReturnStatement) {
89+
var method = PsiTreeUtil.getParentOfType(parent, PsiMethod.class);
90+
expected = method == null ? null : method.getReturnType();
91+
} else if (parent instanceof PsiTypeCastExpression outer) {
92+
expected = outer.getType();
93+
}
94+
if (expected == null || !TypeConversionUtil.isAssignable(expected, from)) {
95+
return false;
96+
}
97+
if (assignable) {
98+
return true;
99+
}
100+
if (operand instanceof PsiMethodCallExpression call) {
101+
var method = call.resolveMethod();
102+
return method != null && method.getReturnType() instanceof PsiClassType result && result.resolve() instanceof com.intellij.psi.PsiTypeParameter;
103+
}
104+
return false;
105+
}
106+
107+
private static boolean resolved(com.intellij.psi.PsiType type) {
108+
if (type instanceof PsiClassType cls) {
109+
return cls.resolve() != null && java.util.Arrays.stream(cls.getParameters()).allMatch(PsiCastDiagnostics::resolved);
110+
}
111+
if (type instanceof PsiArrayType array) {
112+
return resolved(array.getComponentType());
113+
}
114+
if (type instanceof com.intellij.psi.PsiWildcardType wildcard) {
115+
return !wildcard.isBounded() || resolved(wildcard.getBound());
116+
}
117+
return true;
118+
}
119+
120+
static PsiExpression anchor(PsiTypeCastExpression cast) {
121+
PsiExpression anchor = cast;
122+
while (anchor.getParent() instanceof PsiParenthesizedExpression parentheses) {
123+
anchor = parentheses;
124+
}
125+
return anchor;
126+
}
127+
128+
private static boolean sameCall(PsiCallExpression call, PsiTypeCastExpression cast) {
129+
var original = call.resolveMethodGenerics();
130+
if (!original.isValidResult() || original.getElement() == null) {
131+
return false;
132+
}
133+
int start = cast.getTextRange().getStartOffset() - call.getTextRange().getStartOffset();
134+
int end = cast.getTextRange().getEndOffset() - call.getTextRange().getStartOffset();
135+
String text = call.getText();
136+
var replacement = JavaPsiFacade.getElementFactory(call.getProject()).createExpressionFromText(
137+
text.substring(0, start) + cast.getOperand().getText() + text.substring(end), call);
138+
if (!(replacement instanceof PsiCallExpression alternative)) {
139+
return false;
140+
}
141+
var result = alternative.resolveMethodGenerics();
142+
if (!result.isValidResult() || !original.getElement().equals(result.getElement())) {
143+
return false;
144+
}
145+
var method = (PsiMethod) original.getElement();
146+
if (method.isVarArgs() && cast.getOperand().getType() instanceof PsiArrayType && !cast.getCastType().getType().equals(cast.getOperand().getType())) {
147+
return false;
148+
}
149+
return java.util.Arrays.stream(method.getTypeParameters()).allMatch(parameter -> java.util.Objects.equals(
150+
original.getSubstitutor().substitute(parameter), result.getSubstitutor().substitute(parameter)));
151+
}
152+
153+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* SonarQube Java
3+
* Copyright (C) SonarSource Sàrl
4+
* mailto:info AT sonarsource DOT com
5+
*
6+
* You can redistribute and/or modify this program under the terms of
7+
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12+
* See the Sonar Source-Available License for more details.
13+
*
14+
* You should have received a copy of the Sonar Source-Available License
15+
* along with this program; if not, see https://sonarsource.com/license/ssal/
16+
*/
17+
package org.sonar.java.model;
18+
19+
import com.intellij.codeInsight.ExceptionUtil;
20+
import com.intellij.psi.PsiClassType;
21+
import com.intellij.psi.PsiDisjunctionType;
22+
import com.intellij.psi.PsiElement;
23+
import com.intellij.psi.PsiJavaCodeReferenceElement;
24+
import com.intellij.psi.PsiMethod;
25+
import com.intellij.psi.PsiMethodCallExpression;
26+
import com.intellij.psi.PsiNewExpression;
27+
import com.intellij.psi.PsiTryStatement;
28+
import com.intellij.psi.PsiTypeElement;
29+
import com.intellij.psi.util.InheritanceUtil;
30+
import com.intellij.psi.util.PsiTreeUtil;
31+
import java.util.ArrayList;
32+
import java.util.List;
33+
import java.util.function.BiConsumer;
34+
35+
final class PsiCatchDiagnostics {
36+
private PsiCatchDiagnostics() {
37+
}
38+
39+
static void collect(PsiTryStatement statement, BiConsumer<PsiElement, String> warning) {
40+
var block = statement.getTryBlock();
41+
if (block == null || incompleteExecutable(statement)) {
42+
return;
43+
}
44+
var thrown = new ArrayList<PsiClassType>(ExceptionUtil.getThrownExceptions(block));
45+
if (statement.getResourceList() != null) {
46+
thrown.addAll(ExceptionUtil.getThrownExceptions(statement.getResourceList()));
47+
}
48+
var previous = new ArrayList<com.intellij.psi.PsiType>();
49+
for (var section : statement.getCatchSections()) {
50+
var parameter = section.getParameter();
51+
if (parameter == null || parameter.getTypeElement() == null) {
52+
continue;
53+
}
54+
var type = parameter.getType();
55+
List<com.intellij.psi.PsiType> alternatives = type instanceof PsiDisjunctionType union ? union.getDisjunctions() : List.of(type);
56+
for (var alternative : alternatives) {
57+
if (!(alternative instanceof PsiClassType cls) || cls.resolve() == null
58+
|| InheritanceUtil.isInheritor(cls, "java.lang.RuntimeException") || InheritanceUtil.isInheritor(cls, "java.lang.Error")
59+
|| cls.equalsToText("java.lang.Exception") || cls.equalsToText("java.lang.Throwable")) {
60+
continue;
61+
}
62+
var relevant = thrown.stream().filter(exception -> alternative.isAssignableFrom(exception) || exception.isAssignableFrom(alternative)).toList();
63+
if (!relevant.isEmpty() && relevant.stream().allMatch(exception -> previous.stream().anyMatch(caught -> caught.isAssignableFrom(exception)))
64+
&& previous.stream().noneMatch(caught -> caught.isAssignableFrom(alternative))) {
65+
var element = parameter.getTypeElement();
66+
if (type instanceof PsiDisjunctionType) {
67+
element = PsiTreeUtil.getChildrenOfTypeAsList(element, PsiTypeElement.class).stream()
68+
.filter(candidate -> candidate.getType().equals(alternative)).findFirst().orElse(element);
69+
}
70+
warning.accept(element, "Unreachable catch block for " + PsiDiagnosticTypes.name(alternative)
71+
+ ". Only more specific exceptions are thrown and they are handled by previous catch block(s).");
72+
}
73+
}
74+
previous.addAll(alternatives);
75+
}
76+
}
77+
78+
private static boolean incompleteExecutable(PsiTryStatement statement) {
79+
var method = PsiTreeUtil.getParentOfType(statement, PsiMethod.class);
80+
var scope = method == null || method.getBody() == null ? statement : method.getBody();
81+
return PsiTreeUtil.findChildrenOfType(scope, PsiMethodCallExpression.class).stream().anyMatch(call -> call.resolveMethod() == null)
82+
|| PsiTreeUtil.findChildrenOfType(scope, PsiJavaCodeReferenceElement.class).stream()
83+
.anyMatch(reference -> (reference.getParent() instanceof PsiTypeElement || reference.getParent() instanceof PsiNewExpression) && reference.resolve() == null);
84+
}
85+
}

0 commit comments

Comments
 (0)