[java] Avoid NPE in CloseResourceRule (#4964, #4751)

Merge pull request #4964 from Monits:issue-4751
Fixes #4751
This commit is contained in:
Andreas Dangel 2024-04-18 20:58:12 +02:00
commit 75f1ee8582
No known key found for this signature in database
GPG Key ID: 93450DF2DF9A3FA3
2 changed files with 11 additions and 6 deletions

View File

@ -60,6 +60,7 @@ This is a {{ site.pmd.release_type }} release.
* [#4873](https://github.com/pmd/pmd/issues/4873): \[java] AvoidCatchingGenericException: Can no longer suppress on the exception itself
* java-errorprone
* [#2056](https://github.com/pmd/pmd/issues/2056): \[java] CloseResource false-positive with URLClassLoader in cast expression
* [#4751](https://github.com/pmd/pmd/issues/4751): \[java] PMD crashes when analyzing CloseResource Rule
* [#4928](https://github.com/pmd/pmd/issues/4928): \[java] EmptyCatchBlock false negative when allowCommentedBlocks=true
* java-performance
* [#3845](https://github.com/pmd/pmd/issues/3845): \[java] InsufficientStringBufferDeclaration should consider literal expression

View File

@ -51,6 +51,7 @@ import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil;
import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.types.InvocationMatcher;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
import net.sourceforge.pmd.properties.PropertyDescriptor;
@ -287,12 +288,15 @@ public class CloseResourceRule extends AbstractJavaRule {
private boolean isWrappingResourceSpecifiedInTry(ASTVariableId var) {
ASTVariableAccess wrappedVarName = getWrappedVariableName(var);
if (wrappedVarName != null) {
ASTVariableId referencedVar = wrappedVarName.getReferencedSym().tryGetNode();
if (referencedVar != null) {
List<ASTTryStatement> tryContainers = referencedVar.ancestors(ASTTryStatement.class).toList();
for (ASTTryStatement tryContainer : tryContainers) {
if (isTryWithResourceSpecifyingVariable(tryContainer, referencedVar)) {
return true;
JVariableSymbol referencedSym = wrappedVarName.getReferencedSym();
if (referencedSym != null) {
ASTVariableId referencedVar = referencedSym.tryGetNode();
if (referencedVar != null) {
List<ASTTryStatement> tryContainers = referencedVar.ancestors(ASTTryStatement.class).toList();
for (ASTTryStatement tryContainer : tryContainers) {
if (isTryWithResourceSpecifyingVariable(tryContainer, referencedVar)) {
return true;
}
}
}
}