[java] Avoid usage of deprecated methods

- getName() instead of getMethodName() or getVariableName()
- firstChild() instead of getFirstChildOfType()
- getRoot() instead of getFirstParentOfType(ASTCompilationUnit.class)
- children() instead of findChildrenOfType()
- no more addRuleChainVisit()
- ancestors() instead of getNthParent()
- descendants() instead of findDescendantsOfType()
This commit is contained in:
Andreas Dangel committed 2023-12-13 18:20:28 +01:00
1 parent e283f11551
commit 0fb4593234
25 files changed
+43 -54

No files matched your search

@@ -66,7 +66,7 @@ public final class ASTFieldDeclaration extends AbstractJavaNode
/**
* Returns the type node at the beginning of this field declaration.
* The type of this node is not necessarily the type of the variables,
* see {@link ASTVariableId#getType()}.
* see {@link ASTVariableId#getTypeNode()}.
*/
@Override
public ASTType getTypeNode() {
@@ -14,7 +14,7 @@ import net.sourceforge.pmd.lang.document.FileLocation;
* {@linkplain ASTForStatement foreach statements}.
*
* <p>This statement may define several variables, possibly of different types
* (see {@link ASTVariableId#getType()}). The nodes corresponding to
* (see {@link ASTVariableId#getTypeNode()}). The nodes corresponding to
* the declared variables are accessible through {@link #getVarIds()}.
*
* <pre class="grammar">
@@ -44,7 +44,7 @@ public interface ASTType extends TypeNode, Annotatable, LeftRecursiveNode {
/**
* Returns the number of array dimensions of this type.
* This is 0 unless this node {@linkplain #isArrayType()}.
* This is 0 unless this node is {@linkplain ASTArrayType}.
*/
@Deprecated
default int getArrayDepth() {
@@ -14,6 +14,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol;
import net.sourceforge.pmd.lang.java.types.JTypeMirror;
import net.sourceforge.pmd.lang.rule.xpath.DeprecatedAttribute;
// @formatter:off
@@ -291,7 +292,7 @@ public final class ASTVariableId extends AbstractTypedSymbolDeclarator<JVariable
* FormalParameter, LocalVariableDeclaration or FieldDeclaration).
*
* <p>The type of the returned node is not necessarily the type of this
* node. See {@link #getType()} for an explanation.
* node. See {@link #getTypeMirror()} for an explanation.
*
* @return the type node, or {@code null} if there is no explicit type,
* e.g. if {@link #isTypeInferred()} returns true.
@@ -327,7 +328,7 @@ public final class ASTVariableId extends AbstractTypedSymbolDeclarator<JVariable
// @formatter:on
@Override
@SuppressWarnings("PMD.UselessOverridingMethod")
public Class<?> getType() {
return super.getType();
public @NonNull JTypeMirror getTypeMirror() {
return super.getTypeMirror();
}
}
@@ -23,7 +23,7 @@ public interface TypeParamOwnerNode extends SymbolDeclaratorNode {
* there is none.
*/
default @Nullable ASTTypeParameters getTypeParameters() {
return getFirstChildOfType(ASTTypeParameters.class);
return firstChild(ASTTypeParameters.class);
}
@@ -427,7 +427,7 @@ public class LanguageLevelChecker<T> {
@Override
public Void visit(ASTStringLiteral node, T data) {
if (node.isStringLiteral() && SPACE_ESCAPE_PATTERN.matcher(node.getImage()).find()) {
if (SPACE_ESCAPE_PATTERN.matcher(node.getImage()).find()) {
check(node, RegularLanguageFeature.SPACE_STRING_ESCAPES, data);
}
if (node.isTextBlock()) {
@@ -560,7 +560,7 @@ public class LanguageLevelChecker<T> {
check(node, RegularLanguageFeature.PRIVATE_METHODS_IN_INTERFACES, data);
}
checkIdent(node, node.getMethodName(), data);
checkIdent(node, node.getName(), data);
return null;
}
@@ -73,11 +73,11 @@ public class NcssVisitor extends JavaVisitorBase<MutableInt, Void> {
@Override
public Void visit(ASTClassDeclaration node, MutableInt data) {
if (countImports) {
ASTCompilationUnit acu = node.getFirstParentOfType(ASTCompilationUnit.class);
List<ASTImportDeclaration> imports = acu.findChildrenOfType(ASTImportDeclaration.class);
ASTCompilationUnit acu = node.getRoot();
List<ASTImportDeclaration> imports = acu.children(ASTImportDeclaration.class).toList();
int increment = imports.size();
if (!acu.findChildrenOfType(ASTPackageDeclaration.class).isEmpty()) {
if (acu.children(ASTPackageDeclaration.class).nonEmpty()) {
increment++;
}
data.add(increment);
@@ -7,6 +7,8 @@ package net.sourceforge.pmd.lang.java.rule.codestyle;
import java.util.Arrays;
import java.util.Collection;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.NodeStream;
import net.sourceforge.pmd.lang.java.ast.ASTClassDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
@@ -15,6 +17,7 @@ import net.sourceforge.pmd.lang.java.ast.JModifier;
import net.sourceforge.pmd.lang.java.ast.ModifierOwner;
import net.sourceforge.pmd.lang.java.rule.AbstractIgnoredAnnotationRule;
import net.sourceforge.pmd.lang.java.rule.design.UseUtilityClassRule;
import net.sourceforge.pmd.lang.rule.RuleTargetSelector;
/**
* This rule detects non-static classes with no constructors;
@@ -24,8 +27,9 @@ import net.sourceforge.pmd.lang.java.rule.design.UseUtilityClassRule;
*/
public class AtLeastOneConstructorRule extends AbstractIgnoredAnnotationRule {
public AtLeastOneConstructorRule() {
addRuleChainVisit(ASTClassDeclaration.class);
@Override
protected @NonNull RuleTargetSelector buildTargetSelector() {
return RuleTargetSelector.forTypes(ASTClassDeclaration.class);
}
@Override
@@ -65,7 +65,7 @@ public class FieldNamingConventionsRule extends AbstractNamingConventionRule<AST
@Override
public Object visit(ASTFieldDeclaration node, Object data) {
for (ASTVariableId id : node) {
if (getProperty(EXCLUDED_NAMES).contains(id.getVariableName())) {
if (getProperty(EXCLUDED_NAMES).contains(id.getName())) {
continue;
}
ASTTypeDeclaration enclosingType = node.getEnclosingType();
@@ -20,7 +20,6 @@ public class LocalVariableCouldBeFinalRule extends AbstractJavaRulechainRule {
public LocalVariableCouldBeFinalRule() {
super(ASTLocalVariableDeclaration.class);
definePropertyDescriptor(IGNORE_FOR_EACH);
addRuleChainVisit(ASTLocalVariableDeclaration.class);
}
@Override
@@ -32,8 +32,6 @@ public final class LocalVariableNamingConventionsRule extends AbstractNamingConv
definePropertyDescriptor(localVarRegex);
definePropertyDescriptor(finalVarRegex);
definePropertyDescriptor(exceptionBlockParameterRegex);
addRuleChainVisit(ASTVariableId.class);
}
@@ -171,7 +171,7 @@ public class UnnecessaryImportRule extends AbstractJavaRule {
continue;
}
for (Pattern p : PATTERNS) {
Matcher m = p.matcher(comment.getImage());
Matcher m = p.matcher(comment.getText());
while (m.find()) {
String fullname = m.group(1);
@@ -40,7 +40,6 @@ public class UnnecessaryModifierRule extends AbstractJavaRulechainRule {
ASTResource.class,
ASTFieldDeclaration.class,
ASTConstructorDeclaration.class);
addRuleChainVisit(ASTRecordDeclaration.class);
}
@@ -79,7 +79,7 @@ public class AvoidBranchingStatementAsLastInLoopRule extends AbstractJavaRulecha
if (parent instanceof ASTFinallyClause) {
// get the parent of the block, in which the try statement is: ForStatement/Block/TryStatement/Finally
// e.g. a ForStatement
parent = parent.getNthParent(3);
parent = parent.ancestors().get(2);
}
}
if (parent instanceof ASTForStatement || parent instanceof ASTForeachStatement) {
@@ -546,7 +546,7 @@ public class CloseResourceRule extends AbstractJavaRule {
* where to search for if statements
* @param node
* the node, where the call for the close is done
* @param varName
* @param var
* the variable, that is maybe null-checked
* @return <code>true</code> if no if condition is involved or if the if
* condition is a null-check.
@@ -89,16 +89,16 @@ public class DoubleCheckedLockingRule extends AbstractJavaRule {
return data;
}
List<ASTIfStatement> isl = node.findDescendantsOfType(ASTIfStatement.class);
List<ASTIfStatement> isl = node.descendants(ASTIfStatement.class).toList();
if (isl.size() == 2) {
ASTIfStatement outerIf = isl.get(0);
if (JavaRuleUtil.isNullCheck(outerIf.getCondition(), returnVariable)) {
// find synchronized
List<ASTSynchronizedStatement> ssl = outerIf.findDescendantsOfType(ASTSynchronizedStatement.class);
List<ASTSynchronizedStatement> ssl = outerIf.descendants(ASTSynchronizedStatement.class).toList();
if (ssl.size() == 1 && ssl.get(0).ancestors().any(it -> it == outerIf)) {
ASTIfStatement is2 = isl.get(1);
if (JavaRuleUtil.isNullCheck(is2.getCondition(), returnVariable)) {
List<ASTAssignmentExpression> assignments = is2.findDescendantsOfType(ASTAssignmentExpression.class);
List<ASTAssignmentExpression> assignments = is2.descendants(ASTAssignmentExpression.class).toList();
if (assignments.size() == 1
&& JavaAstUtils.isReferenceToVar(assignments.get(0).getLeftOperand(), returnVariable)) {
asCtx(data).addViolation(node);
@@ -7,6 +7,7 @@ package net.sourceforge.pmd.lang.java.rule.xpath.internal;
import java.util.List;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.document.FileLocation;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.JavaComment;
import net.sourceforge.pmd.lang.rule.xpath.internal.AstElementNode;
@@ -63,9 +64,10 @@ public class GetCommentOnFunction extends BaseJavaXPathFunction {
int codeBeginLine = contextNode.getBeginLine();
int codeEndLine = contextNode.getEndLine();
List<JavaComment> commentList = contextNode.getFirstParentOfType(ASTCompilationUnit.class).getComments();
List<JavaComment> commentList = contextNode.ancestorsOrSelf().filterIs(ASTCompilationUnit.class).first().getComments();
for (JavaComment comment : commentList) {
if (comment.getBeginLine() == codeBeginLine || comment.getEndLine() == codeEndLine) {
FileLocation location = comment.getReportLocation();
if (location.getStartLine() == codeBeginLine || location.getEndLine() == codeEndLine) {
return new StringValue(comment.getText());
}
}
@@ -7,7 +7,6 @@ package net.sourceforge.pmd.lang.java.rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTVariableId;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
/**
* @author Clément Fournier
@@ -30,7 +29,7 @@ public class DummyJavaRule extends AbstractJavaRule {
@Override
public void apply(Node node, RuleContext ctx) {
((JavaNode) node).jjtAccept(this, ctx);
node.acceptVisitor(this, ctx);
}
@Override
@@ -7,7 +7,6 @@ package net.sourceforge.pmd.lang.java.types;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -38,10 +37,9 @@ class TypeTestUtilTest extends BaseParserTest {
ASTClassDeclaration klass =
java.parse("package org; import java.io.Serializable; "
+ "class FooBar implements Serializable {}")
.getFirstDescendantOfType(ASTClassDeclaration.class);
.descendants(ASTClassDeclaration.class).firstOrThrow();
assertNull(klass.getType());
assertTrue(TypeTestUtil.isA("org.FooBar", klass));
assertTrue(TypeTestUtil.isA("java.io.Serializable", klass));
assertTrue(TypeTestUtil.isA(Serializable.class, klass));
@@ -53,7 +51,7 @@ class TypeTestUtilTest extends BaseParserTest {
ASTAnnotation annot =
java.parse("import a.b.Test;"
+ "class FooBar { @Test void bar() {} }")
.getFirstDescendantOfType(ASTAnnotation.class);
.descendants(ASTAnnotation.class).firstOrThrow();
assertTrue(TypeTestUtil.isA("a.b.Test", annot));
assertTrue(TypeOps.isUnresolved(annot.getTypeMirror()));
@@ -74,7 +72,6 @@ class TypeTestUtilTest extends BaseParserTest {
.getFirstDescendantOfType(ASTEnumDeclaration.class);
assertNull(klass.getType());
assertTrue(TypeTestUtil.isA("org.FooBar", klass));
assertIsStrictSubtype(klass, Iterable.class);
assertIsStrictSubtype(klass, Enum.class);
@@ -155,7 +152,6 @@ class TypeTestUtilTest extends BaseParserTest {
.getFirstDescendantOfType(ASTAnnotationTypeDeclaration.class);
assertNull(klass.getType());
assertTrue(TypeTestUtil.isA("org.FooBar", klass));
assertIsA(klass, Annotation.class);
assertIsA(klass, Object.class);
@@ -237,7 +233,6 @@ class TypeTestUtilTest extends BaseParserTest {
ASTAnnotation annotation = java.parse("package org; import foo.Stuff; @Stuff public class FooBar {}")
.getFirstDescendantOfType(ASTAnnotation.class);
assertNull(annotation.getType());
assertTrue(TypeTestUtil.isA("foo.Stuff", annotation));
assertFalse(TypeTestUtil.isA("other.Stuff", annotation));
// we know it's not Stuff, it's foo.Stuff
@@ -4,6 +4,7 @@
package net.sourceforge.pmd.lang.java.ast
import io.kotest.matchers.shouldBe
import net.sourceforge.pmd.lang.ast.test.shouldBe
import net.sourceforge.pmd.lang.java.ast.JavaVersion.Companion.Earliest
import net.sourceforge.pmd.lang.java.ast.JavaVersion.Companion.Latest
@@ -37,7 +38,7 @@ class ASTAnnotationTest : ParserTestSpec({
it::getMemberList shouldBe null
it::getAnnotationName shouldBe "F"
it.typeNode.text.toString() shouldBe "F"
}
}
@@ -49,7 +50,7 @@ class ASTAnnotationTest : ParserTestSpec({
it::getMemberList shouldBe null
it::getAnnotationName shouldBe "java.lang.Override"
it.typeNode.text.toString() shouldBe "java.lang.Override"
}
}
@@ -61,7 +62,7 @@ class ASTAnnotationTest : ParserTestSpec({
it::getMemberList shouldBe null
it::getAnnotationName shouldBe "Override"
it.typeNode.text.toString() shouldBe "Override"
}
}
}
@@ -25,7 +25,7 @@ class ASTFieldDeclarationTest : ParserTestSpec({
it::getModifiers shouldBe modifiers { }
it.hasVisibility(ModifierOwner.Visibility.V_PUBLIC) shouldBe false
it::isSyntacticallyPublic shouldBe false
it.hasExplicitModifiers(JModifier.PUBLIC) shouldBe false
it.hasVisibility(ModifierOwner.Visibility.V_PACKAGE) shouldBe true
primitiveType(INT)
@@ -28,7 +28,6 @@ class ASTLiteralTest : ParserTestSpec({
"\"\"" should parseAs {
stringLit("\"\"") {
it::isStringLiteral shouldBe true
it::getConstValue shouldBe ""
}
}
@@ -214,7 +213,6 @@ $delim
"'c'" should parseAs {
charLit("'c'") {
it::isCharLiteral shouldBe true
it::getConstValue shouldBe 'c'
}
}
@@ -115,14 +115,6 @@ object CustomTreePrinter : KotlintestBeanTreePrinter<Node>(NodeTreeLikeAdapter)
private val javaImplicitAssertions: Assertions<Node> = {
DefaultMatchingConfig.implicitAssertions(it)
if (it is ASTLiteral) {
it::isNumericLiteral shouldBe (it is ASTNumericLiteral)
it::isCharLiteral shouldBe (it is ASTCharLiteral)
it::isStringLiteral shouldBe (it is ASTStringLiteral)
it::isBooleanLiteral shouldBe (it is ASTBooleanLiteral)
it::isNullLiteral shouldBe (it is ASTNullLiteral)
}
if (it is ASTExpression) run {
it::isParenthesized shouldBe (it.parenthesisDepth > 0)
}
@@ -16,6 +16,7 @@ import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken
import net.sourceforge.pmd.lang.ast.test.NodeSpec
import net.sourceforge.pmd.lang.ast.test.ValuedNodeSpec
import net.sourceforge.pmd.lang.ast.test.shouldBe
import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil
import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind
import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.*
@@ -111,7 +112,7 @@ fun TreeNodeWrapper<Node, *>.thisExpr(qualifier: ValuedNodeSpec<ASTThisExpressio
fun TreeNodeWrapper<Node, *>.variableId(name: String, otherAssertions: NodeSpec<ASTVariableId> = EmptyAssertions) =
child<ASTVariableId>(ignoreChildren = otherAssertions == EmptyAssertions) {
it::getVariableName shouldBe name
it::getName shouldBe name
otherAssertions()
}
@@ -120,7 +121,7 @@ fun TreeNodeWrapper<Node, *>.simpleLambdaParam(name: String, otherAssertions: No
it::getModifiers shouldBe modifiers { }
child<ASTVariableId>(ignoreChildren = otherAssertions == EmptyAssertions) {
it::getVariableName shouldBe name
it::getName shouldBe name
otherAssertions()
}
}
@@ -418,7 +419,7 @@ fun TreeNodeWrapper<Node, *>.arrayType(contents: NodeSpec<ASTArrayType> = EmptyA
fun TreeNodeWrapper<Node, *>.primitiveType(type: PrimitiveTypeKind, assertions: NodeSpec<ASTPrimitiveType> = EmptyAssertions) =
child<ASTPrimitiveType> {
it::getKind shouldBe type
it::getTypeImage shouldBe type.toString()
PrettyPrintingUtil.prettyPrintType(it) shouldBe type.toString();
assertions()
}
@@ -40,7 +40,7 @@ public class StatementAndBraceFinder {
this.dataFlow.createStartNode(node.getBeginLine()); // +1
this.dataFlow.createNewNode(node);
node.jjtAccept(this, dataFlow);
node.acceptVisitor(this, dataFlow);
this.dataFlow.createEndNode(node.getEndLine()); // +1
if (LOGGER.isLoggable(Level.FINE)) {