repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/TypeParamOwnerNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.symbols.JTypeParameterOwnerSymbol; /** * A symbol declaration, whose symbol can declare type parameters. * * @author Clément Fournier */ public interface TypeParamOwnerNode extends SymbolDeclaratorNode { @Override JTypeParameterOwnerSymbol getSymbol(); /** * Returns the type parameter declaration of this node, or null if * there is none. */ default @Nullable ASTTypeParameters getTypeParameters() { return getFirstChildOfType(ASTTypeParameters.class); } }
740
22.903226
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTStatementExpressionList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTNonEmptyList; /** * A list of statement expressions. Statement expressions are those * expressions which can appear in an {@linkplain ASTExpressionStatement expression statement}. * * * <p>Statement expression lists occur only {@link ASTForInit} and {@link ASTForUpdate}. * To improve the API of {@link ASTForInit}, however, this node implements {@link ASTStatement}. * * <pre class="grammar"> * * StatementExpressionList ::= {@link ASTExpression Expression} ( "," {@link ASTExpression Expression} )* * * </pre> */ public final class ASTStatementExpressionList extends ASTNonEmptyList<ASTExpression> implements ASTStatement { ASTStatementExpressionList(int id) { super(id, ASTExpression.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,071
29.628571
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTReferenceType.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a reference type, i.e. a {@linkplain ASTClassOrInterfaceType class or interface type}, * or an {@linkplain ASTArrayType array type}. * * <pre class="grammar"> * * ReferenceType ::= {@link ASTClassOrInterfaceType ClassOrInterfaceType} * | {@link ASTArrayType ArrayType} * | {@link ASTIntersectionType IntersectionType} * | {@link ASTUnionType UnionType} * | {@link ASTWildcardType WildcardType} * * </pre> */ public interface ASTReferenceType extends ASTType { }
694
29.217391
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTIfStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * Represents an {@code if} statement, possibly with an {@code else} statement. * * <pre class="grammar"> * * IfStatement ::= "if" "(" {@linkplain ASTExpression Expression} ")" {@linkplain ASTStatement Statement} * ( "else" {@linkplain ASTStatement Statement} )? * * </pre> */ public final class ASTIfStatement extends AbstractStatement { private boolean hasElse; ASTIfStatement(int id) { super(id); } void setHasElse() { this.hasElse = true; } /** * Returns true if this statement has an {@code else} clause. */ public boolean hasElse() { return this.hasElse; } /** * Returns the node that represents the guard of this conditional. * This may be any expression of type boolean. */ public ASTExpression getCondition() { return (ASTExpression) getChild(0); } /** * Returns the statement that will be run if the guard evaluates * to true. */ public ASTStatement getThenBranch() { return (ASTStatement) getChild(1); } /** * Returns the statement of the {@code else} clause, if any. */ public @Nullable ASTStatement getElseBranch() { return hasElse() ? (ASTStatement) getChild(2) : null; } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,642
21.506849
105
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTMethodCall.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A method invocation expression. This node represents both qualified (with a left-hand side) * and unqualified invocation expressions. * * <pre class="grammar"> * * * MethodCall ::= &lt;IDENTIFIER&gt; {@link ASTArgumentList ArgumentList} * | {@link ASTExpression Expression} "." {@link ASTTypeArguments TypeArguments}? &lt;IDENTIFIER&gt; {@link ASTArgumentList ArgumentList} * * </pre> */ public final class ASTMethodCall extends AbstractInvocationExpr implements ASTPrimaryExpression, QualifiableExpression, InvocationNode, MethodUsage { ASTMethodCall(int id) { super(id); } @Override public void jjtClose() { super.jjtClose(); // we need to set the name. if (getMethodName() != null || getChild(0) instanceof ASTSuperExpression) { return; } // Otherwise, the method call was parsed as an ambiguous name followed by arguments // The LHS stays ambiguous // the cast serves as an assert ASTAmbiguousName fstChild = (ASTAmbiguousName) getChild(0); fstChild.shrinkOrDeleteInParentSetImage(); assert getMethodName() != null; } @Override public @NonNull String getMethodName() { return super.getImage(); } @Override @NonNull public ASTArgumentList getArguments() { return (ASTArgumentList) getChild(getNumChildren() - 1); } @Override @Nullable public ASTTypeArguments getExplicitTypeArguments() { return getFirstChildOfType(ASTTypeArguments.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
2,038
25.141026
151
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTMemberValueArrayInitializer.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Iterator; /** * Represents an array of member values in an annotation {@linkplain ASTMemberValue member value}. * * <pre class="grammar"> * * MemberValueArrayInitializer ::= "{" ( {@linkplain ASTMemberValue MemberValue} ( "," {@linkplain ASTMemberValue MemberValue} )* ","? )? "}" * * </pre> * */ public final class ASTMemberValueArrayInitializer extends AbstractJavaNode implements Iterable<ASTMemberValue>, ASTMemberValue { ASTMemberValueArrayInitializer(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public Iterator<ASTMemberValue> iterator() { return children(ASTMemberValue.class).iterator(); } }
946
23.921053
142
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTDoStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a {@code do ... while} statement. * * * <pre class="grammar"> * * DoStatement ::= "do" {@linkplain ASTStatement Statement} "while" "(" {@linkplain ASTExpression Expression} ")" ";" * * </pre> */ public final class ASTDoStatement extends AbstractStatement implements ASTLoopStatement { ASTDoStatement(int id) { super(id); } /** * Returns the node that represents the guard of this loop. * This may be any expression of type boolean. */ @Override public ASTExpression getCondition() { return (ASTExpression) getChild(1); } /** * Returns the statement that will be run while the guard * evaluates to true. */ @Override public ASTStatement getBody() { return (ASTStatement) getChild(0); } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,098
21.428571
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/FunctionalExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; /** * A method reference or lambda expression. */ public interface FunctionalExpression extends ASTExpression { /** * Returns the type of the functional interface. * E.g. in {@code stringStream.map(s -> s.isEmpty())}, this is * {@code java.util.function.Function<java.lang.String, java.lang.Boolean>}. * * @see #getFunctionalMethod() */ @Override @NonNull JTypeMirror getTypeMirror(); /** * Returns the method that is overridden in the functional interface. * E.g. in {@code stringStream.map(s -> s.isEmpty())}, this is * {@code java.util.function.Function#apply(java.lang.String) -> * java.lang.Boolean} * * @see #getTypeMirror() */ JMethodSig getFunctionalMethod(); }
1,065
26.333333
80
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchArrowBranch.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A non-fallthrough switch rule, introduced with switch expressions. * See {@link ASTSwitchLike}. * * <pre class="grammar"> * * SwitchLabeledExpression ::= {@link ASTSwitchLabel SwitchLabel} "-&gt;" {@link ASTSwitchArrowRHS SwitchArrowRHS} * * </pre> */ public final class ASTSwitchArrowBranch extends AbstractJavaNode implements ASTSwitchBranch { ASTSwitchArrowBranch(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the right hand side of the arrow. */ public ASTSwitchArrowRHS getRightHandSide() { return (ASTSwitchArrowRHS) getLastChild(); } }
873
25.484848
114
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTRecordPattern.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.annotation.Experimental; /** * A record pattern (Java 19 Preview and Java 20 Preview). * * <pre class="grammar"> * * RecordPattern ::= {@linkplain ASTReferenceType ReferenceType} {@linkplain ASTComponentPatternList ComponentPatternList} * * </pre> * * @see ASTRecordDeclaration * @see <a href="https://openjdk.org/jeps/405">JEP 405: Record Patterns (Preview)</a> (Java 19) * @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a> (Java 20) */ @Experimental public final class ASTRecordPattern extends AbstractJavaNode implements ASTPattern { private int parenDepth; ASTRecordPattern(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Gets the type against which the expression is tested. */ public ASTReferenceType getTypeNode() { return getFirstChildOfType(ASTReferenceType.class); } /** Returns the declared variable. */ public ASTVariableDeclaratorId getVarId() { return getFirstChildOfType(ASTVariableDeclaratorId.class); } void bumpParenDepth() { parenDepth++; } @Override @Experimental public int getParenthesisDepth() { return parenDepth; } }
1,505
24.965517
122
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTImplementsList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTNonEmptyList; /** * Represents the {@code implements} clause of a class declaration. * * <pre class="grammar"> * * ImplementsList ::= "implements" {@link ASTClassOrInterfaceType ClassOrInterfaceType} ( "," {@link ASTClassOrInterfaceType ClassOrInterfaceType})* * * </pre> */ public final class ASTImplementsList extends ASTNonEmptyList<ASTClassOrInterfaceType> { ASTImplementsList(int id) { super(id, ASTClassOrInterfaceType.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
806
24.21875
148
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTEnumBody.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Body of an {@linkplain ASTEnumDeclaration enum declaration}. * * <pre class="grammar"> * * EnumBody ::= "{" * [ {@link ASTEnumConstant EnumConstant} ( "," ( {@link ASTEnumConstant EnumConstant} )* ] * [ "," ] * [ ";" ( {@link ASTBodyDeclaration ClassOrInterfaceBodyDeclaration} )* ] * "}" * * </pre> * * */ public final class ASTEnumBody extends ASTTypeBody { private boolean trailingComma; private boolean separatorSemi; ASTEnumBody(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } void setTrailingComma() { this.trailingComma = true; } void setSeparatorSemi() { this.separatorSemi = true; } /** * Returns true if the last enum constant has a trailing comma. * For example: * <pre>{@code * enum Foo { A, B, C, } * enum Bar { , } * }</pre> */ public boolean hasTrailingComma() { return trailingComma; } /** * Returns true if the last enum constant has a trailing semi-colon. * This semi is not optional when the enum has other members. * For example: * <pre>{@code * enum Foo { * A(2); * * Foo(int i) {...} * } * * enum Bar { A; } * enum Baz { ; } * }</pre> */ public boolean hasSeparatorSemi() { return separatorSemi; } }
1,669
20.973684
104
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAssertStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents an {@code assert} statement. * * <pre class="grammar"> * * AssertStatement ::= "assert" {@linkplain ASTExpression Expression} ( ":" {@linkplain ASTExpression Expression} )? ";" * * </pre> */ public final class ASTAssertStatement extends AbstractStatement { ASTAssertStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the expression tested by this assert statement. */ public ASTExpression getCondition() { return (ASTExpression) getChild(0); } /** * Returns true if this assert statement has a "detail message" * expression. In that case, {@link #getDetailMessageNode()} doesn't * return null. */ public boolean hasDetailMessage() { return getNumChildren() == 2; } /** * Returns the expression that corresponds to the detail message, * i.e. the expression after the colon, if it's present. */ public ASTExpression getDetailMessageNode() { return hasDetailMessage() ? (ASTExpression) getChild(1) : null; } }
1,346
23.053571
120
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTClassOrInterfaceBody.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents the body of a {@linkplain ASTClassOrInterfaceDeclaration class or interface declaration}. * This includes anonymous classes, including those defined within an {@linkplain ASTEnumConstant enum constant}. * * <pre class="grammar"> * * ClassOrInterfaceBody ::= "{" {@linkplain ASTBodyDeclaration ClassOrInterfaceBodyDeclaration}* "}" * * </pre> */ public final class ASTClassOrInterfaceBody extends ASTTypeBody { ASTClassOrInterfaceBody(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
794
25.5
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFormalParameters.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * A list of {@linkplain ASTFormalParameter formal parameters} in a * method or constructor declaration. Some formal parameter lists may * feature a {@linkplain ASTReceiverParameter receiver parameter}. That * is not treated as a regular formal parameter, as it does not declare * a variable. * * <pre class="grammar"> * * FormalParameters ::= "(" ")" * | "(" ({@link ASTReceiverParameter ReceiverParameter} | {@link ASTFormalParameter FormalParameter}) ("," {@link ASTFormalParameter FormalParameter})* ")" * * </pre> * */ public final class ASTFormalParameters extends ASTList<ASTFormalParameter> { ASTFormalParameters(int id) { super(id, ASTFormalParameter.class); } /** * Returns the number of formal parameters. * This excludes the receiver parameter, if any. */ @Override public int size() { return getFirstChild() instanceof ASTReceiverParameter ? getNumChildren() - 1 : getNumChildren(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the receiver parameter if it is present, otherwise returns * null. */ @Nullable public ASTReceiverParameter getReceiverParameter() { return AstImplUtil.getChildAs(this, 0, ASTReceiverParameter.class); } }
1,666
28.767857
176
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTryStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.NodeStream; /** * Try statement node. * * * <pre class="grammar"> * * TryStatement ::= "try" {@link ASTResourceList ResourceList}? * {@link ASTBlock Block} * {@link ASTCatchClause CatchClause}* * {@link ASTFinallyClause FinallyClause}? * * </pre> */ public final class ASTTryStatement extends AbstractStatement { ASTTryStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns true if this node is a try-with-resources, in which case it * has a ResourceSpecification child node. */ public boolean isTryWithResources() { return getChild(0) instanceof ASTResourceList; } /** * Returns the node for the resource list. This is null if this is * not a try-with-resources. */ @Nullable public ASTResourceList getResources() { return AstImplUtil.getChildAs(this, 0, ASTResourceList.class); } /** * Returns the body of this try statement. */ public ASTBlock getBody() { return children(ASTBlock.class).first(); } /** * Returns the catch statement nodes of this try statement. * If there are none, returns an empty list. */ public NodeStream<ASTCatchClause> getCatchClauses() { return children(ASTCatchClause.class); } /** * Returns the {@code finally} clause of this try statement, if any. * * @return The finally statement, or null if there is none */ @Nullable public ASTFinallyClause getFinallyClause() { return getFirstChildOfType(ASTFinallyClause.class); } }
2,005
23.168675
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTCastExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a type cast expression. This is syntactically a unary prefix * operation and has the same precedence. * * <pre class="grammar"> * * CastExpression ::= "(" {@link ASTType Type} ")" {@linkplain ASTExpression Expression} * * </pre> */ public final class ASTCastExpression extends AbstractJavaExpr implements ASTExpression { ASTCastExpression(int id) { super(id); } public ASTType getCastType() { return getFirstChildOfType(ASTType.class); } public ASTExpression getOperand() { return (ASTExpression) getChild(getNumChildren() - 1); } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
895
23.888889
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTUnaryExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a unary operation on a value. The syntactic form may be * prefix or postfix, which are represented with the same nodes, even * though they have different precedences. * * <pre class="grammar"> * * UnaryExpression ::= PrefixExpression | PostfixExpression * * PrefixExpression ::= {@link UnaryOp PrefixOp} {@link ASTExpression Expression} * * PostfixExpression ::= {@link ASTExpression Expression} {@link UnaryOp PostfixOp} * * </pre> */ public final class ASTUnaryExpression extends AbstractJavaExpr { private UnaryOp operator; ASTUnaryExpression(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the expression nested within this expression. */ public ASTExpression getOperand() { return (ASTExpression) getChild(0); } /** * Returns true if this is a prefix expression. * * @deprecated XPath-attribute only, use {@code getOperator().isPrefix()} in java code. */ @Deprecated public boolean isPrefix() { return getOperator().isPrefix(); } /** Returns the constant representing the operator of this expression. */ public UnaryOp getOperator() { return operator; } void setOp(UnaryOp op) { this.operator = op; } }
1,546
23.171875
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTLabeledStatement.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * A wrapper around a statement that assigns it a label. * * <pre class="grammar"> * * LabeledStatement ::= &lt;IDENTIFIER&gt; ":" {@link ASTStatement Statement} * * </pre> */ public final class ASTLabeledStatement extends AbstractStatement { ASTLabeledStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the name of the label. */ public String getLabel() { return getImage(); } /** * Returned the statement named by this label. */ public ASTStatement getStatement() { return (ASTStatement) getChild(0); } }
883
19.55814
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JavaParser.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.AstInfo; import net.sourceforge.pmd.lang.ast.ParseException; import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior; import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeParserAdapter; import net.sourceforge.pmd.lang.java.ast.internal.LanguageLevelChecker; import net.sourceforge.pmd.lang.java.ast.internal.ReportingStrategy; import net.sourceforge.pmd.lang.java.internal.JavaAstProcessor; import net.sourceforge.pmd.lang.java.internal.JavaLanguageProcessor; import net.sourceforge.pmd.lang.java.internal.JavaLanguageProperties; /** * Adapter for the JavaParser, using the specified grammar version. * * @author Pieter_Van_Raemdonck - Application Engineers NV/SA - www.ae.be * @author Andreas Dangel */ public class JavaParser extends JjtreeParserAdapter<ASTCompilationUnit> { private final String suppressMarker; private final JavaLanguageProcessor javaProcessor; private final boolean postProcess; public JavaParser(String suppressMarker, JavaLanguageProcessor javaProcessor, boolean postProcess) { this.suppressMarker = suppressMarker; this.javaProcessor = javaProcessor; this.postProcess = postProcess; } @Override protected TokenDocumentBehavior tokenBehavior() { return JavaTokenDocumentBehavior.INSTANCE; } @Override protected ASTCompilationUnit parseImpl(CharStream cs, ParserTask task) throws ParseException { LanguageVersion version = task.getLanguageVersion(); int jdkVersion = JavaLanguageProperties.getInternalJdkVersion(version); boolean preview = JavaLanguageProperties.isPreviewEnabled(version); JavaParserImpl parser = new JavaParserImpl(cs); parser.setSuppressMarker(suppressMarker); parser.setJdkVersion(jdkVersion); parser.setPreview(preview); ASTCompilationUnit root = parser.CompilationUnit(); root.setAstInfo(new AstInfo<>(task, root).withSuppressMap(parser.getSuppressMap())); LanguageLevelChecker<?> levelChecker = new LanguageLevelChecker<>(jdkVersion, preview, // TODO change this strategy with a new lang property ReportingStrategy.reporterThatThrows()); levelChecker.check(root); if (postProcess) { JavaAstProcessor.process(javaProcessor, task.getReporter(), root); } return root; } }
2,818
36.586667
98
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTVariableAccess.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.types.JVariableSig; /** * An unqualified reference to a variable (either local, or a field that * is in scope). * * <pre class="grammar"> * * VariableAccess ::= &lt;IDENTIFIER&gt; * * </pre> * * @implNote {@linkplain ASTAmbiguousName Ambiguous names} are promoted * to this status in the syntactic contexts, where we know they're definitely * variable references. */ public final class ASTVariableAccess extends AbstractJavaExpr implements ASTNamedReferenceExpr { private JVariableSig typedSym; /** * Constructor promoting an ambiguous name to a variable reference. */ ASTVariableAccess(ASTAmbiguousName name) { super(JavaParserImplTreeConstants.JJTVARIABLEACCESS); setImage(name.getFirstToken().getImage()); } ASTVariableAccess(JavaccToken identifier) { super(JavaParserImplTreeConstants.JJTVARIABLEACCESS); TokenUtils.expectKind(identifier, JavaTokenKinds.IDENTIFIER); setImage(identifier.getImage()); setFirstToken(identifier); setLastToken(identifier); } ASTVariableAccess(int id) { super(id); } @Override public String getName() { return getImage(); } @Override public @Nullable JVariableSig getSignature() { if (typedSym == null) { forceTypeResolution(); // this will do it only once, even if it fails } return typedSym; } void setTypedSym(JVariableSig sig) { this.typedSym = sig; assert typedSym != null : "Null signature?"; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
2,097
25.556962
96
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTTypeExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AtLeastOneChild; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypingContext; /** * Wraps a type node but presents the interface of {@link ASTExpression}. * This is only used in the following contexts: * <ul> * <li>As the right-hand side of {@link BinaryOp#INSTANCEOF instanceof expressions}. * <li>As the qualifier of {@linkplain ASTMethodCall method calls}, * {@link ASTFieldAccess field accesses}, when they access a static method or field * <li>As the qualifier of {@linkplain ASTMethodReference method references}, * if it references a static method, or is a constructor reference * </ul> * * <pre class="grammar"> * * TypeExpression ::= {@link ASTType Type} * * </pre> */ public final class ASTTypeExpression extends AbstractJavaNode implements ASTPrimaryExpression, AtLeastOneChild, LeftRecursiveNode { ASTTypeExpression(int id) { super(id); } ASTTypeExpression(ASTType wrapped) { this(JavaParserImplTreeConstants.JJTTYPEEXPRESSION); this.addChild((AbstractJavaNode) wrapped, 0); copyTextCoordinates((AbstractJavaNode) wrapped); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Gets the wrapped type node. */ public ASTType getTypeNode() { return (ASTType) getChild(0); } /** Returns 0, type expressions can never be parenthesized. */ @Override public int getParenthesisDepth() { return 0; } /** Returns false, type expressions can never be parenthesized. */ @Override public boolean isParenthesized() { return false; } @Override public @NonNull JTypeMirror getTypeMirror(TypingContext ctx) { return getTypeNode().getTypeMirror(ctx); } }
2,124
28.513889
131
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/JModifier.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Locale; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; /** * A Java modifier. The ordering of constants respects the ordering * recommended by the JLS. */ // Note: the class is named JModifier and not Modifier to avoid conflict // with java.lang.reflect.Modifier public enum JModifier { // for anything PUBLIC(Modifier.PUBLIC), PROTECTED(Modifier.PROTECTED), PRIVATE(Modifier.PRIVATE), /** Modifier {@code "sealed"} (preview feature of JDK 15). */ SEALED(0), /** Modifier {@code "non-sealed"} (preview feature of JDK 15). */ NON_SEALED("non-sealed", 0), ABSTRACT(Modifier.ABSTRACT), STATIC(Modifier.STATIC), FINAL(Modifier.FINAL), // for methods SYNCHRONIZED(Modifier.SYNCHRONIZED), NATIVE(Modifier.NATIVE), DEFAULT(0), // not for fields STRICTFP(Modifier.STRICT), // for fields TRANSIENT(Modifier.TRANSIENT), VOLATILE(Modifier.VOLATILE); private final String token; private final int reflect; JModifier(int reflect) { this.token = name().toLowerCase(Locale.ROOT); this.reflect = reflect; } JModifier(String token, int reflect) { this.token = token; this.reflect = reflect; } /** * Returns the constant of java.lang.reflect.Modifier that this * modifier corresponds to. Be aware that the following constants * are source-level modifiers only, for which this method returns 0: * <ul> * <li>{@link #DEFAULT}: this doesn't exist at the class file level. * A default method is a non-static non-abstract public method declared * in an interface ({@link JMethodSymbol#isDefaultMethod()}. * <li>{@link #SEALED}: a sealed class has an attribute {@code PermittedSubclasses} * with a non-zero length (in the compiled class file) * <li>{@link #NON_SEALED}: this doesn't exist at the class file level at all. * But a class must have the non-sealed modifier in source if it * is neither sealed, nor final, and appears in the {@code PermittedSubclasses} * attribute of some direct supertype. * </ul> */ public int getReflectMod() { return reflect; } /** * Returns how the modifier is written in source. */ public String getToken() { return token; } @Override public String toString() { return getToken(); } public static int toReflect(Collection<JModifier> mods) { int res = 0; for (JModifier mod : mods) { res |= mod.getReflectMod(); } return res; } /** * Gets a modifier from its name. * * @throws IllegalArgumentException if the name is incorrect */ public static @NonNull JModifier fromToken(@NonNull String token) { return valueOf(token.toLowerCase(Locale.ROOT)); } }
3,141
26.321739
87
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArgumentList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTMaybeEmptyListOf; /** * The argument list of a {@linkplain ASTMethodCall method}, {@linkplain ASTConstructorCall constructor call}, * or {@linkplain ASTExplicitConstructorInvocation explicit constructor invocation}. * * <pre class="grammar"> * * ArgumentList ::= "(" ( {@link ASTExpression Expression} ( "," {@link ASTExpression Expression})* )? ")" * * </pre> */ public final class ASTArgumentList extends ASTMaybeEmptyListOf<ASTExpression> { ASTArgumentList(int id) { super(id, ASTExpression.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
873
28.133333
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/InvocationNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; /** * Groups {@linkplain ASTMethodCall method} and {@linkplain ASTConstructorCall constructor call}, * together, as well as {@linkplain ASTExplicitConstructorInvocation explicit constructor invocation statements}, * and {@linkplain ASTEnumConstant enum constant declarations}. * Those last two are included, because they are special syntax * to call a constructor. * * <p>The arguments of the invocation are said to be in an "invocation context", * which influences what conversions they are subject to. It also * means the type of the arguments may depend on the resolution * of the {@linkplain #getMethodType() compile-time declaration} * of this node. */ public interface InvocationNode extends TypeNode, MethodUsage { /** * Returns the node representing the list of arguments * passed to the invocation. Can be null if this is an * {@link ASTEnumConstant}. */ @Nullable ASTArgumentList getArguments(); /** * Returns the explicit type arguments if they exist. */ @Nullable ASTTypeArguments getExplicitTypeArguments(); /** * Gets the type of the method or constructor that is called by * this node. See {@link OverloadSelectionResult#getMethodType()}. */ default JMethodSig getMethodType() { return getOverloadSelectionInfo().getMethodType(); } /** * Returns information about the overload selection for this call. * Be aware, that selection might have failed ({@link OverloadSelectionResult#isFailed()}). */ OverloadSelectionResult getOverloadSelectionInfo(); }
1,915
30.933333
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTConditionalExpression.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Represents a conditional expression, aka ternary expression. * * <pre class="grammar"> * * ConditionalExpression ::= {@linkplain ASTExpression Expression} "?" {@linkplain ASTExpression Expression} ":" {@linkplain ASTExpression Expression} * * </pre> */ public final class ASTConditionalExpression extends AbstractJavaExpr { private boolean isStandalone; ASTConditionalExpression(int id) { super(id); } /** * Returns the node that represents the guard of this conditional. * That is the expression before the '?'. */ public ASTExpression getCondition() { return (ASTExpression) getChild(0); } /** * Returns the node that represents the expression that will be evaluated * if the guard evaluates to true. */ public ASTExpression getThenBranch() { return (ASTExpression) getChild(1); } /** * Returns the node that represents the expression that will be evaluated * if the guard evaluates to false. */ public ASTExpression getElseBranch() { return (ASTExpression) getChild(2); } @Override public <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Note: this method is not used at all in pre-Java 8 analysis, * because standalone/poly exprs weren't formalized before java 8. * Calling this method then is undefined. */ // very internal boolean isStandalone() { assert getLanguageVersion().compareToVersion("8") >= 0 : "This method's result is undefined in pre java 8 code"; return this.isStandalone; } void setStandaloneTernary() { this.isStandalone = true; } }
1,912
24.851351
151
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTModuleDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.NodeStream; /** * A module declaration. This is found at the top-level of a * {@linkplain ASTCompilationUnit modular compilation unit}. * * <pre clas="grammar"> * * ModuleDeclaration ::= {@linkplain ASTModifierList AnnotationList} "open"? * "module" {@linkplain ASTModuleName ModuleName} * "{" {@linkplain ASTModuleDirective ModuleDirective}* "}" * * </pre> */ public final class ASTModuleDeclaration extends AbstractJavaNode implements Annotatable { private boolean open; ASTModuleDeclaration(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the name of the declared module. Module names look * like package names, eg {@code java.base}. */ public String getName() { return firstChild(ASTModuleName.class).getName(); } /** * Returns a stream with all directives declared by the module. */ public NodeStream<ASTModuleDirective> getDirectives() { return children(ASTModuleDirective.class); } void setOpen(boolean open) { this.open = open; } public boolean isOpen() { return open; } }
1,474
24.431034
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTMethodOrConstructorDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.impl.GenericNode; import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JMethodSig; /** * Groups method and constructor declarations under a common type. * * <pre class="grammar"> * * MethodOrConstructorDeclaration ::= {@link ASTMethodDeclaration MethodDeclaration} * | {@link ASTConstructorDeclaration ConstructorDeclaration} * * </pre> * * @author Clément Fournier * @since 5.8.1 */ public interface ASTMethodOrConstructorDeclaration extends AccessNode, ASTBodyDeclaration, TypeParamOwnerNode, GenericNode<JavaNode>, JavadocCommentOwner { @Override JExecutableSymbol getSymbol(); /** * Returns the generic signature for the method. This is a {@link JMethodSig} * declared in the {@linkplain JClassType#getGenericTypeDeclaration() generic type declaration} * of the enclosing type. The signature may mention type parameters * of the enclosing types, and its own type parameters. */ JMethodSig getGenericSignature(); /** * Returns the name of the method, or the simple name of the declaring class for * a constructor declaration. */ String getName(); /** * Returns true if this method is abstract, so doesn't * declare a body. Interface members are * implicitly abstract, whether they declare the * {@code abstract} modifier or not. Default interface * methods are not abstract though, consistently with the * standard reflection API. */ // TODO is this relevant? @Override default boolean isAbstract() { return hasModifiers(JModifier.ABSTRACT); } /** * Returns the formal parameters node of this method or constructor. */ @NonNull default ASTFormalParameters getFormalParameters() { return getFirstChildOfType(ASTFormalParameters.class); } /** * Returns the number of formal parameters expected by this declaration. * This excludes any receiver parameter, which is irrelevant to arity. */ default int getArity() { return getFormalParameters().size(); } /** * Returns the body of this method or constructor. Returns null if * this is the declaration of an abstract method. */ @Nullable default ASTBlock getBody() { JavaNode last = getLastChild(); return last instanceof ASTBlock ? (ASTBlock) last : null; } /** * Returns the {@code throws} clause of this declaration, or null * if there is none. */ @Nullable default ASTThrowsList getThrowsList() { return getFirstChildOfType(ASTThrowsList.class); } /** * Returns true if this node's last formal parameter is varargs. */ default boolean isVarargs() { JavaNode lastFormal = getFormalParameters().getLastChild(); return lastFormal instanceof ASTFormalParameter && ((ASTFormalParameter) lastFormal).isVarargs(); } }
3,395
28.025641
105
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTSwitchBranch.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; /** * A branch of a {@link ASTSwitchLike SwitchLike}. * * <pre class="grammar"> * * SwitchBranch ::= {@link ASTSwitchArrowBranch SwitchArrowBranch} * | {@link ASTSwitchFallthroughBranch FallthroughBranch} * * </pre> */ public interface ASTSwitchBranch extends JavaNode { /** * Returns the label, which may be compound. */ default ASTSwitchLabel getLabel() { return (ASTSwitchLabel) getFirstChild(); } /** Return true if this is the default branch. */ default boolean isDefault() { return getLabel().isDefault(); } /** Returns the next branch, if it exists. */ default @Nullable ASTSwitchBranch getNextBranch() { return (ASTSwitchBranch) getNextSibling(); } /** Returns the previous branch, if it exists. */ default @Nullable ASTSwitchBranch getPreviousBranch() { JavaNode prev = getPreviousSibling(); return prev instanceof ASTSwitchBranch ? (ASTSwitchBranch) prev : null; } }
1,198
25.644444
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTFieldDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.rule.xpath.DeprecatedAttribute; /** * Represents a field declaration in the body of a type declaration. * * <p>This declaration may define several variables, possibly of different * types. The nodes corresponding to the declared variables are accessible * through {@link #iterator()}. * * <pre class="grammar"> * * FieldDeclaration ::= {@link ASTModifierList ModifierList} {@linkplain ASTType Type} {@linkplain ASTVariableDeclarator VariableDeclarator} ( "," {@linkplain ASTVariableDeclarator VariableDeclarator} )* ";" * * </pre> */ public final class ASTFieldDeclaration extends AbstractJavaNode implements Iterable<ASTVariableDeclaratorId>, LeftRecursiveNode, AccessNode, ASTBodyDeclaration, InternalInterfaces.MultiVariableIdOwner, JavadocCommentOwner { ASTFieldDeclaration(int id) { super(id); } @Override public FileLocation getReportLocation() { // report on the identifier and not the annotations return getVarIds().firstOrThrow().getFirstToken().getReportLocation(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Gets the variable name of this field. This method searches the first * VariableDeclaratorId node and returns its image or <code>null</code> if * the child node is not found. * * @return a String representing the name of the variable * * @deprecated FieldDeclaration may declare several variables, so this is not exhaustive * Iterate on the {@linkplain ASTVariableDeclaratorId VariableDeclaratorIds} instead */ @Deprecated @DeprecatedAttribute(replaceWith = "VariableDeclaratorId/@Name") public String getVariableName() { return getVarIds().firstOrThrow().getName(); } /** * 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 ASTVariableDeclaratorId#getType()}. */ @Override public ASTType getTypeNode() { return getFirstChildOfType(ASTType.class); } }
2,475
31.155844
207
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTConstructorDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.java.symbols.JConstructorSymbol; /** * A constructor of a {@linkplain ASTConstructorDeclaration class} or * {@linkplain ASTEnumDeclaration enum} declaration. * * <pre class="grammar"> * * ConstructorDeclaration ::= {@link ASTModifierList ModifierList} * {@link ASTTypeParameters TypeParameters}? * &lt;IDENTIFIER&gt; * {@link ASTFormalParameters FormalParameters} * ({@link ASTThrowsList ThrowsList})? * {@link ASTBlock Block} * * </pre> */ public final class ASTConstructorDeclaration extends AbstractMethodOrConstructorDeclaration<JConstructorSymbol> { ASTConstructorDeclaration(int id) { super(id); } @Override public String getName() { return getImage(); } @Override public FileLocation getReportLocation() { return getModifiers().getLastToken().getNext().getReportLocation(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public boolean containsComment() { return getBody().containsComment(); } @Override public @NonNull ASTBlock getBody() { return (ASTBlock) getLastChild(); } }
1,625
26.559322
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAnnotationMemberList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTMaybeEmptyListOf; /** * Represents the list of {@link ASTMemberValuePair member-value pairs} * in an {@link ASTAnnotation annotation}. * * <pre class="grammar"> * * AnnotationMemberList ::= "(" {@link ASTMemberValuePair MemberValuePair} ( "," {@link ASTMemberValuePair MemberValuePair} )* ")" * | "(" {@link ASTMemberValuePair ValueShorthand} ")" * | "(" ")" * * </pre> */ public final class ASTAnnotationMemberList extends ASTMaybeEmptyListOf<ASTMemberValuePair> { ASTAnnotationMemberList(int id) { super(id, ASTMemberValuePair.class); } /** * Returns the value of the attribute with the given name, returns * null if no such attribute was mentioned. * * @param attrName Name of an attribute */ public ASTMemberValue getAttribute(String attrName) { return toStream().filter(it -> it.getName().equals(attrName)).map(ASTMemberValuePair::getValue).first(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,320
30.452381
130
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTExtendsList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTNonEmptyList; /** * Represents the {@code extends} clause of a class or interface declaration. * If the parent is an interface declaration, then these types are all interface * types. Otherwise, then this list contains exactly one element. * * <pre class="grammar"> * * ExtendsList ::= "extends" {@link ASTType Type} ( "," {@link ASTType Type} )* * </pre> */ public final class ASTExtendsList extends ASTNonEmptyList<ASTClassOrInterfaceType> { ASTExtendsList(int id) { super(id, ASTClassOrInterfaceType.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
885
25.848485
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTResource.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; /** * A resource of a {@linkplain ASTTryStatement try-with-resources}. This contains another * node that represents the resource, according to the grammar below. * * <p>In the case of concise try-with resources, the subexpressions are * required to be only field accesses or variable references to compile. * * <pre class="grammar"> * * Resource ::= {@link ASTLocalVariableDeclaration LocalVariableDeclaration} * | {@link ASTPrimaryExpression PrimaryExpression} * * </pre> */ public final class ASTResource extends AbstractJavaNode { ASTResource(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns true if this appears as an expression, and not as a * local variable declaration. */ public boolean isConciseResource() { return getChild(0) instanceof ASTExpression; } /** * Gets the name with which the resource can be accessed in the * body of the try statement. If this is a {@linkplain #isConciseResource() concise resource}, * then returns the sequence of names that identifies the expression. * If this has a local variable declaration, then returns the name * of the variable. */ public String getStableName() { if (isConciseResource()) { ASTExpression expr = getInitializer(); StringBuilder builder = new StringBuilder(); while (expr instanceof ASTFieldAccess) { ASTFieldAccess fa = (ASTFieldAccess) expr; builder.insert(0, "." + fa.getName()); expr = fa.getQualifier(); } // the last one may be ambiguous, or a variable reference // the only common interface we have to get their name is // unfortunately Node::getImage if (expr != null) { builder.insert(0, expr.getImage()); } return builder.toString(); } else { return asLocalVariableDeclaration().iterator().next().getName(); } } @Nullable public ASTLocalVariableDeclaration asLocalVariableDeclaration() { return AstImplUtil.getChildAs(this, 0, ASTLocalVariableDeclaration.class); } /** * Returns the initializer of the expression. * If this is a concise resource, then returns that expression. * If this is a local variable declaration, returns the initializer of * the variable. */ public ASTExpression getInitializer() { Node c = getChild(0); if (c instanceof ASTExpression) { return (ASTExpression) c; } else { return ((ASTLocalVariableDeclaration) c).iterator().next().getInitializer(); } } }
3,093
31.568421
98
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTAnyTypeDeclaration.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import static net.sourceforge.pmd.lang.java.ast.JModifier.ABSTRACT; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.rule.xpath.DeprecatedAttribute; /** * Groups class, enum, record, annotation and interface declarations under a common * supertype. * * <pre class="grammar"> * * AnyTypeDeclaration ::= {@link ASTClassOrInterfaceDeclaration ClassOrInterfaceDeclaration} * | {@link ASTAnonymousClassDeclaration AnonymousClassDeclaration} * | {@link ASTEnumDeclaration EnumDeclaration} * | {@link ASTAnnotationTypeDeclaration AnnotationTypeDeclaration} * | {@link ASTRecordDeclaration RecordDeclaration} * * </pre> */ public interface ASTAnyTypeDeclaration extends TypeNode, AccessNode, TypeParamOwnerNode, ASTBodyDeclaration, ASTTopLevelDeclaration, FinalizableNode, JavadocCommentOwner { @Override @NonNull JClassSymbol getSymbol(); /** * Returns the {@linkplain JClassType#getGenericTypeDeclaration() generic type declaration} * of the declared type. Note that for {@linkplain ASTAnonymousClassDeclaration anonymous classes}, * this returns a class type whose symbol is the actual anonymous * class. Eg {@code new Runnable() { void foo() { } void run() { } }} * would present both methods, ie not just be a {@code Runnable}. * The {@link ASTConstructorCall} would have type {@code Runnable} * though, not the anonymous class. */ @Override @NonNull JClassType getTypeMirror(); /** * Returns the simple name of this type declaration. Returns the * empty string if this is an anonymous class declaration. */ @NonNull default String getSimpleName() { return getImage(); } /** * @deprecated Use {@link #getSimpleName()} */ @Deprecated @DeprecatedAttribute(replaceWith = "@SimpleName") @Override String getImage(); /** * Returns the name of the package in which this class is declared. */ default String getPackageName() { return getRoot().getPackageName(); } /** * Returns the binary name of this type declaration. This * is like {@link Class#getName()}. */ @NonNull String getBinaryName(); /** * Returns the canonical name of this class, if it exists. * Otherwise returns null. This is like {@link Class#getCanonicalName()}. * * <p>A canonical name exists if all enclosing types have a * canonical name, and this is neither a local class nor an * anonymous class. For example: * * <pre>{@code * package p; * * public class A { // p.A * class M { // p.A.M * { * class Local { // null, local class * class M2 {} // null, member of a local class * } * * new Local() { // null, anonymous class * class M2 {} // null, member of an anonymous class * }; * } * } * * } * }</pre> * * * So non-local/anonymous classes declared * somewhere in a local/anonymous class also have no loc */ @Nullable String getCanonicalName(); /** * Returns true if this is an abstract type. Interfaces and annotations * types are implicitly abstract. */ @Override default boolean isAbstract() { return hasModifiers(ABSTRACT); } /** * Returns the enum constants declared by this enum. If this is not * an enum declaration, returns an empty stream. */ default NodeStream<ASTEnumConstant> getEnumConstants() { return getFirstChildOfType(ASTEnumBody.class).children(ASTEnumConstant.class); } /** * Returns the record components declared by this class. If this is not * a record declaration, returns null. */ default @Nullable ASTRecordComponentList getRecordComponents() { return null; } /** * Retrieves the member declarations (fields, methods, classes, etc.) * from the body of this type declaration. */ default NodeStream<ASTBodyDeclaration> getDeclarations() { return getBody().toStream(); } /** * Returns the declarations of a particular type. * * @param klass Type of the declarations * @param <T>Type of the declarations */ default <T extends ASTBodyDeclaration> NodeStream<T> getDeclarations(Class<? extends T> klass) { return getDeclarations().filterIs(klass); } /** * Returns the operations declared in this class (methods and constructors). */ default NodeStream<ASTMethodOrConstructorDeclaration> getOperations() { return getDeclarations().filterIs(ASTMethodOrConstructorDeclaration.class); } /** * Returns the body of this type declaration. */ default ASTTypeBody getBody() { return (ASTTypeBody) getLastChild(); } /** * Returns true if this type declaration is nested inside an interface, * class or annotation. */ default boolean isNested() { return getParent() instanceof ASTTypeBody; } /** * Returns true if the class is declared inside a block other * than the body of another class, or the top level. Anonymous * classes are not considered local. Only class declarations * can be local. Local classes cannot be static. */ default boolean isLocal() { return getParent() instanceof ASTLocalClassStatement; } /** * Returns true if this type is declared at the top-level of a file. */ default boolean isTopLevel() { return getParent() instanceof ASTCompilationUnit; } /** * Returns true if this is an {@linkplain ASTAnonymousClassDeclaration anonymous class declaration}. */ default boolean isAnonymous() { return this instanceof ASTAnonymousClassDeclaration; } /** * Returns true if this is an {@linkplain ASTEnumDeclaration enum class declaration}. */ default boolean isEnum() { return this instanceof ASTEnumDeclaration; } /** * Returns true if this is an {@linkplain ASTRecordDeclaration record class declaration}. */ default boolean isRecord() { return this instanceof ASTRecordDeclaration; } /** * Returns true if this is an interface type declaration (including * annotation types). This is consistent with {@link Class#isInterface()}. */ default boolean isInterface() { return false; } /** * Returns true if this is a regular class declaration (not an enum, * not a record, not an interface or annotation). Note that eg * {@link JClassSymbol#isClass()} counts records and enums in, just * like {@link #isInterface()} counts annotations in. */ default boolean isRegularClass() { return false; } /** * Returns true if this is a regular interface declaration (not an annotation). * Note that {@link #isInterface()} counts annotations in. */ default boolean isRegularInterface() { return false; } /** Returns true if this is an {@linkplain ASTAnnotationTypeDeclaration annotation type declaration}. */ default boolean isAnnotation() { return this instanceof ASTAnnotationTypeDeclaration; } /** * Returns the list of interfaces implemented by this class, or * extended by this interface. Returns null if no such list is declared. */ default @NonNull NodeStream<ASTClassOrInterfaceType> getSuperInterfaceTypeNodes() { return ASTList.orEmptyStream(isInterface() ? firstChild(ASTExtendsList.class) : firstChild(ASTImplementsList.class)); } }
8,364
28.350877
108
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTVariableDeclarator.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Groups a variable ID and its initializer if it exists. * May be found as a child of {@linkplain ASTFieldDeclaration field declarations} and * {@linkplain ASTLocalVariableDeclaration local variable declarations}. * * <p>The {@linkplain #getInitializer() initializer} is the only place * {@linkplain ASTArrayInitializer array initializer expressions} can be found. * * <pre class="grammar"> * * VariableDeclarator ::= {@linkplain ASTVariableDeclaratorId VariableDeclaratorId} ( "=" {@linkplain ASTExpression Expression} )? * * </pre> */ public class ASTVariableDeclarator extends AbstractJavaNode implements InternalInterfaces.VariableIdOwner { ASTVariableDeclarator(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the name of the declared variable. */ public String getName() { return getVarId().getName(); } /** * Returns the id of the declared variable. */ @Override @NonNull public ASTVariableDeclaratorId getVarId() { return (ASTVariableDeclaratorId) getChild(0); } /** * Returns true if the declared variable is initialized. * Otherwise, {@link #getInitializer()} returns null. */ public boolean hasInitializer() { return getLastChild() instanceof ASTExpression; } /** * Returns the initializer, of the variable, or null if it doesn't exist. */ @Nullable public ASTExpression getInitializer() { return hasInitializer() ? (ASTExpression) getLastChild() : null; } }
1,950
25.013333
130
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTArrayType.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.ast.NodeStream; /** * Represents an array type. * * <pre class="grammar"> * * ArrayType ::= {@link ASTPrimitiveType PrimitiveType} {@link ASTArrayDimensions ArrayDimensions} * | {@link ASTClassOrInterfaceType ClassOrInterfaceType} {@link ASTArrayDimensions ArrayDimensions} * * </pre> */ public final class ASTArrayType extends AbstractJavaTypeNode implements ASTReferenceType { ASTArrayType(int id) { super(id); } @Override public NodeStream<ASTAnnotation> getDeclaredAnnotations() { return getDimensions().getFirstChild().getDeclaredAnnotations(); } public ASTArrayDimensions getDimensions() { return (ASTArrayDimensions) getChild(1); } public ASTType getElementType() { return (ASTType) getChild(0); } @Override public int getArrayDepth() { return getDimensions().size(); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
1,215
23.816327
112
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTRecordBody.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; /** * Defines the body of a {@linkplain ASTRecordDeclaration RecordDeclaration} (JDK 16 feature). * This can contain additional methods and or constructors. * * <pre class="grammar"> * * RecordBody ::= "{" ( {@linkplain ASTCompactConstructorDeclaration CompactConstructorDeclaration} * | {@linkplain ASTBodyDeclaration BodyDeclaration} )* "}" * * </pre> * */ public final class ASTRecordBody extends ASTTypeBody { ASTRecordBody(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
791
25.4
101
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTPermitsList.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import net.sourceforge.pmd.lang.java.ast.ASTList.ASTNonEmptyList; /** * Represents the {@code permits} clause of a (sealed) class declaration. * * <p>This is a Java 17 Feature. * * <p>See https://openjdk.java.net/jeps/409 * * <pre class="grammar"> * * PermitsList ::= "permits" ClassOrInterfaceType * ( "," ClassOrInterfaceType )* * </pre> */ public final class ASTPermitsList extends ASTNonEmptyList<ASTClassOrInterfaceType> { ASTPermitsList(int id) { super(id, ASTClassOrInterfaceType.class); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
834
23.558824
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTExpressionStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; /** * A statement that contains an expression. Note that this is not an * expression itself. * * <pre class="grammar"> * * ExpressionStatement ::= {@link ASTExpression StatementExpression} ";" * * </pre> */ public final class ASTExpressionStatement extends AbstractStatement { ASTExpressionStatement(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** Returns the contained expression. */ @NonNull public ASTExpression getExpr() { return (ASTExpression) getChild(0); } }
845
21.864865
91
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTExplicitConstructorInvocation.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; /** * An explicit constructor invocation, occurring at the start of a * {@linkplain ASTConstructorDeclaration constructor declaration}. * * <p>See <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.8.7.1">JLS 8.8.7.1</a>. * * <pre class="grammar"> * * ExplicitConstructorInvocation ::= {@link ASTTypeArguments TypeArguments}? "this" {@link ASTArgumentList ArgumentList} ";" * | {@link ASTTypeArguments TypeArguments}? "super" {@link ASTArgumentList ArgumentList} ";" * | {@link ASTExpression Expression} "." {@link ASTTypeArguments TypeArguments}? "super" {@link ASTArgumentList ArgumentList} ";" * * </pre> */ public final class ASTExplicitConstructorInvocation extends AbstractJavaTypeNode implements InvocationNode, ASTStatement { private boolean isSuper; private OverloadSelectionResult result; ASTExplicitConstructorInvocation(int id) { super(id); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override @NonNull public ASTArgumentList getArguments() { return (ASTArgumentList) getLastChild(); } /** * Returns the number of arguments of the called constructor. */ public int getArgumentCount() { return getArguments().size(); } void setIsSuper() { this.isSuper = true; } /** * Returns true if this statement calls a constructor of the same * class. The JLS calls that an <i>alternate constructor invocation</i>. */ public boolean isThis() { return !isSuper; } /** * Returns true if this statement calls a constructor of the direct * superclass. The JLS calls that a <i>superclass constructor invocation</i>. */ public boolean isSuper() { return isSuper; } /** * Returns true if this is a qualified superclass constructor invocation. * They allow a subclass constructor to explicitly specify the newly created * object's immediately enclosing instance with respect to the direct * superclass (§8.1.3). This may be necessary when the superclass is * an inner class. */ public boolean isQualified() { return getFirstChild() instanceof ASTPrimaryExpression; } @Override @Nullable public ASTTypeArguments getExplicitTypeArguments() { return getFirstChildOfType(ASTTypeArguments.class); } /** * Returns the qualifying expression if this is a {@linkplain #isQualified() qualified superclass * constructor invocation}. */ @Nullable public ASTExpression getQualifier() { return AstImplUtil.getChildAs(this, 0, ASTExpression.class); } @Override public OverloadSelectionResult getOverloadSelectionInfo() { forceTypeResolution(); return assertNonNullAfterTypeRes(result); } void setOverload(OverloadSelectionResult result) { this.result = result; } }
3,420
29.274336
162
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTCompilationUnit.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.AstInfo; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.ast.RootNode; import net.sourceforge.pmd.lang.ast.impl.GenericNode; import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable; import net.sourceforge.pmd.lang.java.types.TypeSystem; import net.sourceforge.pmd.lang.java.types.ast.LazyTypeResolver; /** * The root node of all Java ASTs. * * <pre class="grammar"> * * CompilationUnit ::= RegularCompilationUnit * | ModularCompilationUnit * * RegularCompilationUnit ::= * {@linkplain ASTPackageDeclaration PackageDeclaration}? * {@linkplain ASTImportDeclaration ImportDeclaration}* * {@linkplain ASTAnyTypeDeclaration TypeDeclaration}* * * ModularCompilationUnit ::= * {@linkplain ASTImportDeclaration ImportDeclaration}* * {@linkplain ASTModuleDeclaration ModuleDeclaration} * * </pre> */ public final class ASTCompilationUnit extends AbstractJavaNode implements JavaNode, GenericNode<JavaNode>, RootNode { private LazyTypeResolver lazyTypeResolver; private List<JavaComment> comments; private AstInfo<ASTCompilationUnit> astInfo; ASTCompilationUnit(int id) { super(id); setRoot(this); } public List<JavaComment> getComments() { return comments; } void setAstInfo(AstInfo<ASTCompilationUnit> task) { this.astInfo = task; } @Override public AstInfo<ASTCompilationUnit> getAstInfo() { return astInfo; } void setComments(List<JavaComment> comments) { this.comments = comments; } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } /** * Returns the package declaration, if there is one. */ public @Nullable ASTPackageDeclaration getPackageDeclaration() { return AstImplUtil.getChildAs(this, 0, ASTPackageDeclaration.class); } /** * Returns the package name of this compilation unit. If there is no * package declaration, then returns the empty string. */ public @NonNull String getPackageName() { ASTPackageDeclaration pack = getPackageDeclaration(); return pack == null ? "" : pack.getName(); } /** * Returns the top-level type declarations declared in this compilation * unit. This may be empty, eg if this a package-info.java, or a modular * compilation unit (but ordinary compilation units may also be empty). */ public NodeStream<ASTAnyTypeDeclaration> getTypeDeclarations() { return children(ASTAnyTypeDeclaration.class); } /** * Returns the module declaration, if this is a modular compilation unit. */ public @Nullable ASTModuleDeclaration getModuleDeclaration() { return firstChild(ASTModuleDeclaration.class); } @Override public @NonNull JSymbolTable getSymbolTable() { assert symbolTable != null : "Symbol table wasn't set"; return symbolTable; } @Override public TypeSystem getTypeSystem() { assert lazyTypeResolver != null : "Type resolution not initialized"; return lazyTypeResolver.getTypeSystem(); } void setTypeResolver(LazyTypeResolver typeResolver) { this.lazyTypeResolver = typeResolver; } @NonNull LazyTypeResolver getLazyTypeResolver() { assert lazyTypeResolver != null : "Type resolution not initialized"; return lazyTypeResolver; } }
3,822
28.407692
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/LanguageLevelChecker.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast.internal; import java.util.Locale; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAssertStatement; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTIntersectionType; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodReference; import net.sourceforge.pmd.lang.java.ast.ASTModuleDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.ASTNumericLiteral; import net.sourceforge.pmd.lang.java.ast.ASTPattern; import net.sourceforge.pmd.lang.java.ast.ASTReceiverParameter; import net.sourceforge.pmd.lang.java.ast.ASTRecordDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTRecordPattern; import net.sourceforge.pmd.lang.java.ast.ASTResource; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.ASTSwitchArrowBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression; import net.sourceforge.pmd.lang.java.ast.ASTSwitchGuard; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel; import net.sourceforge.pmd.lang.java.ast.ASTTryStatement; import net.sourceforge.pmd.lang.java.ast.ASTType; import net.sourceforge.pmd.lang.java.ast.ASTTypeArguments; import net.sourceforge.pmd.lang.java.ast.ASTTypeParameters; import net.sourceforge.pmd.lang.java.ast.ASTTypePattern; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.ASTYieldStatement; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavaTokenKinds; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.util.IteratorUtil; /** * Checks that an AST conforms to some language level. The reporting * behaviour is parameterized with a {@link ReportingStrategy}. * * @param <T> Type of object accumulating violations */ public class LanguageLevelChecker<T> { private static final Pattern SPACE_ESCAPE_PATTERN = Pattern.compile("(?<!\\\\)\\\\s"); private final int jdkVersion; private final boolean preview; private final CheckVisitor visitor = new CheckVisitor(); private final ReportingStrategy<T> reportingStrategy; public LanguageLevelChecker(int jdkVersion, boolean preview, ReportingStrategy<T> reportingStrategy) { this.jdkVersion = jdkVersion; this.preview = preview; this.reportingStrategy = reportingStrategy; } public int getJdkVersion() { return jdkVersion; } public boolean isPreviewEnabled() { return preview; } public void check(JavaNode node) { T accumulator = reportingStrategy.createAccumulator(); node.descendants(JavaNode.class).crossFindBoundaries().forEach(n -> n.acceptVisitor(visitor, accumulator)); reportingStrategy.done(accumulator); } private boolean check(Node node, LanguageFeature feature, T acc) { String message = feature.errorMessage(this.jdkVersion, this.preview); if (message != null) { reportingStrategy.report(node, message, acc); return false; } return true; } private static String displayNameLower(String name) { return name.replaceAll("__", "-") .replace('_', ' ') .toLowerCase(Locale.ROOT); } private static String versionDisplayName(int jdk) { if (jdk < 8) { return "Java 1." + jdk; } else { return "Java " + jdk; } } /** * Those are just for the preview features. * They are implemented in at least one preview language version. * They might be also be standardized. */ private enum PreviewFeature implements LanguageFeature { /** * Pattern matching for switch * @see <a href="https://openjdk.org/jeps/406">JEP 406: Pattern Matching for switch (Preview)</a> (Java 17) * @see <a href="https://openjdk.org/jeps/420">JEP 420: Pattern Matching for switch (Second Preview)</a> (Java 18) * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> (Java 19) * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> (Java 20) */ PATTERNS_IN_SWITCH_STATEMENTS(17, 20, false), /** * Part of pattern matching for switch * @see #PATTERNS_IN_SWITCH_STATEMENTS * @see <a href="https://openjdk.org/jeps/406">JEP 406: Pattern Matching for switch (Preview)</a> (Java 17) * @see <a href="https://openjdk.org/jeps/420">JEP 420: Pattern Matching for switch (Second Preview)</a> (Java 18) * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> (Java 19) * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> (Java 20) */ NULL_IN_SWITCH_CASES(17, 20, false), /** * Part of pattern matching for switch: Case refinement using "when" * @see #PATTERNS_IN_SWITCH_STATEMENTS * @see <a href="https://openjdk.org/jeps/427">JEP 427: Pattern Matching for switch (Third Preview)</a> (Java 19) * @see <a href="https://openjdk.org/jeps/433">JEP 433: Pattern Matching for switch (Fourth Preview)</a> (Java 20) */ CASE_REFINEMENT(19, 20, false), /** * Record patterns * @see <a href="https://openjdk.org/jeps/405">JEP 405: Record Patterns (Preview)</a> (Java 19) * @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a> (Java 20) */ DECONSTRUCTION_PATTERNS(19, 20, false), /** * Record deconstruction patterns in for-each loops * @see <a href="https://openjdk.org/jeps/432">JEP 432: Record Patterns (Second Preview)</a> (Java 20) */ DECONSTRUCTION_PATTERNS_IN_ENHANCED_FOR_STATEMENT(20, 20, false), ; // SUPPRESS CHECKSTYLE enum trailing semi is awesome private final int minPreviewVersion; private final int maxPreviewVersion; private final boolean wasStandardized; PreviewFeature(int minPreviewVersion, int maxPreviewVersion, boolean wasStandardized) { this.minPreviewVersion = minPreviewVersion; this.maxPreviewVersion = maxPreviewVersion; this.wasStandardized = wasStandardized; } @Override public String errorMessage(int jdk, boolean preview) { boolean isStandard = wasStandardized && jdk > maxPreviewVersion; boolean canBePreview = jdk >= minPreviewVersion && jdk <= maxPreviewVersion; boolean isPreview = preview && canBePreview; if (isStandard || isPreview) { return null; } String message = StringUtils.capitalize(displayNameLower(name())); if (canBePreview) { message += " is a preview feature of JDK " + jdk; } else if (wasStandardized) { message = message + " was only standardized in Java " + (maxPreviewVersion + 1); } else if (minPreviewVersion == maxPreviewVersion) { message += " is a preview feature of JDK " + minPreviewVersion; } else { message += " is a preview feature of JDKs " + minPreviewVersion + " to " + maxPreviewVersion; } return message + ", you should select your language version accordingly"; } } /** * Those use a max valid version. * * @see <a href="http://cr.openjdk.java.net/~gbierman/jep397/jep397-20201204/specs/contextual-keywords-jls.html">Contextual Keywords</a> */ private enum Keywords implements LanguageFeature { /** * ReservedKeyword since Java 1.4. */ ASSERT_AS_AN_IDENTIFIER(4, "assert"), /** * ReservedKeyword since Java 1.5. */ ENUM_AS_AN_IDENTIFIER(5, "enum"), /** * ReservedKeyword since Java 9. */ UNDERSCORE_AS_AN_IDENTIFIER(9, "_"), /** * ContextualKeyword since Java 10. */ VAR_AS_A_TYPE_NAME(10, "var"), /** * ContextualKeyword since Java 13 Preview. */ YIELD_AS_A_TYPE_NAME(13, "yield"), /** * ContextualKeyword since Java 14 Preview. */ RECORD_AS_A_TYPE_NAME(14, "record"), /** * ContextualKeyword since Java 15 Preview. */ SEALED_AS_A_TYPE_NAME(15, "sealed"), /** * ContextualKeyword since Java 15 Preview. */ PERMITS_AS_A_TYPE_NAME(15, "permits"), ; // SUPPRESS CHECKSTYLE enum trailing semi is awesome private final int maxJdkVersion; private final String reserved; Keywords(int minJdkVersion, String reserved) { this.maxJdkVersion = minJdkVersion; this.reserved = reserved; } @Override public String errorMessage(int jdk, boolean preview) { if (jdk < this.maxJdkVersion) { return null; } String s = displayNameLower(name()); String usageType = s.substring(s.indexOf(' ') + 1); // eg "as an identifier" return "Since " + LanguageLevelChecker.versionDisplayName(maxJdkVersion) + ", '" + reserved + "'" + " is reserved and cannot be used " + usageType; } } /** Those use a min valid version. */ private enum RegularLanguageFeature implements LanguageFeature { ASSERT_STATEMENTS(4), STATIC_IMPORT(5), ENUMS(5), GENERICS(5), ANNOTATIONS(5), FOREACH_LOOPS(5), VARARGS_PARAMETERS(5), HEXADECIMAL_FLOATING_POINT_LITERALS(5), UNDERSCORES_IN_NUMERIC_LITERALS(7), BINARY_NUMERIC_LITERALS(7), TRY_WITH_RESOURCES(7), COMPOSITE_CATCH_CLAUSES(7), DIAMOND_TYPE_ARGUMENTS(7), DEFAULT_METHODS(8), RECEIVER_PARAMETERS(8), TYPE_ANNOTATIONS(8), INTERSECTION_TYPES_IN_CASTS(8), LAMBDA_EXPRESSIONS(8), METHOD_REFERENCES(8), MODULE_DECLARATIONS(9), DIAMOND_TYPE_ARGUMENTS_FOR_ANONYMOUS_CLASSES(9), PRIVATE_METHODS_IN_INTERFACES(9), CONCISE_RESOURCE_SYNTAX(9), /** * @see <a href="https://openjdk.org/jeps/361">JEP 361: Switch Expressions</a> */ COMPOSITE_CASE_LABEL(14), /** * @see <a href="https://openjdk.org/jeps/361">JEP 361: Switch Expressions</a> */ SWITCH_EXPRESSIONS(14), /** * @see <a href="https://openjdk.org/jeps/361">JEP 361: Switch Expressions</a> */ SWITCH_RULES(14), /** * @see #SWITCH_EXPRESSIONS * @see <a href="https://openjdk.org/jeps/361">JEP 361: Switch Expressions</a> */ YIELD_STATEMENTS(14), /** * @see <a href="https://openjdk.org/jeps/378">JEP 378: Text Blocks</a> */ TEXT_BLOCK_LITERALS(15), /** * The new escape sequence {@code \s} simply translates to a single space {@code \u0020}. * * @see #TEXT_BLOCK_LITERALS * @see <a href="https://openjdk.org/jeps/378">JEP 378: Text Blocks</a> */ SPACE_STRING_ESCAPES(15), /** * @see <a href="https://openjdk.org/jeps/359">JEP 359: Records (Preview)</a> (Java 14) * @see <a href="https://openjdk.org/jeps/384">JEP 384: Records (Second Preview)</a> (Java 15) * @see <a href="https://openjdk.org/jeps/395">JEP 395: Records</a> (Java 16) */ RECORD_DECLARATIONS(16), /** * @see <a href="https://openjdk.org/jeps/305">JEP 305: Pattern Matching for instanceof (Preview)</a> (Java 14) * @see <a href="https://openjdk.org/jeps/375">JEP 375: Pattern Matching for instanceof (Second Preview)</a> (Java 15) * @see <a href="https://openjdk.org/jeps/394">JEP 394: Pattern Matching for instanceof</a> (Java 16) */ TYPE_PATTERNS_IN_INSTANCEOF(16), /** * Part of the records JEP 394. * @see #RECORD_DECLARATIONS * @see <a href="https://bugs.openjdk.org/browse/JDK-8253374">JLS changes for Static Members of Inner Classes</a> (Java 16) */ STATIC_LOCAL_TYPE_DECLARATIONS(16), /** * @see <a href="https://openjdk.org/jeps/360">JEP 360: Sealed Classes (Preview)</a> (Java 15) * @see <a href="https://openjdk.org/jeps/397">JEP 397: Sealed Classes (Second Preview)</a> (Java 16) * @see <a href="https://openjdk.org/jeps/409">JEP 409: Sealed Classes</a> (Java 17) */ SEALED_CLASSES(17), ; // SUPPRESS CHECKSTYLE enum trailing semi is awesome private final int minJdkLevel; RegularLanguageFeature(int minJdkLevel) { this.minJdkLevel = minJdkLevel; } @Override public String errorMessage(int jdk, boolean preview) { if (jdk >= this.minJdkLevel) { return null; } return StringUtils.capitalize(displayNameLower(name())) + " are a feature of " + versionDisplayName(minJdkLevel) + ", you should select your language version accordingly"; } } interface LanguageFeature { @Nullable String errorMessage(int jdk, boolean preview); } private final class CheckVisitor extends JavaVisitorBase<T, Void> { @Override protected Void visitChildren(Node node, T data) { throw new AssertionError("Shouldn't recurse"); } @Override public Void visitNode(Node node, T param) { return null; } @Override public Void visit(ASTStringLiteral node, T data) { if (node.isStringLiteral() && SPACE_ESCAPE_PATTERN.matcher(node.getImage()).find()) { check(node, RegularLanguageFeature.SPACE_STRING_ESCAPES, data); } if (node.isTextBlock()) { check(node, RegularLanguageFeature.TEXT_BLOCK_LITERALS, data); } return null; } @Override public Void visit(ASTImportDeclaration node, T data) { if (node.isStatic()) { check(node, RegularLanguageFeature.STATIC_IMPORT, data); } return null; } @Override public Void visit(ASTYieldStatement node, T data) { check(node, RegularLanguageFeature.YIELD_STATEMENTS, data); return null; } @Override public Void visit(ASTSwitchExpression node, T data) { check(node, RegularLanguageFeature.SWITCH_EXPRESSIONS, data); return null; } @Override public Void visit(ASTRecordDeclaration node, T data) { check(node, RegularLanguageFeature.RECORD_DECLARATIONS, data); return null; } @Override public Void visit(ASTConstructorCall node, T data) { if (node.usesDiamondTypeArgs()) { if (check(node, RegularLanguageFeature.DIAMOND_TYPE_ARGUMENTS, data) && node.isAnonymousClass()) { check(node, RegularLanguageFeature.DIAMOND_TYPE_ARGUMENTS_FOR_ANONYMOUS_CLASSES, data); } } return null; } @Override public Void visit(ASTTypeArguments node, T data) { check(node, RegularLanguageFeature.GENERICS, data); return null; } @Override public Void visit(ASTTypeParameters node, T data) { check(node, RegularLanguageFeature.GENERICS, data); return null; } @Override public Void visit(ASTFormalParameter node, T data) { if (node.isVarargs()) { check(node, RegularLanguageFeature.VARARGS_PARAMETERS, data); } return null; } @Override public Void visit(ASTReceiverParameter node, T data) { check(node, RegularLanguageFeature.RECEIVER_PARAMETERS, data); return null; } @Override public Void visit(ASTAnnotation node, T data) { if (node.getParent() instanceof ASTType) { check(node, RegularLanguageFeature.TYPE_ANNOTATIONS, data); } else { check(node, RegularLanguageFeature.ANNOTATIONS, data); } return null; } @Override public Void visit(ASTForeachStatement node, T data) { check(node, RegularLanguageFeature.FOREACH_LOOPS, data); if (node.getFirstChild() instanceof ASTRecordPattern) { check(node, PreviewFeature.DECONSTRUCTION_PATTERNS_IN_ENHANCED_FOR_STATEMENT, data); } return null; } @Override public Void visit(ASTEnumDeclaration node, T data) { check(node, RegularLanguageFeature.ENUMS, data); visitTypeDecl((ASTAnyTypeDeclaration) node, data); return null; } @Override public Void visit(ASTNumericLiteral node, T data) { int base = node.getBase(); if (base == 16 && !node.isIntegral()) { check(node, RegularLanguageFeature.HEXADECIMAL_FLOATING_POINT_LITERALS, data); } else if (base == 2) { check(node, RegularLanguageFeature.BINARY_NUMERIC_LITERALS, data); } else if (node.getImage().indexOf('_') >= 0) { check(node, RegularLanguageFeature.UNDERSCORES_IN_NUMERIC_LITERALS, data); } return null; } @Override public Void visit(ASTMethodReference node, T data) { check(node, RegularLanguageFeature.METHOD_REFERENCES, data); return null; } @Override public Void visit(ASTLambdaExpression node, T data) { check(node, RegularLanguageFeature.LAMBDA_EXPRESSIONS, data); return null; } @Override public Void visit(ASTMethodDeclaration node, T data) { if (node.hasModifiers(JModifier.DEFAULT)) { check(node, RegularLanguageFeature.DEFAULT_METHODS, data); } if (node.isPrivate() && node.getEnclosingType().isInterface()) { check(node, RegularLanguageFeature.PRIVATE_METHODS_IN_INTERFACES, data); } checkIdent(node, node.getMethodName(), data); return null; } @Override public Void visit(ASTAssertStatement node, T data) { check(node, RegularLanguageFeature.ASSERT_STATEMENTS, data); return null; } @Override public Void visit(ASTTypePattern node, T data) { check(node, RegularLanguageFeature.TYPE_PATTERNS_IN_INSTANCEOF, data); return null; } @Override public Void visit(ASTRecordPattern node, T data) { check(node, PreviewFeature.DECONSTRUCTION_PATTERNS, data); return null; } @Override public Void visit(ASTSwitchGuard node, T data) { check(node, PreviewFeature.CASE_REFINEMENT, data); return null; } @Override public Void visit(ASTTryStatement node, T data) { if (node.isTryWithResources()) { if (check(node, RegularLanguageFeature.TRY_WITH_RESOURCES, data)) { for (ASTResource resource : node.getResources()) { if (resource.isConciseResource()) { check(node, RegularLanguageFeature.CONCISE_RESOURCE_SYNTAX, data); break; } } } } return null; } @Override public Void visit(ASTIntersectionType node, T data) { if (node.getParent() instanceof ASTCastExpression) { check(node, RegularLanguageFeature.INTERSECTION_TYPES_IN_CASTS, data); } return null; } @Override public Void visit(ASTCatchClause node, T data) { if (node.getParameter().isMulticatch()) { check(node, RegularLanguageFeature.COMPOSITE_CATCH_CLAUSES, data); } return null; } @Override public Void visit(ASTSwitchLabel node, T data) { if (IteratorUtil.count(node.iterator()) > 1) { check(node, RegularLanguageFeature.COMPOSITE_CASE_LABEL, data); } if (node.isDefault() && JavaTokenKinds.CASE == node.getFirstToken().getKind()) { check(node, PreviewFeature.PATTERNS_IN_SWITCH_STATEMENTS, data); } if (node.getFirstChild() instanceof ASTNullLiteral) { check(node, PreviewFeature.NULL_IN_SWITCH_CASES, data); } if (node.getFirstChild() instanceof ASTPattern) { check(node, PreviewFeature.PATTERNS_IN_SWITCH_STATEMENTS, data); } return null; } @Override public Void visit(ASTModuleDeclaration node, T data) { check(node, RegularLanguageFeature.MODULE_DECLARATIONS, data); return null; } @Override public Void visit(ASTSwitchArrowBranch node, T data) { check(node, RegularLanguageFeature.SWITCH_RULES, data); return null; } @Override public Void visit(ASTVariableDeclaratorId node, T data) { checkIdent(node, node.getName(), data); return null; } @Override public Void visitTypeDecl(ASTAnyTypeDeclaration node, T data) { if (node.getModifiers().hasAnyExplicitly(JModifier.SEALED, JModifier.NON_SEALED)) { check(node, RegularLanguageFeature.SEALED_CLASSES, data); } else if (node.isLocal() && !node.isRegularClass()) { check(node, RegularLanguageFeature.STATIC_LOCAL_TYPE_DECLARATIONS, data); } String simpleName = node.getSimpleName(); if ("var".equals(simpleName)) { check(node, Keywords.VAR_AS_A_TYPE_NAME, data); } else if ("yield".equals(simpleName)) { check(node, Keywords.YIELD_AS_A_TYPE_NAME, data); } else if ("record".equals(simpleName)) { check(node, Keywords.RECORD_AS_A_TYPE_NAME, data); } else if ("sealed".equals(simpleName)) { check(node, Keywords.SEALED_AS_A_TYPE_NAME, data); } else if ("permits".equals(simpleName)) { check(node, Keywords.PERMITS_AS_A_TYPE_NAME, data); } checkIdent(node, simpleName, data); return null; } private void checkIdent(JavaNode node, String simpleName, T acc) { if ("enum".equals(simpleName)) { check(node, Keywords.ENUM_AS_AN_IDENTIFIER, acc); } else if ("assert".equals(simpleName)) { check(node, Keywords.ASSERT_AS_AN_IDENTIFIER, acc); } else if ("_".equals(simpleName)) { check(node, Keywords.UNDERSCORE_AS_AN_IDENTIFIER, acc); } } } }
24,595
36.323217
140
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/JavaAstUtils.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast.internal; import static net.sourceforge.pmd.lang.java.ast.JavaTokenKinds.FORMAL_COMMENT; import static net.sourceforge.pmd.lang.java.ast.JavaTokenKinds.MULTI_LINE_COMMENT; import static net.sourceforge.pmd.lang.java.ast.JavaTokenKinds.SINGLE_LINE_COMMENT; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.GenericToken; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTArrayAllocation; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.AccessType; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTBooleanLiteral; import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTLabeledStatement; import net.sourceforge.pmd.lang.java.ast.ASTList; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.ASTNumericLiteral; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTSuperExpression; import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTThisExpression; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.ast.Annotatable; import net.sourceforge.pmd.lang.java.ast.BinaryOp; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavaTokenKinds; import net.sourceforge.pmd.lang.java.ast.QualifiableExpression; import net.sourceforge.pmd.lang.java.ast.TypeNode; import net.sourceforge.pmd.lang.java.ast.UnaryOp; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.symbols.internal.ast.AstLocalVarSym; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.util.CollectionUtil; import net.sourceforge.pmd.util.OptionalBool; /** * Common utility functions to work with the Java AST. See also * {@link TypeTestUtil}. Only add here things that are not specific to * rules (use {@link JavaRuleUtil} for that). This API may be eventually * published. */ public final class JavaAstUtils { private JavaAstUtils() { // utility class } public static boolean isConditional(JavaNode ifx) { return isInfixExprWithOperator(ifx, BinaryOp.CONDITIONAL_OPS); } public static int numAlternatives(ASTSwitchBranch n) { return n.isDefault() ? 1 : n.getLabel().getExprList().count(); } /** * Returns true if this is a numeric literal with the given int value. * This also considers long literals. */ public static boolean isLiteralInt(JavaNode e, int value) { return e instanceof ASTNumericLiteral && ((ASTNumericLiteral) e).isIntegral() && ((ASTNumericLiteral) e).getValueAsInt() == value; } /** This is type-aware, so will not pick up on numeric addition. */ public static boolean isStringConcatExpr(@Nullable JavaNode e) { if (e instanceof ASTInfixExpression) { ASTInfixExpression infix = (ASTInfixExpression) e; return infix.getOperator() == BinaryOp.ADD && TypeTestUtil.isA(String.class, infix); } return false; } /** * If the parameter is an operand of a binary infix expression, * returns the other operand. Otherwise returns null. */ public static @Nullable ASTExpression getOtherOperandIfInInfixExpr(@Nullable JavaNode e) { if (e != null && e.getParent() instanceof ASTInfixExpression) { return (ASTExpression) e.getParent().getChild(1 - e.getIndexInParent()); } return null; } public static @Nullable ASTExpression getOtherOperandIfInAssignmentExpr(@Nullable JavaNode e) { if (e != null && e.getParent() instanceof ASTAssignmentExpression) { return (ASTExpression) e.getParent().getChild(1 - e.getIndexInParent()); } return null; } /** * Returns true if the node is a {@link ASTMethodDeclaration} that * is a main method. */ public static boolean isMainMethod(JavaNode node) { return node instanceof ASTMethodDeclaration && ((ASTMethodDeclaration) node).isMainMethod(); } public static boolean hasField(ASTAnyTypeDeclaration node, String name) { for (JFieldSymbol f : node.getSymbol().getDeclaredFields()) { String fname = f.getSimpleName(); if (fname.startsWith("m_") || fname.startsWith("_")) { fname = fname.substring(fname.indexOf('_') + 1); } if (fname.equalsIgnoreCase(name)) { return true; } } return false; } /** * Returns true if the formal parameters of the method or constructor * match the given types exactly. Note that for varargs methods, the * last param must have an array type (but it is not checked to be varargs). * This will return false if we're not sure. * * @param node Method or ctor * @param types List of types to match (may be empty) * * @throws NullPointerException If any of the classes is null, or the node is null * @see TypeTestUtil#isExactlyA(Class, TypeNode) */ public static boolean hasParameters(ASTMethodOrConstructorDeclaration node, Class<?>... types) { ASTFormalParameters formals = node.getFormalParameters(); if (formals.size() != types.length) { return false; } for (int i = 0; i < formals.size(); i++) { ASTFormalParameter fi = formals.get(i); if (!TypeTestUtil.isExactlyA(types[i], fi)) { return false; } } return true; } /** * Returns true if the {@code throws} declaration of the method or constructor * matches the given types exactly. * * @param node Method or ctor * @param types List of exception types to match (may be empty) * * @throws NullPointerException If any of the classes is null, or the node is null * @see TypeTestUtil#isExactlyA(Class, TypeNode) */ @SafeVarargs public static boolean hasExceptionList(ASTMethodOrConstructorDeclaration node, Class<? extends Throwable>... types) { @NonNull List<ASTClassOrInterfaceType> formals = ASTList.orEmpty(node.getThrowsList()); if (formals.size() != types.length) { return false; } for (int i = 0; i < formals.size(); i++) { ASTClassOrInterfaceType fi = formals.get(i); if (!TypeTestUtil.isExactlyA(types[i], fi)) { return false; } } return true; } /** * True if the variable is never used. Note that the visibility of * the variable must be less than {@link Visibility#V_PRIVATE} for * us to be sure of it. */ public static boolean isNeverUsed(ASTVariableDeclaratorId varId) { return CollectionUtil.none(varId.getLocalUsages(), JavaAstUtils::isReadUsage); } private static boolean isReadUsage(ASTNamedReferenceExpr expr) { return expr.getAccessType() == AccessType.READ // x++ as a method argument or used in other expression || expr.getParent() instanceof ASTUnaryExpression && !(expr.getParent().getParent() instanceof ASTExpressionStatement); } /** * True if the variable is incremented or decremented via a compound * assignment operator, or a unary increment/decrement expression. */ public static boolean isVarAccessReadAndWrite(ASTNamedReferenceExpr expr) { return expr.getAccessType() == AccessType.WRITE && (!(expr.getParent() instanceof ASTAssignmentExpression) || ((ASTAssignmentExpression) expr.getParent()).getOperator().isCompound()); } /** * True if the variable access is a non-compound assignment. */ public static boolean isVarAccessStrictlyWrite(ASTNamedReferenceExpr expr) { return expr.getParent() instanceof ASTAssignmentExpression && expr.getIndexInParent() == 0 && !((ASTAssignmentExpression) expr.getParent()).getOperator().isCompound(); } /** * Returns the set of labels on this statement. */ public static Set<String> getStatementLabels(ASTStatement node) { if (!(node.getParent() instanceof ASTLabeledStatement)) { return Collections.emptySet(); } return node.ancestors().takeWhile(it -> it instanceof ASTLabeledStatement) .toStream() .map(it -> ((ASTLabeledStatement) it).getLabel()) .collect(Collectors.toSet()); } public static boolean isAnonymousClassCreation(@Nullable ASTExpression expression) { return expression instanceof ASTConstructorCall && ((ASTConstructorCall) expression).isAnonymousClass(); } /** * Will cut through argument lists, except those of enum constants * and explicit invocation nodes. */ public static @NonNull ASTExpression getTopLevelExpr(ASTExpression expr) { JavaNode last = expr.ancestorsOrSelf() .takeWhile(it -> it instanceof ASTExpression || it instanceof ASTArgumentList && it.getParent() instanceof ASTExpression) .last(); return (ASTExpression) Objects.requireNonNull(last); } /** * Returns the variable IDS corresponding to variables declared in * the init clause of the loop. */ public static NodeStream<ASTVariableDeclaratorId> getLoopVariables(ASTForStatement loop) { return NodeStream.of(loop.getInit()) .filterIs(ASTLocalVariableDeclaration.class) .flatMap(ASTLocalVariableDeclaration::getVarIds); } /** * Whether one expression is the boolean negation of the other. Many * forms are not yet supported. This method is symmetric so only needs * to be called once. */ public static boolean areComplements(ASTExpression e1, ASTExpression e2) { if (isBooleanNegation(e1)) { return areEqual(unaryOperand(e1), e2); } else if (isBooleanNegation(e2)) { return areEqual(e1, unaryOperand(e2)); } else if (e1 instanceof ASTInfixExpression && e2 instanceof ASTInfixExpression) { ASTInfixExpression ifx1 = (ASTInfixExpression) e1; ASTInfixExpression ifx2 = (ASTInfixExpression) e2; if (ifx1.getOperator().getComplement() != ifx2.getOperator()) { return false; } if (ifx1.getOperator().hasSamePrecedenceAs(BinaryOp.EQ)) { // NOT(a == b, a != b) // NOT(a == b, b != a) return areEqual(ifx1.getLeftOperand(), ifx2.getLeftOperand()) && areEqual(ifx1.getRightOperand(), ifx2.getRightOperand()) || areEqual(ifx2.getLeftOperand(), ifx1.getLeftOperand()) && areEqual(ifx2.getRightOperand(), ifx1.getRightOperand()); } // todo we could continue with de Morgan and such } return false; } private static boolean areEqual(ASTExpression e1, ASTExpression e2) { return tokenEquals(e1, e2); } /** * Returns true if both nodes have exactly the same tokens. * * @param node First node * @param that Other node */ public static boolean tokenEquals(JavaNode node, JavaNode that) { return tokenEquals(node, that, null); } /** * Returns true if both nodes have the same tokens, modulo some renaming * function. The renaming function maps unqualified variables and type * identifiers of the first node to the other. This should be used * in nodes living in the same lexical scope, so that unqualified * names mean the same thing. * * @param node First node * @param other Other node * @param varRenamer A renaming function. If null, no renaming is applied. * Must not return null, if no renaming occurs, returns its argument. */ public static boolean tokenEquals(@NonNull JavaNode node, @NonNull JavaNode other, @Nullable Function<String, @NonNull String> varRenamer) { // Since type and variable names obscure one another, // it's ok to use a single renaming function. Iterator<JavaccToken> thisIt = GenericToken.range(node.getFirstToken(), node.getLastToken()).iterator(); Iterator<JavaccToken> thatIt = GenericToken.range(other.getFirstToken(), other.getLastToken()).iterator(); int lastKind = 0; while (thisIt.hasNext()) { if (!thatIt.hasNext()) { return false; } JavaccToken o1 = thisIt.next(); JavaccToken o2 = thatIt.next(); if (o1.kind != o2.kind) { return false; } String mappedImage = o1.getImage(); if (varRenamer != null && o1.kind == JavaTokenKinds.IDENTIFIER && lastKind != JavaTokenKinds.DOT && lastKind != JavaTokenKinds.METHOD_REF //method name && o1.getNext() != null && o1.getNext().kind != JavaTokenKinds.LPAREN) { mappedImage = varRenamer.apply(mappedImage); } if (!o2.getImage().equals(mappedImage)) { return false; } lastKind = o1.kind; } return !thatIt.hasNext(); } public static boolean isNullLiteral(ASTExpression node) { return node instanceof ASTNullLiteral; } /** Returns true if the node is a boolean literal with any value. */ public static boolean isBooleanLiteral(JavaNode e) { return e instanceof ASTBooleanLiteral; } /** Returns true if the node is a boolean literal with the given constant value. */ public static boolean isBooleanLiteral(JavaNode e, boolean value) { return e instanceof ASTBooleanLiteral && ((ASTBooleanLiteral) e).isTrue() == value; } public static boolean isBooleanNegation(JavaNode e) { return e instanceof ASTUnaryExpression && ((ASTUnaryExpression) e).getOperator() == UnaryOp.NEGATION; } /** * If the argument is a unary expression, returns its operand, otherwise * returns null. */ public static @Nullable ASTExpression unaryOperand(@Nullable ASTExpression e) { return e instanceof ASTUnaryExpression ? ((ASTUnaryExpression) e).getOperand() : null; } /** * Whether the expression is an access to a field of this instance, * not inherited, qualified or not ({@code this.field} or just {@code field}). */ public static boolean isThisFieldAccess(ASTExpression e) { if (!(e instanceof ASTNamedReferenceExpr)) { return false; } JVariableSymbol sym = ((ASTNamedReferenceExpr) e).getReferencedSym(); return sym instanceof JFieldSymbol && !((JFieldSymbol) sym).isStatic() // not inherited && ((JFieldSymbol) sym).getEnclosingClass().equals(e.getEnclosingType().getSymbol()) // correct syntactic form && (e instanceof ASTVariableAccess || isSyntacticThisFieldAccess(e)); } /** * Whether the expression is a {@code this.field}, with no outer * instance qualifier ({@code Outer.this.field}). The field symbol * is not checked to resolve to a field declared in this class (it * may be inherited) */ public static boolean isSyntacticThisFieldAccess(ASTExpression e) { if (e instanceof ASTFieldAccess) { ASTExpression qualifier = ((ASTFieldAccess) e).getQualifier(); if (qualifier instanceof ASTThisExpression) { // unqualified this return ((ASTThisExpression) qualifier).getQualifier() == null; } } return false; } public static boolean hasAnyAnnotation(Annotatable node, Collection<String> qualifiedNames) { return qualifiedNames.stream().anyMatch(node::isAnnotationPresent); } /** * Returns true if the expression is the default field value for * the given type. */ public static boolean isDefaultValue(JTypeMirror type, ASTExpression expr) { if (type.isPrimitive()) { if (type.isPrimitive(PrimitiveTypeKind.BOOLEAN)) { return expr instanceof ASTBooleanLiteral && !((ASTBooleanLiteral) expr).isTrue(); } else { Object constValue = expr.getConstValue(); return constValue instanceof Number && ((Number) constValue).doubleValue() == 0d || constValue instanceof Character && constValue.equals('\u0000'); } } else { return expr instanceof ASTNullLiteral; } } /** * Returns true if the expression is a {@link ASTNamedReferenceExpr} * that references the symbol. */ public static boolean isReferenceToVar(@Nullable ASTExpression expression, @NonNull JVariableSymbol symbol) { return expression instanceof ASTNamedReferenceExpr && symbol.equals(((ASTNamedReferenceExpr) expression).getReferencedSym()); } public static boolean isUnqualifiedThis(ASTExpression e) { return e instanceof ASTThisExpression && ((ASTThisExpression) e).getQualifier() == null; } public static boolean isUnqualifiedSuper(ASTExpression e) { return e instanceof ASTSuperExpression && ((ASTSuperExpression) e).getQualifier() == null; } public static boolean isUnqualifiedThisOrSuper(ASTExpression e) { return isUnqualifiedSuper(e) || isUnqualifiedThis(e); } /** * Returns true if the expression is a {@link ASTNamedReferenceExpr} * that references any of the symbol in the set. */ public static boolean isReferenceToVar(@Nullable ASTExpression expression, @NonNull Set<? extends JVariableSymbol> symbols) { return expression instanceof ASTNamedReferenceExpr && symbols.contains(((ASTNamedReferenceExpr) expression).getReferencedSym()); } /** * Returns true if both expressions refer to the same variable. * A "variable" here can also means a field path, eg, {@code this.field.a}. * This method unifies {@code this.field} and {@code field} if possible, * and also considers {@code this}. * * <p>Note that while this is more useful than just checking whether * both expressions access the same symbol, it still does not mean that * they both access the same <i>value</i>. The actual value is data-flow * dependent. */ public static boolean isReferenceToSameVar(ASTExpression e1, ASTExpression e2) { if (e1 instanceof ASTNamedReferenceExpr && e2 instanceof ASTNamedReferenceExpr) { if (OptionalBool.YES != referenceSameSymbol((ASTNamedReferenceExpr) e1, (ASTNamedReferenceExpr) e2)) { return false; } if (e1.getClass() != e2.getClass()) { // unify `this.f` and `f` // note, we already know that the symbol is the same so there's no scoping problem return isSyntacticThisFieldAccess(e1) || isSyntacticThisFieldAccess(e2); } else if (e1 instanceof ASTFieldAccess && e2 instanceof ASTFieldAccess) { return isReferenceToSameVar(((ASTFieldAccess) e1).getQualifier(), ((ASTFieldAccess) e2).getQualifier()); } return e1 instanceof ASTVariableAccess && e2 instanceof ASTVariableAccess; } else if (e1 instanceof ASTThisExpression || e2 instanceof ASTThisExpression) { return e1.getClass() == e2.getClass(); } return false; } private static OptionalBool referenceSameSymbol(ASTNamedReferenceExpr e1, ASTNamedReferenceExpr e2) { if (!e1.getName().equals(e2.getName())) { return OptionalBool.NO; } JVariableSymbol ref1 = e1.getReferencedSym(); JVariableSymbol ref2 = e2.getReferencedSym(); if (ref1 == null || ref2 == null) { return OptionalBool.UNKNOWN; } return OptionalBool.definitely(ref1.equals(ref2)); } /** * Returns true if the expression is a reference to a local variable. */ public static boolean isReferenceToLocal(ASTExpression expr) { return expr instanceof ASTVariableAccess && ((ASTVariableAccess) expr).getReferencedSym() instanceof AstLocalVarSym; } /** * Returns true if the expression has the form `field`, or `this.field`, * where `field` is a field declared in the enclosing class. Considers * inherited fields. Assumes we're not in a static context. */ public static boolean isRefToFieldOfThisInstance(ASTExpression usage) { if (!(usage instanceof ASTNamedReferenceExpr)) { return false; } JVariableSymbol symbol = ((ASTNamedReferenceExpr) usage).getReferencedSym(); if (!(symbol instanceof JFieldSymbol)) { return false; } if (usage instanceof ASTVariableAccess) { return !Modifier.isStatic(((JFieldSymbol) symbol).getModifiers()); } else if (usage instanceof ASTFieldAccess) { return isUnqualifiedThisOrSuper(((ASTFieldAccess) usage).getQualifier()); } return false; } /** * Returns true if the expression is a reference to a field declared * in this class (not a superclass), on any instance (not just `this`). */ public static boolean isRefToFieldOfThisClass(ASTExpression usage) { if (!(usage instanceof ASTNamedReferenceExpr)) { return false; } JVariableSymbol symbol = ((ASTNamedReferenceExpr) usage).getReferencedSym(); if (!(symbol instanceof JFieldSymbol)) { return false; } if (usage instanceof ASTVariableAccess) { return !Modifier.isStatic(((JFieldSymbol) symbol).getModifiers()); } else if (usage instanceof ASTFieldAccess) { return Objects.equals(((JFieldSymbol) symbol).getEnclosingClass(), usage.getEnclosingType().getSymbol()); } return false; } public static boolean isCallOnThisInstance(ASTMethodCall call) { // syntactic approach. if (call.getQualifier() != null) { return isUnqualifiedThisOrSuper(call.getQualifier()); } // unqualified call JMethodSig mtype = call.getMethodType(); return !mtype.getSymbol().isUnresolved() && mtype.getSymbol().getEnclosingClass().equals(call.getEnclosingType().getSymbol()); } public static ASTClassOrInterfaceType getThisOrSuperQualifier(ASTExpression expr) { if (expr instanceof ASTThisExpression) { return ((ASTThisExpression) expr).getQualifier(); } else if (expr instanceof ASTSuperExpression) { return ((ASTSuperExpression) expr).getQualifier(); } return null; } public static boolean isThisOrSuper(ASTExpression expr) { return expr instanceof ASTThisExpression || expr instanceof ASTSuperExpression; } /** * Return a node stream containing all the operands of an addition expression. * For instance, {@code a+b+c} will be parsed as a tree with two levels. * This method will return a flat node stream containing {@code a, b, c}. * * @param e An expression, if it is not a string concatenation expression, * then returns an empty node stream. */ public static NodeStream<ASTExpression> flattenOperands(ASTExpression e) { List<ASTExpression> result = new ArrayList<>(); flattenOperandsRec(e, result); return NodeStream.fromIterable(result); } private static void flattenOperandsRec(ASTExpression e, List<ASTExpression> result) { if (isStringConcatExpr(e)) { ASTInfixExpression infix = (ASTInfixExpression) e; flattenOperandsRec(infix.getLeftOperand(), result); flattenOperandsRec(infix.getRightOperand(), result); } else { result.add(e); } } /** * Returns true if the node is the last child of its parent. Returns * false if this is the root node. */ public static boolean isLastChild(Node it) { Node parent = it.getParent(); return parent != null && it.getIndexInParent() == parent.getNumChildren() - 1; } /** * Returns a node stream of enclosing expressions in the same call chain. * For instance in {@code a.b().c().d()}, called on {@code a}, this will * yield {@code a.b()}, and {@code a.b().c()}. */ @SuppressWarnings({"unchecked", "rawtypes"}) public static NodeStream<QualifiableExpression> followingCallChain(ASTExpression expr) { return (NodeStream) expr.ancestors().takeWhile(it -> it instanceof QualifiableExpression); } public static ASTExpression peelCasts(@Nullable ASTExpression expr) { while (expr instanceof ASTCastExpression) { expr = ((ASTCastExpression) expr).getOperand(); } return expr; } public static boolean isArrayInitializer(ASTExpression expr) { return expr instanceof ASTArrayAllocation && ((ASTArrayAllocation) expr).getArrayInitializer() != null; } public static boolean isCloneMethod(ASTMethodDeclaration node) { // this is enough as in valid code, this signature overrides Object#clone // and the other things like visibility are checked by the compiler return "clone".equals(node.getName()) && node.getArity() == 0 && !node.isStatic(); } public static boolean isEqualsMethod(ASTMethodDeclaration node) { return "equals".equals(node.getName()) && node.getArity() == 1 && node.getFormalParameters().get(0).getTypeMirror().isTop() && !node.isStatic(); } public static boolean isHashCodeMethod(ASTMethodDeclaration node) { return "hashCode".equals(node.getName()) && node.getArity() == 0 && !node.isStatic(); } public static boolean isArrayLengthFieldAccess(ASTExpression node) { if (node instanceof ASTFieldAccess) { ASTFieldAccess field = (ASTFieldAccess) node; return "length".equals(field.getName()) && field.getQualifier().getTypeMirror().isArray(); } return false; } /** * @see ASTBreakStatement#getTarget() */ public static boolean mayBeBreakTarget(JavaNode it) { return it instanceof ASTLoopStatement || it instanceof ASTSwitchStatement || it instanceof ASTLabeledStatement; } /** * Tests if the node is an {@link ASTInfixExpression} with one of the given operators. */ public static boolean isInfixExprWithOperator(@Nullable JavaNode e, Set<BinaryOp> operators) { if (e instanceof ASTInfixExpression) { ASTInfixExpression infix = (ASTInfixExpression) e; return operators.contains(infix.getOperator()); } return false; } /** * Tests if the node is an {@link ASTInfixExpression} with the given operator. */ public static boolean isInfixExprWithOperator(@Nullable JavaNode e, BinaryOp operator) { if (e instanceof ASTInfixExpression) { ASTInfixExpression infix = (ASTInfixExpression) e; return operator == infix.getOperator(); } return false; } /** * Returns true if the given token is a Java comment. */ public static boolean isComment(JavaccToken t) { switch (t.kind) { case FORMAL_COMMENT: case MULTI_LINE_COMMENT: case SINGLE_LINE_COMMENT: return true; default: return false; } } /** * Return true if the catch clause just rethrows the caught exception * immediately. */ public static boolean isJustRethrowException(ASTCatchClause clause) { ASTBlock body = clause.getBody(); if (body.size() == 1) { ASTStatement stmt = body.get(0); return stmt instanceof ASTThrowStatement && isReferenceToVar(((ASTThrowStatement) stmt).getExpr(), clause.getParameter().getVarId().getSymbol()); } return false; } }
31,486
40.213351
129
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast.internal; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.ast.ParseException; /** * Strategy for reporting language-feature violations, for use by a * {@link LanguageLevelChecker}. For example, {@link ReportingStrategy#reporterThatThrows()} * produces a checker that throws a parse exception. It would be trivial * to make eg a checker that eg collects all warnings instead of failing * on the first one. * * @param <T> Type of object accumulating violations */ public interface ReportingStrategy<T> { /** Create a blank accumulator before performing the check. */ T createAccumulator(); /** Consume the accumulator, after all violations have been reported. */ void done(T accumulator); /** * Report that a node violates a language feature. This doesn't have * to throw an exception, we could also just warn, or accumulate into * the parameter. */ void report(Node node, String message, T acc); /** * Creates a reporter that throws a {@link ParseException} when the * first error is reported. */ static ReportingStrategy<Void> reporterThatThrows() { return new ReportingStrategy<Void>() { @Override public Void createAccumulator() { return null; } @Override public void done(Void accumulator) { // do nothing } @Override public void report(Node node, String message, Void acc) { throw new ParseException(message).withLocation(node); } }; } }
1,762
27.901639
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/PrettyPrintingUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast.internal; import static net.sourceforge.pmd.util.AssertionUtil.shouldNotReachHere; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.ASTAmbiguousName; import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTArrayAccess; import net.sourceforge.pmd.lang.java.ast.ASTArrayType; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTClassLiteral; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTIntersectionType; import net.sourceforge.pmd.lang.java.ast.ASTList; import net.sourceforge.pmd.lang.java.ast.ASTLiteral; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType; import net.sourceforge.pmd.lang.java.ast.ASTRecordDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReferenceType; import net.sourceforge.pmd.lang.java.ast.ASTResource; import net.sourceforge.pmd.lang.java.ast.ASTSuperExpression; import net.sourceforge.pmd.lang.java.ast.ASTThisExpression; import net.sourceforge.pmd.lang.java.ast.ASTType; import net.sourceforge.pmd.lang.java.ast.ASTTypeArguments; import net.sourceforge.pmd.lang.java.ast.ASTTypeExpression; import net.sourceforge.pmd.lang.java.ast.ASTUnionType; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.ASTVoidType; import net.sourceforge.pmd.lang.java.ast.ASTWildcardType; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.lang.java.ast.QualifiableExpression; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.TypePrettyPrint; import net.sourceforge.pmd.lang.java.types.TypePrettyPrint.TypePrettyPrinter; import net.sourceforge.pmd.util.CollectionUtil; /** * @author Clément Fournier */ public final class PrettyPrintingUtil { private PrettyPrintingUtil() { // util class } /** * Returns a normalized method name. This just looks at the image of the types of the parameters. */ public static String displaySignature(String methodName, ASTFormalParameters params) { StringBuilder sb = new StringBuilder(); sb.append(methodName); sb.append('('); boolean first = true; for (ASTFormalParameter param : params) { if (!first) { sb.append(", "); } first = false; prettyPrintTypeNode(sb, param.getTypeNode()); int extraDimensions = ASTList.sizeOrZero(param.getVarId().getExtraDimensions()); while (extraDimensions-- > 0) { sb.append("[]"); } } sb.append(')'); return sb.toString(); } private static void prettyPrintTypeNode(StringBuilder sb, ASTType t) { if (t instanceof ASTPrimitiveType) { sb.append(((ASTPrimitiveType) t).getKind().getSimpleName()); } else if (t instanceof ASTClassOrInterfaceType) { ASTClassOrInterfaceType classT = (ASTClassOrInterfaceType) t; sb.append(classT.getSimpleName()); ASTTypeArguments targs = classT.getTypeArguments(); if (targs != null) { sb.append("<"); CollectionUtil.joinOn(sb, targs.toStream(), PrettyPrintingUtil::prettyPrintTypeNode, ", "); sb.append(">"); } } else if (t instanceof ASTArrayType) { prettyPrintTypeNode(sb, ((ASTArrayType) t).getElementType()); int depth = ((ASTArrayType) t).getArrayDepth(); for (int i = 0; i < depth; i++) { sb.append("[]"); } } else if (t instanceof ASTVoidType) { sb.append("void"); } else if (t instanceof ASTWildcardType) { sb.append("?"); ASTReferenceType bound = ((ASTWildcardType) t).getTypeBoundNode(); if (bound != null) { sb.append(((ASTWildcardType) t).isLowerBound() ? " super " : " extends "); prettyPrintTypeNode(sb, bound); } } else if (t instanceof ASTUnionType) { CollectionUtil.joinOn(sb, ((ASTUnionType) t).getComponents(), PrettyPrintingUtil::prettyPrintTypeNode, " | "); } else if (t instanceof ASTIntersectionType) { CollectionUtil.joinOn(sb, ((ASTIntersectionType) t).getComponents(), PrettyPrintingUtil::prettyPrintTypeNode, " & "); } else if (t instanceof ASTAmbiguousName) { sb.append(((ASTAmbiguousName) t).getName()); } else { throw shouldNotReachHere("Unhandled type? " + t); } } public static String prettyPrintType(ASTType t) { StringBuilder sb = new StringBuilder(); prettyPrintTypeNode(sb, t); return sb.toString(); } /** * Returns a normalized method name. This just looks at the image of the types of the parameters. */ public static String displaySignature(ASTMethodOrConstructorDeclaration node) { return displaySignature(node.getName(), node.getFormalParameters()); } /** * Returns the generic kind of declaration this is, eg "enum" or "class". */ public static String getPrintableNodeKind(ASTAnyTypeDeclaration decl) { if (decl instanceof ASTClassOrInterfaceDeclaration && decl.isInterface()) { return "interface"; } else if (decl instanceof ASTAnnotationTypeDeclaration) { return "annotation"; } else if (decl instanceof ASTEnumDeclaration) { return "enum"; } else if (decl instanceof ASTRecordDeclaration) { return "record"; } return "class"; } /** * Returns the "name" of a node. For methods and constructors, this * may return a signature with parameters. */ public static String getNodeName(JavaNode node) { // constructors are differentiated by their parameters, while we only use method name for methods if (node instanceof ASTMethodDeclaration) { return ((ASTMethodDeclaration) node).getName(); } else if (node instanceof ASTMethodOrConstructorDeclaration) { // constructors are differentiated by their parameters, while we only use method name for methods return displaySignature((ASTConstructorDeclaration) node); } else if (node instanceof ASTFieldDeclaration) { return ((ASTFieldDeclaration) node).getVarIds().firstOrThrow().getName(); } else if (node instanceof ASTResource) { return ((ASTResource) node).getStableName(); } else if (node instanceof ASTAnyTypeDeclaration) { return ((ASTAnyTypeDeclaration) node).getSimpleName(); } else if (node instanceof ASTVariableDeclaratorId) { return ((ASTVariableDeclaratorId) node).getName(); } else { return node.getImage(); // todo get rid of this } } /** * Returns the 'kind' of node this is. For instance for a {@link ASTFieldDeclaration}, * returns "field". * * @throws UnsupportedOperationException If unimplemented for a node kind * @see #getPrintableNodeKind(ASTAnyTypeDeclaration) */ public static String getPrintableNodeKind(JavaNode node) { if (node instanceof ASTAnyTypeDeclaration) { return getPrintableNodeKind((ASTAnyTypeDeclaration) node); } else if (node instanceof ASTMethodDeclaration) { return "method"; } else if (node instanceof ASTConstructorDeclaration) { return "constructor"; } else if (node instanceof ASTFieldDeclaration) { return "field"; } else if (node instanceof ASTResource) { return "resource specification"; } throw new UnsupportedOperationException("Node " + node + " is unaccounted for"); } public static String prettyImport(ASTImportDeclaration importDecl) { String name = importDecl.getImportedName(); if (importDecl.isImportOnDemand()) { return name + ".*"; } return name; } /** * Pretty print the selected overload. */ public static @NonNull String prettyPrintOverload(ASTMethodCall it) { return prettyPrintOverload(it.getOverloadSelectionInfo().getMethodType()); } public static @NonNull String prettyPrintOverload(JMethodSymbol it) { return prettyPrintOverload(it.getTypeSystem().sigOf(it)); } public static @NonNull String prettyPrintOverload(JMethodSig it) { return TypePrettyPrint.prettyPrint(it, overloadPrinter()); } private static TypePrettyPrinter overloadPrinter() { return new TypePrettyPrinter().qualifyNames(false).printMethodResult(false); } public static CharSequence prettyPrint(JavaNode node) { StringBuilder sb = new StringBuilder(); node.acceptVisitor(new ExprPrinter(), sb); return sb; } static class ExprPrinter extends JavaVisitorBase<StringBuilder, Void> { private static final int MAX_ARG_LENGTH = 20; @Override public Void visitJavaNode(JavaNode node, StringBuilder data) { return null; // don't recurse } @Override public Void visit(ASTTypeExpression node, StringBuilder data) { node.getTypeNode().acceptVisitor(this, data); return null; } @Override public Void visit(ASTCastExpression node, StringBuilder data) { ppInParens(data, node.getCastType()).append(' '); node.getOperand().acceptVisitor(this, data); return null; } @Override public Void visit(ASTClassLiteral node, StringBuilder data) { node.getTypeNode().acceptVisitor(this, data); data.append(".class"); return null; } @Override public Void visitLiteral(ASTLiteral node, StringBuilder data) { data.append(node.getText()); return null; } @Override public Void visit(ASTFieldAccess node, StringBuilder data) { addQualifier(node, data); data.append(node.getName()); return null; } @Override public Void visit(ASTVariableAccess node, StringBuilder data) { data.append(node.getName()); return null; } @Override public Void visit(ASTThisExpression node, StringBuilder data) { if (node.getQualifier() != null) { node.getQualifier().acceptVisitor(this, data); data.append('.'); } data.append("this"); return null; } @Override public Void visit(ASTSuperExpression node, StringBuilder data) { if (node.getQualifier() != null) { node.getQualifier().acceptVisitor(this, data); data.append('.'); } data.append("super"); return null; } @Override public Void visit(ASTArrayAccess node, StringBuilder data) { node.getQualifier().acceptVisitor(this, data); data.append('['); node.getIndexExpression().acceptVisitor(this, data); data.append(']'); return null; } @Override public Void visitType(ASTType node, StringBuilder data) { prettyPrintTypeNode(data, node); return null; } @Override public Void visit(ASTMethodCall node, StringBuilder sb) { addQualifier(node, sb); sb.append(node.getMethodName()); if (node.getArguments().isEmpty()) { sb.append("()"); } else { final int argStart = sb.length(); sb.append('('); boolean first = true; for (ASTExpression arg : node.getArguments()) { if (sb.length() - argStart >= MAX_ARG_LENGTH) { sb.append("..."); break; } else if (!first) { sb.append(", "); } arg.acceptVisitor(this, sb); first = false; } sb.append(')'); } return null; } private void addQualifier(QualifiableExpression node, StringBuilder data) { ASTExpression qualifier = node.getQualifier(); if (qualifier != null) { if (!(qualifier instanceof ASTPrimaryExpression)) { ppInParens(data, qualifier); } else { qualifier.acceptVisitor(this, data); } data.append('.'); } } private StringBuilder ppInParens(StringBuilder data, JavaNode qualifier) { data.append('('); qualifier.acceptVisitor(this, data); return data.append(')'); } } }
14,442
37.208995
109
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/JavaMetrics.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics; import static net.sourceforge.pmd.internal.util.PredicateUtil.always; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import org.apache.commons.lang3.mutable.MutableInt; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.metrics.internal.AtfdBaseVisitor; import net.sourceforge.pmd.lang.java.metrics.internal.ClassFanOutVisitor; import net.sourceforge.pmd.lang.java.metrics.internal.CognitiveComplexityVisitor; import net.sourceforge.pmd.lang.java.metrics.internal.CognitiveComplexityVisitor.State; import net.sourceforge.pmd.lang.java.metrics.internal.CycloVisitor; import net.sourceforge.pmd.lang.java.metrics.internal.NcssVisitor; import net.sourceforge.pmd.lang.java.metrics.internal.NpathBaseVisitor; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.metrics.Metric; import net.sourceforge.pmd.lang.metrics.MetricOption; import net.sourceforge.pmd.lang.metrics.MetricOptions; import net.sourceforge.pmd.lang.metrics.MetricsUtil; /** * Built-in Java metrics. See {@link Metric} and {@link MetricsUtil} * for usage doc. * * @see "Michele Lanza and Radu Marinescu. <i>Object-Oriented Metrics in Practice: * Using Software Metrics to Characterize, Evaluate, and Improve the Design * of Object-Oriented Systems.</i> Springer, Berlin, 1 edition, October 2006." */ public final class JavaMetrics { /** * Number of usages of foreign attributes, both directly and through accessors. * "Foreign" hier means "not belonging to {@code this}", although field accesses * to fields declared in the enclosing class are not considered foreign. * * <p>High values of ATFD (&gt; 3 for an operation) may suggest that the * class or operation breaks encapsulation by relying on the internal * representation of the classes it uses instead of the services they provide. */ public static final Metric<JavaNode, Integer> ACCESS_TO_FOREIGN_DATA = Metric.of(JavaMetrics::computeAtfd, isJavaNode(), "Access To Foreign Data", "ATFD"); /** * Number of independent paths through a block of code. * Formally, given that the control flow graph of the block has n * vertices, e edges and p connected components, the cyclomatic complexity * of the block is given by {@code CYCLO = e - n + 2p}. In practice * it can be calculated by counting control flow statements following * the standard rules given below. * * <p>The standard version of the metric complies with McCabe’s original definition: * <ul> * <li>Methods have a base complexity of 1. * <li>+1 for every control flow statement (if, case, catch, throw, * do, while, for, break, continue) and conditional expression (?:). * Notice switch cases count as one, but not the switch itself: the * point is that a switch should have the same complexity value as * the equivalent series of if statements. * <li>else, finally and default do not count; * <li>+1 for every boolean operator ({@code &&}, {@code ||}) in * the guard condition of a control flow statement. That’s because * Java has short-circuit evaluation semantics for boolean operators, * which makes every boolean operator kind of a control flow statement in itself. * </ul> * * <p>Code example: * <pre>{@code * class Foo { * void baseCyclo() { // Cyclo = 1 * highCyclo(); * } * * void highCyclo() { // Cyclo = 10 * int x = 0, y = 2; * boolean a = false, b = true; * * if (a && (y == 1 ? b : true)) { // +3 * if (y == x) { // +1 * while (true) { // +1 * if (x++ < 20) { // +1 * break; // +1 * } * } * } else if (y == t && !d) { // +2 * x = a ? y : x; // +1 * } else { * x = 2; * } * } * } * } * }</pre> * * @see CycloOption */ public static final Metric<ASTMethodOrConstructorDeclaration, Integer> CYCLO = Metric.of(JavaMetrics::computeCyclo, asMethodOrCtor(), "Cyclomatic Complexity", "Cyclo"); /** * Cognitive complexity is a measure of how difficult it is for humans * to read and understand a method. Code that contains a break in the * control flow is more complex, whereas the use of language shorthands * doesn't increase the level of complexity. Nested control flows can * make a method more difficult to understand, with each additional * nesting of the control flow leading to an increase in cognitive * complexity. * * <p>Information about Cognitive complexity can be found in the original paper here: * <a href='https://www.sonarsource.com/docs/CognitiveComplexity.pdf'>CognitiveComplexity</a> * * <h3>Basic Idea</h3> * <ol> * <li>Ignore structures that allow multiple statements to be readably shorthanded into one * <li>Increment (add one) for each break in the linear flow of the code * <li>Increment when flow-breaking structures are nested * </ol> * * <h3>Increments</h3> * There is an increment for each of the following: * <ul> * <li>`if`, `else if`, `else`, ternary operator * <li>`switch` * <li>`for`, `foreach` * <li>`while`, `do while` * <li>`catch` * <li>`goto LABEL`, `break LABEL`, `continue LABEL` * <li>sequences of binary logical operators * <li>each method in a recursion cycle * </ul> * * <h3>Nesting level</h3> * The following structures increment the nesting level: * <ul> * <li>`if`, `else if`, `else`, ternary operator * <li>`switch` * <li>`for`, `foreach` * <li>`while`, `do while` * <li>`catch` * <li>nested methods and method-like structures such as lambdas * </ul> * * <h3>Nesting increments</h3> * The following structures receive a nesting increment commensurate with their nested depth * inside nested structures: * <ul> * <li>`if`, ternary operator * <li>`switch` * <li>`for`, `foreach` * <li>`while`, `do while` * <li>`catch` * </ul> * * <h3>Code example</h3> * * <pre>{@code * class Foo { * void myMethod () { * try { * if (condition1) { // +1 * for (int i = 0; i < 10; i++) { // +2 (nesting=1) * while (condition2) { } // +3 (nesting=2) * } * } * } catch (ExcepType1 | ExcepType2 e) { // +1 * if (condition2) { } // +2 (nesting=1) * } * } // Cognitive Complexity 9 * } * }</pre> */ public static final Metric<ASTMethodOrConstructorDeclaration, Integer> COGNITIVE_COMPLEXITY = Metric.of(JavaMetrics::computeCognitive, asMethodOrCtor(), "Cognitive Complexity", "CognitiveComp"); /** * This counts the number of other classes a given class or operation * relies on. Classes from the package {@code java.lang} are ignored * by default (can be changed via options). Also primitives are not * included into the count. * * <p>Code example: * <pre>{@code * import java.util.*; * import java.io.IOException; * * public class Foo { // total 8 * public Set set = new HashSet(); // +2 * public Map map = new HashMap(); // +2 * public String string = ""; // from java.lang -> does not count by default * public Double number = 0.0; // from java.lang -> does not count by default * public int[] intArray = new int[3]; // primitive -> does not count * * \@Deprecated // from java.lang -> does not count by default * public void foo(List list) throws Exception { // +1 (Exception is from java.lang) * throw new IOException(); // +1 * } * * public int getMapSize() { * return map.size(); // +1 because it uses the Class from the 'map' field * } * } * }</pre> * * @see ClassFanOutOption */ public static final Metric<JavaNode, Integer> FAN_OUT = Metric.of(JavaMetrics::computeFanOut, isJavaNode(), "Fan-Out", "CFO"); /** * Simply counts the number of lines of code the operation or class * takes up in the source. This metric doesn’t discount comments or blank lines. * See {@link #NCSS} for a less biased metric. */ public static final Metric<JavaNode, Integer> LINES_OF_CODE = Metric.of(JavaMetrics::computeLoc, isJavaNode(), "Lines of code", "LOC"); /** * Number of statements in a class or operation. That’s roughly * equivalent to counting the number of semicolons and opening braces * in the program. Comments and blank lines are ignored, and statements * spread on multiple lines count as only one (e.g. {@code int\n a;} * counts a single statement). * * <p>The standard version of the metric is based off [JavaNCSS](http://www.kclee.de/clemens/java/javancss/): * <ul> * <li>+1 for any of the following statements: {@code if}, {@code else}, * {@code while}, {@code do}, {@code for}, {@code switch}, {@code break}, * {@code continue}, {@code return}, {@code throw}, {@code synchronized}, * {@code catch}, {@code finally}. * <li>+1 for each assignment, variable declaration (except for loop initializers) * or statement expression. We count variables declared on the same line (e.g. * {@code int a, b, c;}) as a single statement. * <li>Contrary to Sonarqube, but as JavaNCSS, we count type declarations (class, interface, enum, annotation), * and method and field declarations. * <li>Contrary to JavaNCSS, but as Sonarqube, we do not count package * declaration and import declarations as statements. This makes it * easier to compare nested classes to outer classes. Besides, it makes * for class metric results that actually represent the size of the class * and not of the file. If you don’t like that behaviour, use the {@link NcssOption#COUNT_IMPORTS} option. * </ul> * * <pre>{@code * import java.util.Collections; // +0 * import java.io.IOException; // +0 * * class Foo { // +1, total Ncss = 12 * * public void bigMethod() // +1 * throws IOException { * int x = 0, y = 2; // +1 * boolean a = false, b = true; // +1 * * if (a || b) { // +1 * try { // +1 * do { // +1 * x += 2; // +1 * } while (x < 12); * * System.exit(0); // +1 * } catch (IOException ioe) { // +1 * throw new PatheticFailException(ioe); // +1 * } * } else { * assert false; // +1 * } * } * } * }</pre> */ public static final Metric<JavaNode, Integer> NCSS = Metric.of(JavaMetrics::computeNcss, isJavaNode(), "Non-commenting source statements", "NCSS"); /** * Number of acyclic execution paths through a piece of code. This * is related to cyclomatic complexity, but the two metrics don’t * count the same thing: NPath counts the number of distinct full * paths from the beginning to the end of the method, while Cyclo * only counts the number of decision points. NPath is not computed * as simply as {@link #CYCLO}. With NPath, two decision points appearing * sequentially have their complexity multiplied. * * <p>The fact that NPath multiplies the complexity of statements makes * it grow exponentially: 10 {@code if .. else} statements in a row * would give an NPath of 1024, while Cyclo would evaluate to 20. * Methods with an NPath complexity over 200 are generally considered * too complex. * * <p>We compute NPath recursively, with the following set of rules: * <ul> * <li>An empty block has a complexity of 1. * <li>The complexity of a block is the product of the NPath complexity * of its statements, calculated as follows: * <ul> * <li>The complexity of for, do and while statements is 1, plus the * complexity of the block, plus the complexity of the guard condition. * <li> The complexity of a cascading if statement ({@code if .. else if ..}) * is the number of if statements in the chain, plus the complexity of * their guard condition, plus the complexity of the unguarded else block * (or 1 if there is none). * <li> The complexity of a switch statement is the number of cases, * plus the complexity of each case block. It’s equivalent to the * complexity of the equivalent cascade of if statements. * <li> The complexity of a ternary expression ({@code ? :}) is the complexity * of the guard condition, plus the complexity of both expressions. * It’s equivalent to the complexity of the equivalent {@code if .. else} construct. * <li> The complexity of a {@code try .. catch} statement is the complexity * of the {@code try} block, plus the complexity of each catch block. * <li> The complexity of a return statement is the complexity of the * expression (or 1 if there is none). * <li> All other statements have a complexity of 1 and are discarded * from the product. * </ul> * </li> * </ul> */ public static final Metric<ASTMethodOrConstructorDeclaration, BigInteger> NPATH = Metric.of(JavaMetrics::computeNpath, asMethodOrCtor(), "NPath Complexity", "NPath"); public static final Metric<ASTAnyTypeDeclaration, Integer> NUMBER_OF_ACCESSORS = Metric.of(JavaMetrics::computeNoam, asClass(always()), "Number of accessor methods", "NOAM"); public static final Metric<ASTAnyTypeDeclaration, Integer> NUMBER_OF_PUBLIC_FIELDS = Metric.of(JavaMetrics::computeNopa, asClass(always()), "Number of public attributes", "NOPA"); /** * The relative number of method pairs of a class that access in common * at least one attribute of the measured class. TCC only counts direct * attribute accesses, that is, only those attributes that are accessed * in the body of the method. * * <p>The value is a double between 0 and 1. * * <p>TCC is taken to be a reliable cohesion metric for a class. * High values (&gt;70%) indicate a class with one basic function, * which is hard to break into subcomponents. On the other hand, low * values (&lt;50%) may indicate that the class tries to do too much * and defines several unrelated services, which is undesirable. */ public static final Metric<ASTAnyTypeDeclaration, Double> TIGHT_CLASS_COHESION = Metric.of(JavaMetrics::computeTcc, asClass(it -> !it.isInterface()), "Tight Class Cohesion", "TCC"); /** * Sum of the statistical complexity of the operations in the class. * We use CYCLO to quantify the complexity of an operation. * * <p>WMC uses the same options as CYCLO, which are provided to CYCLO when computing it ({@link CycloOption}). */ public static final Metric<ASTAnyTypeDeclaration, Integer> WEIGHED_METHOD_COUNT = Metric.of(JavaMetrics::computeWmc, asClass(it -> !it.isInterface()), "Weighed Method Count", "WMC"); /** * Number of “functional” public methods divided by the total number * of public methods. Our definition of “functional method” excludes * constructors, getters, and setters. * * <p>The value is a double between 0 and 1. * * <p>This metric tries to quantify whether the measured class’ interface * reveals more data than behaviour. Low values (less than 30%) indicate * that the class reveals much more data than behaviour, which is a * sign of poor encapsulation. */ public static final Metric<ASTAnyTypeDeclaration, Double> WEIGHT_OF_CLASS = Metric.of(JavaMetrics::computeWoc, asClass(it -> !it.isInterface()), "Weight Of Class", "WOC"); private JavaMetrics() { // utility class } private static Function<Node, JavaNode> isJavaNode() { return n -> n instanceof JavaNode ? (JavaNode) n : null; } private static Function<Node, @Nullable ASTMethodOrConstructorDeclaration> asMethodOrCtor() { return n -> n instanceof ASTMethodOrConstructorDeclaration ? (ASTMethodOrConstructorDeclaration) n : null; } private static <T extends Node> Function<Node, T> filterMapNode(Class<? extends T> klass, Predicate<? super T> pred) { return n -> n.asStream().filterIs(klass).filter(pred).first(); } private static Function<Node, ASTAnyTypeDeclaration> asClass(Predicate<? super ASTAnyTypeDeclaration> pred) { return filterMapNode(ASTAnyTypeDeclaration.class, pred); } private static int computeNoam(ASTAnyTypeDeclaration node, MetricOptions ignored) { return node.getDeclarations() .filterIs(ASTMethodDeclaration.class) .filter(JavaRuleUtil::isGetterOrSetter) .count(); } private static int computeNopa(ASTAnyTypeDeclaration node, MetricOptions ignored) { return node.getDeclarations() .filterIs(ASTFieldDeclaration.class) .filter(AccessNode::isPublic) .flatMap(ASTFieldDeclaration::getVarIds) .count(); } private static int computeNcss(JavaNode node, MetricOptions options) { MutableInt result = new MutableInt(0); node.acceptVisitor(new NcssVisitor(options, node), result); return result.getValue(); } private static int computeLoc(JavaNode node, MetricOptions ignored) { // the report location is now not necessarily the entire node. FileLocation loc = node.getTextDocument().toLocation(node.getTextRegion()); return 1 + loc.getEndLine() - loc.getStartLine(); } private static int computeCyclo(JavaNode node, MetricOptions options) { MutableInt counter = new MutableInt(0); node.acceptVisitor(new CycloVisitor(options, node), counter); return counter.getValue(); } private static BigInteger computeNpath(JavaNode node, MetricOptions ignored) { return node.acceptVisitor(NpathBaseVisitor.INSTANCE, null); } private static int computeCognitive(JavaNode node, MetricOptions ignored) { State state = new State(node); node.acceptVisitor(CognitiveComplexityVisitor.INSTANCE, state); return state.getComplexity(); } private static int computeWmc(ASTAnyTypeDeclaration node, MetricOptions options) { return (int) MetricsUtil.computeStatistics(CYCLO, node.getOperations(), options).getSum(); } private static double computeTcc(ASTAnyTypeDeclaration node, MetricOptions ignored) { List<Set<String>> usagesByMethod = attributeAccessesByMethod(node); int numPairs = numMethodsRelatedByAttributeAccess(usagesByMethod); int maxPairs = maxMethodPairs(usagesByMethod.size()); if (maxPairs == 0) { return 0; } return numPairs / (double) maxPairs; } /** * Collects the attribute accesses by method into a map, for TCC. */ private static List<Set<String>> attributeAccessesByMethod(ASTAnyTypeDeclaration type) { final List<Set<String>> map = new ArrayList<>(); final JClassSymbol typeSym = type.getSymbol(); for (ASTMethodDeclaration decl : type.getDeclarations(ASTMethodDeclaration.class)) { Set<String> attrs = new HashSet<>(); decl.descendants().crossFindBoundaries() .filterIs(ASTNamedReferenceExpr.class) .forEach(it -> { JVariableSymbol sym = it.getReferencedSym(); if (sym instanceof JFieldSymbol && typeSym.equals(((JFieldSymbol) sym).getEnclosingClass())) { attrs.add(sym.getSimpleName()); } }); map.add(attrs); } return map; } /** * Gets the number of pairs of methods that use at least one attribute in common. * * @param usagesByMethod Map of method name to names of local attributes accessed * * @return The number of pairs */ private static int numMethodsRelatedByAttributeAccess(List<Set<String>> usagesByMethod) { int methodCount = usagesByMethod.size(); int pairs = 0; if (methodCount > 1) { for (int i = 0; i < methodCount - 1; i++) { for (int j = i + 1; j < methodCount; j++) { if (!Collections.disjoint(usagesByMethod.get(i), usagesByMethod.get(j))) { pairs++; } } } } return pairs; } /** * Calculates the number of possible method pairs of two methods. * * @param methods Number of methods in the class * * @return Number of possible method pairs */ private static int maxMethodPairs(int methods) { return methods * (methods - 1) / 2; } /** * Options for {@link #NCSS}. */ public enum NcssOption implements MetricOption { /** Counts import and package statement. This makes the metric JavaNCSS compliant. */ COUNT_IMPORTS("countImports"); private final String vName; NcssOption(String valueName) { this.vName = valueName; } @Override public String valueName() { return vName; } } /** * Options for {@link #CYCLO}. */ public enum CycloOption implements MetricOption { /** Do not count the paths in boolean expressions as decision points. */ IGNORE_BOOLEAN_PATHS("ignoreBooleanPaths"), /** Consider assert statements as if they were {@code if (..) throw new AssertionError(..)}. */ CONSIDER_ASSERT("considerAssert"); private final String vName; CycloOption(String valueName) { this.vName = valueName; } @Override public String valueName() { return vName; } } private static int computeAtfd(JavaNode node, MetricOptions ignored) { MutableInt result = new MutableInt(0); node.acceptVisitor(new AtfdBaseVisitor(), result); return result.getValue(); } private static double computeWoc(ASTAnyTypeDeclaration node, MetricOptions ignored) { NodeStream<ASTMethodDeclaration> methods = node.getDeclarations() .filterIs(ASTMethodDeclaration.class) .filter(it -> !it.isPrivate()); int notSetter = methods.filter(it -> !JavaRuleUtil.isGetterOrSetter(it)).count(); int total = methods.count(); if (total == 0) { return 0; } return notSetter / (double) total; } private static int computeFanOut(JavaNode node, MetricOptions options) { Set<JClassSymbol> cfo = new HashSet<>(); node.acceptVisitor(ClassFanOutVisitor.getInstance(options), cfo); return cfo.size(); } /** * Options for {@link #FAN_OUT}. */ public enum ClassFanOutOption implements MetricOption { /** Whether to include classes in the {@code java.lang} package. */ INCLUDE_JAVA_LANG("includeJavaLang"); private final String vName; ClassFanOutOption(String valueName) { this.vName = valueName; } @Override public String valueName() { return vName; } } }
25,507
38.425039
122
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/NpathBaseVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics.internal; import java.math.BigInteger; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTDoStatement; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTSwitchArrowBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression; import net.sourceforge.pmd.lang.java.ast.ASTSwitchFallthroughBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTTryStatement; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; /** * Visitor for the default n-path complexity version. * * @author Clément Fournier * @author Jason Bennett */ public class NpathBaseVisitor extends JavaVisitorBase<Void, BigInteger> { /** Instance. */ public static final NpathBaseVisitor INSTANCE = new NpathBaseVisitor(); /* Multiplies the complexity of the children of this node. */ private BigInteger multiplyChildrenComplexities(JavaNode node) { return multiplyComplexities(node.children()); } private BigInteger multiplyComplexities(NodeStream<? extends JavaNode> nodes) { return nodes.reduce(BigInteger.ONE, (acc, n) -> acc.multiply(n.acceptVisitor(this, null))); } /* Sums the complexity of the children of the node. */ private BigInteger sumChildrenComplexities(JavaNode node, Void data) { BigInteger sum = BigInteger.ZERO; for (JavaNode child : node.children()) { BigInteger childComplexity = child.acceptVisitor(this, data); sum = sum.add(childComplexity); } return sum; } @Override public BigInteger visitMethodOrCtor(ASTMethodOrConstructorDeclaration node, Void data) { return multiplyChildrenComplexities(node); } @Override public BigInteger visitJavaNode(JavaNode node, Void data) { return multiplyChildrenComplexities(node); } @Override public BigInteger visit(ASTIfStatement node, Void data) { // (npath of if + npath of else (or 1) + bool_comp of if) * npath of next int boolCompIf = CycloVisitor.booleanExpressionComplexity(node.getCondition()); BigInteger thenResult = node.getThenBranch().acceptVisitor(this, data); ASTStatement elseBranch = node.getElseBranch(); BigInteger elseResult = elseBranch != null ? elseBranch.acceptVisitor(this, data) : BigInteger.ONE; return thenResult.add(BigInteger.valueOf(boolCompIf)).add(elseResult); } @Override public BigInteger visit(ASTWhileStatement node, Void data) { // (npath of while + bool_comp of while + 1) * npath of next int boolComp = CycloVisitor.booleanExpressionComplexity(node.getCondition()); BigInteger nPathBody = node.getBody().acceptVisitor(this, data); return nPathBody.add(BigInteger.valueOf(boolComp + 1)); } @Override public BigInteger visit(ASTDoStatement node, Void data) { // (npath of do + bool_comp of do + 1) * npath of next int boolComp = CycloVisitor.booleanExpressionComplexity(node.getCondition()); BigInteger nPathBody = node.getBody().acceptVisitor(this, data); return nPathBody.add(BigInteger.valueOf(boolComp + 1)); } @Override public BigInteger visit(ASTForStatement node, Void data) { // (npath of for + bool_comp of for + 1) * npath of next int boolComp = CycloVisitor.booleanExpressionComplexity(node.getCondition()); BigInteger nPathBody = node.getBody().acceptVisitor(this, data); return nPathBody.add(BigInteger.valueOf(boolComp + 1)); } @Override public BigInteger visit(ASTForeachStatement node, Void data) { // (npath of for + 1) * npath of next BigInteger nPathBody = node.getBody().acceptVisitor(this, data); return nPathBody.add(BigInteger.ONE); } @Override public BigInteger visit(ASTReturnStatement node, Void data) { // return statements are valued at 1, or the value of the boolean expression ASTExpression expr = node.getExpr(); if (expr == null) { return BigInteger.ONE; } int boolCompReturn = CycloVisitor.booleanExpressionComplexity(expr); BigInteger conditionalExpressionComplexity = multiplyChildrenComplexities(expr); return conditionalExpressionComplexity.add(BigInteger.valueOf(boolCompReturn)); } @Override public BigInteger visit(ASTSwitchExpression node, Void data) { return handleSwitch(node, data); } @Override public BigInteger visit(ASTSwitchStatement node, Void data) { return handleSwitch(node, data); } public BigInteger handleSwitch(ASTSwitchLike node, Void data) { // bool_comp of switch + sum(npath(case_range)) int boolCompSwitch = CycloVisitor.booleanExpressionComplexity(node.getTestedExpression()); BigInteger npath = BigInteger.ZERO; int caseRange = 0; for (ASTSwitchBranch n : node) { // Fall-through labels count as 1 for complexity if (n instanceof ASTSwitchFallthroughBranch) { caseRange += JavaAstUtils.numAlternatives(n); NodeStream<ASTStatement> statements = ((ASTSwitchFallthroughBranch) n).getStatements(); if (statements.nonEmpty()) { BigInteger branchNpath = multiplyComplexities(statements); npath = npath.add(branchNpath.multiply(BigInteger.valueOf(caseRange))); caseRange = 0; } } else if (n instanceof ASTSwitchArrowBranch) { int numAlts = JavaAstUtils.numAlternatives(n); BigInteger branchNpath = ((ASTSwitchArrowBranch) n).getRightHandSide().acceptVisitor(this, data); npath = npath.add(branchNpath.multiply(BigInteger.valueOf(numAlts))); } } // add in npath of last label return npath.add(BigInteger.valueOf(boolCompSwitch)); } @Override public BigInteger visit(ASTSwitchLabel node, Void data) { if (node.isDefault()) { return BigInteger.ONE; } return BigInteger.valueOf(node.children(ASTExpression.class).count()); } @Override public BigInteger visit(ASTConditionalExpression node, Void data) { // bool comp of guard clause + complexity of last two children (= total - 1) int boolCompTernary = CycloVisitor.booleanExpressionComplexity(node.getCondition()); return sumChildrenComplexities(node, data).add(BigInteger.valueOf(boolCompTernary - 1)); } @Override public BigInteger visit(ASTTryStatement node, Void data) { /* * This scenario was not addressed by the original paper. Based on the * principles outlined in the paper, as well as the Checkstyle NPath * implementation, this code will add the complexity of the try to the * complexities of the catch and finally blocks. */ return sumChildrenComplexities(node, data); } }
8,032
36.018433
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/ClassFanOutVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics.internal; import java.util.Set; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.lang.java.ast.TypeNode; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.ClassFanOutOption; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.metrics.MetricOptions; /** * Visitor for the ClassFanOut metric. * * @author Andreas Pabst */ public final class ClassFanOutVisitor extends JavaVisitorBase<Set<JClassSymbol>, Void> { private static final ClassFanOutVisitor INCLUDE_JLANG = new ClassFanOutVisitor(true); private static final ClassFanOutVisitor EXCLUDE_JLANG = new ClassFanOutVisitor(false); private final boolean includeJavaLang; private ClassFanOutVisitor(boolean includeJavaLang) { this.includeJavaLang = includeJavaLang; } public static ClassFanOutVisitor getInstance(MetricOptions options) { if (options.getOptions().contains(ClassFanOutOption.INCLUDE_JAVA_LANG)) { return INCLUDE_JLANG; } else { return EXCLUDE_JLANG; } } @Override public Void visitExpression(ASTExpression node, Set<JClassSymbol> data) { check(node, data); return visitChildren(node, data); } @Override public Void visit(ASTClassOrInterfaceType node, Set<JClassSymbol> data) { check(node, data); return visitChildren(node, data); } private void check(TypeNode node, Set<JClassSymbol> classes) { JTypeMirror typeMirror = node.getTypeMirror(); if (!(typeMirror instanceof JClassType)) { return; } JClassSymbol symbol = ((JClassType) typeMirror).getSymbol(); if (shouldBeIncluded(symbol)) { classes.add(symbol); } } private boolean shouldBeIncluded(JClassSymbol classToCheck) { return includeJavaLang || !JClassSymbol.PRIMITIVE_PACKAGE.equals(classToCheck.getPackageName()); } }
2,341
31.985915
104
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/CycloVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics.internal; import org.apache.commons.lang3.mutable.MutableInt; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTAssertStatement; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTDoStatement; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression; import net.sourceforge.pmd.lang.java.ast.ASTSwitchFallthroughBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.CycloOption; import net.sourceforge.pmd.lang.metrics.MetricOptions; /** * Visitor for the Cyclo metric. * * @author Clément Fournier * @since 6.7.0 */ public class CycloVisitor extends JavaVisitorBase<MutableInt, Void> { protected final boolean considerBooleanPaths; protected final boolean considerAssert; private final JavaNode topNode; public CycloVisitor(MetricOptions options, JavaNode topNode) { considerBooleanPaths = !options.getOptions().contains(CycloOption.IGNORE_BOOLEAN_PATHS); considerAssert = options.getOptions().contains(CycloOption.CONSIDER_ASSERT); this.topNode = topNode; } @Override public final Void visitJavaNode(JavaNode localNode, MutableInt data) { return localNode.isFindBoundary() && !localNode.equals(topNode) ? null : super.visitJavaNode(localNode, data); } @Override public Void visit(ASTSwitchExpression node, MutableInt data) { return handleSwitch(node, data); } @Override public Void visit(ASTSwitchStatement node, MutableInt data) { return handleSwitch(node, data); } private Void handleSwitch(ASTSwitchLike node, MutableInt data) { if (considerBooleanPaths) { data.add(booleanExpressionComplexity(node.getTestedExpression())); } for (ASTSwitchBranch branch : node) { if (branch.getLabel().isDefault()) { // like for "else", default is not a decision point continue; } if (considerBooleanPaths) { data.add(JavaAstUtils.numAlternatives(branch)); } else if (branch instanceof ASTSwitchFallthroughBranch && ((ASTSwitchFallthroughBranch) branch).getStatements().nonEmpty()) { data.increment(); } } return visitJavaNode(node, data); } @Override public Void visit(ASTConditionalExpression node, MutableInt data) { data.increment(); if (considerBooleanPaths) { data.add(booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); } @Override public Void visit(ASTWhileStatement node, MutableInt data) { data.increment(); if (considerBooleanPaths) { data.add(booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); } @Override public Void visit(ASTIfStatement node, MutableInt data) { data.increment(); if (considerBooleanPaths) { data.add(booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); } @Override public Void visit(ASTForStatement node, MutableInt data) { data.increment(); if (considerBooleanPaths) { data.add(booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); } @Override public Void visit(ASTForeachStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visitMethodOrCtor(ASTMethodOrConstructorDeclaration node, MutableInt data) { data.increment(); return super.visitMethodOrCtor(node, data); } @Override public Void visit(ASTDoStatement node, MutableInt data) { data.increment(); if (considerBooleanPaths) { data.add(booleanExpressionComplexity(node.getCondition())); } return super.visit(node, data); } @Override public Void visit(ASTCatchClause node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTThrowStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTAssertStatement node, MutableInt data) { if (considerAssert) { data.add(2); // equivalent to if (condition) { throw .. } if (considerBooleanPaths) { data.add(booleanExpressionComplexity(node.getCondition())); } } return super.visit(node, data); } /** * Evaluates the number of paths through a boolean expression. This is the total number of {@code &&} and {@code ||} * operators appearing in the expression. This is used in the calculation of cyclomatic and n-path complexity. * * @param expr Expression to analyse * * @return The number of paths through the expression */ public static int booleanExpressionComplexity(@Nullable ASTExpression expr) { if (expr == null) { return 0; } if (expr instanceof ASTConditionalExpression) { ASTConditionalExpression conditional = (ASTConditionalExpression) expr; return booleanExpressionComplexity(conditional.getCondition()) + booleanExpressionComplexity(conditional.getThenBranch()) + booleanExpressionComplexity(conditional.getElseBranch()) + 2; } else { return expr.descendantsOrSelf() .filter(JavaAstUtils::isConditional) .count(); } } }
6,796
31.366667
120
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/AtfdBaseVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics.internal; import org.apache.commons.lang3.mutable.MutableInt; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTSuperExpression; import net.sourceforge.pmd.lang.java.ast.ASTThisExpression; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; /** * Computes Atfd. * * @author Clément Fournier * @since 6.0.0 */ public class AtfdBaseVisitor extends JavaVisitorBase<MutableInt, Void> { @Override public Void visit(ASTMethodCall node, MutableInt data) { if (isForeignMethod(node)) { data.increment(); } return visitChildren(node, data); } @Override public Void visit(ASTFieldAccess node, MutableInt data) { if (isForeignField(node)) { data.increment(); } return visitChildren(node, data); } private boolean isForeignField(ASTFieldAccess node) { JFieldSymbol sym = node.getReferencedSym(); if (sym == null || sym.isStatic()) { return false; } ASTExpression qualifier = node.getQualifier(); return !(qualifier instanceof ASTThisExpression || qualifier instanceof ASTSuperExpression || sym.getEnclosingClass().equals(node.getEnclosingType().getSymbol()) ); } private boolean isForeignMethod(ASTMethodCall node) { return JavaRuleUtil.isGetterOrSetterCall(node) && node.getQualifier() != null && !(node.getQualifier() instanceof ASTThisExpression); } }
1,928
30.112903
82
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/NcssVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics.internal; import java.util.List; import org.apache.commons.lang3.mutable.MutableInt; import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAssertStatement; import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTContinueStatement; import net.sourceforge.pmd.lang.java.ast.ASTDoStatement; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFinallyClause; import net.sourceforge.pmd.lang.java.ast.ASTForInit; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTForUpdate; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTInitializer; import net.sourceforge.pmd.lang.java.ast.ASTLabeledStatement; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTPackageDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTSynchronizedStatement; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.NcssOption; import net.sourceforge.pmd.lang.metrics.MetricOptions; /** * Visitor for the Ncss metric. * * @author Clément Fournier * @since 6.7.0 */ public class NcssVisitor extends JavaVisitorBase<MutableInt, Void> { protected final boolean countImports; @SuppressWarnings("PMD.UnusedFormalParameter") public NcssVisitor(MetricOptions options, JavaNode topNode) { countImports = options.contains(NcssOption.COUNT_IMPORTS); // topNode is unused, but we'll need it if we want to discount lambdas // if we add it later, we break binary compatibility } @Override public final Void visitJavaNode(JavaNode node, MutableInt data) { // same here return super.visitJavaNode(node, data); } @Override public Void visit(ASTClassOrInterfaceDeclaration node, MutableInt data) { if (countImports) { ASTCompilationUnit acu = node.getFirstParentOfType(ASTCompilationUnit.class); List<ASTImportDeclaration> imports = acu.findChildrenOfType(ASTImportDeclaration.class); int increment = imports.size(); if (!acu.findChildrenOfType(ASTPackageDeclaration.class).isEmpty()) { increment++; } data.add(increment); } data.increment(); return super.visit(node, data); } @Override public Void visit(ASTEnumDeclaration node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTAnnotationTypeDeclaration node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTFieldDeclaration node, MutableInt data) { data.increment(); // May use a lambda return super.visit(node, data); } @Override public Void visit(ASTMethodDeclaration node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTConstructorDeclaration node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTLocalVariableDeclaration node, MutableInt data) { // doesn't count variable declared inside a for initializer if (!(node.getParent() instanceof ASTForInit)) { data.increment(); } // May declare a lambda return super.visit(node, data); } @Override public Void visit(ASTIfStatement node, MutableInt data) { data.increment(); if (node.hasElse()) { data.increment(); } return super.visit(node, data); } @Override public Void visit(ASTWhileStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTSwitchStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTExpressionStatement node, MutableInt data) { if (!(node.getParent().getParent() instanceof ASTForUpdate)) { data.increment(); } return null; } @Override public Void visit(ASTExplicitConstructorInvocation node, MutableInt data) { data.increment(); return null; } @Override public Void visit(ASTContinueStatement node, MutableInt data) { data.increment(); return null; } @Override public Void visit(ASTBreakStatement node, MutableInt data) { data.increment(); return null; } @Override public Void visit(ASTReturnStatement node, MutableInt data) { data.increment(); return null; } @Override public Void visit(ASTDoStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTForStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTSynchronizedStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTCatchClause node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTThrowStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTFinallyClause node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTLabeledStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTSwitchLabel node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTInitializer node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTAssertStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } }
7,598
26.9375
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/CognitiveComplexityVisitor.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.metrics.internal; import java.util.ArrayDeque; import java.util.Deque; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBody; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTContinueStatement; import net.sourceforge.pmd.lang.java.ast.ASTDoStatement; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.ast.BinaryOp; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavaVisitorBase; import net.sourceforge.pmd.lang.java.ast.UnaryOp; import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; /** * Visitor for the Cognitive Complexity metric. * * @author Denis Borovikov * @since 6.35.0 */ public class CognitiveComplexityVisitor extends JavaVisitorBase<CognitiveComplexityVisitor.State, Void> { /** Instance. */ public static final CognitiveComplexityVisitor INSTANCE = new CognitiveComplexityVisitor(); public enum BooleanOp { AND, OR } public static class State { private int complexity = 0; private int nestingLevel = 0; private BooleanOp currentBooleanOperation = null; private final Deque<ASTMethodDeclaration> methodStack; public State(JavaNode topNode) { this.methodStack = new ArrayDeque<>(); // push enclosing methods on the stack // so that the stack is independent of where we started the visitor; topNode.ancestors() .filterIs(ASTMethodDeclaration.class) .forEach(methodStack::addLast); } public int getComplexity() { return complexity; } void hybridComplexity() { complexity++; nestingLevel++; } void fundamentalComplexity() { complexity++; } void structuralComplexity() { complexity++; complexity += nestingLevel; nestingLevel++; } void increaseNestingLevel() { nestingLevel++; } void decreaseNestingLevel() { nestingLevel--; } void booleanOperation(BooleanOp op) { if (currentBooleanOperation != op) { if (op != null) { fundamentalComplexity(); } currentBooleanOperation = op; } } void pushMethod(ASTMethodDeclaration calledMethod) { methodStack.push(calledMethod); } void popMethod() { methodStack.pop(); } void callMethod(JMethodSymbol calledMethod) { ASTMethodDeclaration methodNode = calledMethod.tryGetNode(); if (methodNode != null && methodStack.contains(methodNode)) { // This means it's a recursive call. // Note that we consider the entire stack and not just the top. // This is an arbitrary decision that may cause FPs... // Specifically it matters when anonymous classes are involved. // void outer() { // Runnable r = new Runnable(){ // public void run(){ // outer(); // } // }; // // r = () -> outer(); // } // // If we only consider the top of the stack, then within the anonymous class, `outer()` // is not counted as a recursive call. This means the anonymous class // has lower complexity than the lambda (because in the lambda the top // of the stack is `outer`). // // TODO Arguably this could be improved by adding a complexity point // for anonymous classes, because they're syntactically heavyweight. // This would incentivize using lambdas. fundamentalComplexity(); } } @Override public String toString() { return "State{complexity=" + complexity + ", nestingLevel=" + nestingLevel + ", currentBooleanOperation=" + currentBooleanOperation + '}'; } } @Override public Void visit(ASTIfStatement node, State state) { boolean isNotElseIf = !(node.getParent() instanceof ASTIfStatement); node.getCondition().acceptVisitor(this, state); if (isNotElseIf) { state.structuralComplexity(); } node.getThenBranch().acceptVisitor(this, state); if (isNotElseIf) { state.decreaseNestingLevel(); } if (node.hasElse()) { state.hybridComplexity(); node.getElseBranch().acceptVisitor(this, state); state.decreaseNestingLevel(); } return null; } @Override public Void visit(ASTContinueStatement node, State state) { // hack to detect if there is a label boolean hasLabel = node.getImage() != null; if (hasLabel) { state.fundamentalComplexity(); } return visitChildren(node, state); } @Override public Void visit(ASTBreakStatement node, State state) { // hack to detect if there is a label boolean hasLabel = node.getImage() != null; if (hasLabel) { state.fundamentalComplexity(); } return visitChildren(node, state); } @Override public Void visit(ASTInfixExpression node, State state) { BinaryOp op = node.getOperator(); if (op == BinaryOp.CONDITIONAL_AND) { state.booleanOperation(BooleanOp.AND); } else if (op == BinaryOp.CONDITIONAL_OR) { state.booleanOperation(BooleanOp.OR); } return visitChildren(node, state); } @Override public Void visit(ASTUnaryExpression node, State state) { if (node.getOperator() == UnaryOp.NEGATION) { state.booleanOperation(null); } return visitChildren(node, state); } @Override public Void visit(ASTBlock node, State state) { for (JavaNode child : node.children()) { // This needs to happen because the current 'run' of boolean operations is terminated // once we finish a statement. state.booleanOperation(null); child.acceptVisitor(this, state); } return null; } @Override public Void visit(ASTMethodDeclaration node, State state) { state.pushMethod(node); visitChildren(node, state); state.popMethod(); return null; } @Override public Void visit(ASTMethodCall node, State state) { JExecutableSymbol calledSymbol = node.getOverloadSelectionInfo().getMethodType().getSymbol(); if (calledSymbol instanceof JMethodSymbol) { state.callMethod((JMethodSymbol) calledSymbol); } return visitChildren(node, state); } @Override public Void visit(ASTForStatement node, State state) { return structural(node, state); } @Override public Void visit(ASTForeachStatement node, State state) { return structural(node, state); } @Override public Void visit(ASTSwitchStatement node, State state) { return structural(node, state); } @Override public Void visit(ASTLambdaExpression node, State state) { return nonStructural(node, state); } @Override public Void visit(ASTClassOrInterfaceBody node, State state) { return nonStructural(node, state); } @Override public Void visit(ASTWhileStatement node, State state) { return structural(node, state); } @Override public Void visit(ASTCatchClause node, State state) { return structural(node, state); } @Override public Void visit(ASTDoStatement node, State state) { return structural(node, state); } @Override public Void visit(ASTConditionalExpression node, State state) { return structural(node, state); } private Void nonStructural(JavaNode node, State state) { state.increaseNestingLevel(); visitChildren(node, state); state.decreaseNestingLevel(); return null; } private Void structural(JavaNode node, State state) { state.structuralComplexity(); visitChildren(node, state); state.decreaseNestingLevel(); return null; } }
9,527
29.440895
105
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/package-info.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * Contains the built-in rules bundled with the Java distribution. */ package net.sourceforge.pmd.lang.java.rule;
208
22.222222
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/AbstractJavaRulechainRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; /** * Base class for rules using the rulechain. The visit methods don't * recurse by default. * * @author Clément Fournier * @since 7.0.0 */ public abstract class AbstractJavaRulechainRule extends AbstractJavaRule { private final RuleTargetSelector selector; /** * Specify the node types to visit as parameters. * * @param first The first node, there must be at least one * @param visits The rest */ @SafeVarargs @Experimental public AbstractJavaRulechainRule(Class<? extends JavaNode> first, Class<? extends JavaNode>... visits) { selector = RuleTargetSelector.forTypes(first, visits); } @Override protected final @NonNull RuleTargetSelector buildTargetSelector() { return selector; } @Override public Object visitJavaNode(JavaNode node, Object data) { return data; } }
1,233
25.826087
108
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/AbstractJavaRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ 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.JavaParserVisitor; import net.sourceforge.pmd.lang.rule.AbstractRule; /** * Base class for Java rules. Any rule written in Java to analyse Java source should extend from * this base class. * * TODO add documentation * */ public abstract class AbstractJavaRule extends AbstractRule implements JavaParserVisitor { @Override public void apply(Node target, RuleContext ctx) { target.acceptVisitor(this, ctx); } }
695
23.857143
96
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/AbstractIgnoredAnnotationRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.util.Collection; import java.util.Collections; import java.util.List; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.java.ast.Annotatable; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * @deprecated Internal API */ @Deprecated @InternalApi public abstract class AbstractIgnoredAnnotationRule extends AbstractJavaRule { private final PropertyDescriptor<List<String>> ignoredAnnotationsDescriptor = stringListProperty("ignoredAnnotations") .desc(defaultIgnoredAnnotationsDescription()) .defaultValue(defaultSuppressionAnnotations()) .build(); protected Collection<String> defaultSuppressionAnnotations() { return Collections.emptyList(); } protected String defaultIgnoredAnnotationsDescription() { return "Fully qualified names of the annotation types that should be ignored by this rule"; } protected AbstractIgnoredAnnotationRule() { definePropertyDescriptor(ignoredAnnotationsDescriptor); } /** * Checks whether any annotation in ignoredAnnotationsDescriptor is present on the node. * * @param node * the node to check * @return <code>true</code> if the annotation has been found, otherwise <code>false</code> */ protected boolean hasIgnoredAnnotation(Annotatable node) { return getProperty(ignoredAnnotationsDescriptor).stream().anyMatch(node::isAnnotationPresent); } }
1,706
30.611111
102
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/security/AbstractHardCodedConstructorArgsVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.security; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTArrayAllocation; import net.sourceforge.pmd.lang.java.ast.ASTArrayInitializer; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.AccessType; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; abstract class AbstractHardCodedConstructorArgsVisitor extends AbstractJavaRulechainRule { private final Class<?> type; AbstractHardCodedConstructorArgsVisitor(Class<?> constructorType) { super(ASTConstructorCall.class); this.type = constructorType; } @Override public Object visit(ASTConstructorCall node, Object data) { if (TypeTestUtil.isA(type, node)) { ASTArgumentList arguments = node.getArguments(); if (arguments.size() > 0) { validateProperKeyArgument(data, arguments.get(0)); } } return data; } /** * Recursively resolves the argument again, if the variable initializer * is itself a expression. * * <p>Then checks the expression for being a string literal or array */ private void validateProperKeyArgument(Object data, ASTExpression firstArgumentExpression) { if (firstArgumentExpression == null) { return; } ASTVariableAccess varAccess = null; if (firstArgumentExpression instanceof ASTMethodCall) { // check for method call on a named variable ASTExpression expr = ((ASTMethodCall) firstArgumentExpression).getQualifier(); if (expr instanceof ASTVariableAccess) { varAccess = (ASTVariableAccess) expr; } } else if (firstArgumentExpression instanceof ASTVariableAccess) { // check for named variable varAccess = (ASTVariableAccess) firstArgumentExpression; } if (varAccess != null && varAccess.getSignature() != null && varAccess.getSignature().getSymbol() != null) { // named variable or method call on named variable found ASTVariableDeclaratorId varDecl = varAccess.getSignature().getSymbol().tryGetNode(); validateProperKeyArgument(data, varDecl.getInitializer()); validateVarUsages(data, varDecl); } else if (firstArgumentExpression instanceof ASTArrayAllocation) { // hard coded array ASTArrayInitializer arrayInit = ((ASTArrayAllocation) firstArgumentExpression).getArrayInitializer(); if (arrayInit != null) { addViolation(data, arrayInit); } } else { // string literal ASTStringLiteral literal = firstArgumentExpression.descendantsOrSelf() .filterIs(ASTStringLiteral.class).first(); if (literal != null) { addViolation(data, literal); } } } private void validateVarUsages(Object data, ASTVariableDeclaratorId varDecl) { varDecl.getLocalUsages().stream() .filter(u -> u.getAccessType() == AccessType.WRITE) .filter(u -> u.getParent() instanceof ASTAssignmentExpression) .forEach(usage -> { ASTAssignmentExpression assignment = (ASTAssignmentExpression) usage.getParent(); validateProperKeyArgument(data, assignment.getRightOperand()); }); } }
4,042
41.114583
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/security/HardCodedCryptoKeyRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.security; /** * Finds hard coded encryption keys that are passed to * javax.crypto.spec.SecretKeySpec(key, algorithm). * * @author sergeygorbaty * @since 6.4.0 */ public class HardCodedCryptoKeyRule extends AbstractHardCodedConstructorArgsVisitor { public HardCodedCryptoKeyRule() { super(javax.crypto.spec.SecretKeySpec.class); } }
489
22.333333
85
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/security/InsecureCryptoIvRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.security; /** * Finds hardcoded static Initialization Vectors vectors used with cryptographic * operations. * * <code> * //bad: byte[] ivBytes = new byte[] {32, 87, -14, 25, 78, -104, 98, 40}; * //bad: byte[] ivBytes = "hardcoded".getBytes(); * //bad: byte[] ivBytes = someString.getBytes(); * </code> * * <p>{@link javax.crypto.spec.IvParameterSpec} must not be created from a static sources * * @author sergeygorbaty * @since 6.3.0 * */ public class InsecureCryptoIvRule extends AbstractHardCodedConstructorArgsVisitor { public InsecureCryptoIvRule() { super(javax.crypto.spec.IvParameterSpec.class); } }
771
25.62069
89
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentSizeRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.documentation; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.document.Chars; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.JavaComment; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * A rule to manage those who just can't shut up... * * @author Brian Remedios */ public class CommentSizeRule extends AbstractJavaRulechainRule { public static final PropertyDescriptor<Integer> MAX_LINES = PropertyFactory.intProperty("maxLines") .desc("Maximum lines") .require(positive()).defaultValue(6).build(); public static final PropertyDescriptor<Integer> MAX_LINE_LENGTH = PropertyFactory.intProperty("maxLineLength") .desc("Maximum line length") .require(positive()).defaultValue(80).build(); public CommentSizeRule() { super(ASTCompilationUnit.class); definePropertyDescriptor(MAX_LINES); definePropertyDescriptor(MAX_LINE_LENGTH); } @Override public Object visit(ASTCompilationUnit cUnit, Object data) { for (JavaComment comment : cUnit.getComments()) { if (hasTooManyLines(comment)) { addViolationWithMessage(data, cUnit, this.getMessage() + ": Too many lines", comment.getBeginLine(), comment.getEndLine()); } reportLinesTooLong(cUnit, asCtx(data), comment); } return null; } private static boolean hasRealText(Chars line) { return !JavaComment.removeCommentMarkup(line).isEmpty(); } private boolean hasTooManyLines(JavaComment comment) { int firstLineWithText = -1; int lastLineWithText; int lineNumberWithinComment = 0; int maxLines = getProperty(MAX_LINES); for (Chars line : comment.getText().lines()) { if (hasRealText(line)) { lastLineWithText = lineNumberWithinComment; if (firstLineWithText == -1) { firstLineWithText = lineNumberWithinComment; } if (lastLineWithText - firstLineWithText + 1 > maxLines) { return true; } } lineNumberWithinComment++; } return false; } private void reportLinesTooLong(ASTCompilationUnit acu, RuleContext ctx, JavaComment comment) { int maxLength = getProperty(MAX_LINE_LENGTH); int lineNumber = comment.getReportLocation().getStartLine(); for (Chars line : comment.getFilteredLines(true)) { if (line.length() > maxLength) { ctx.addViolationWithPosition(acu, lineNumber, lineNumber, getMessage() + ": Line too long"); } lineNumber++; } } }
3,375
33.44898
99
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentContentRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.documentation; import static net.sourceforge.pmd.properties.PropertyFactory.regexProperty; import java.util.regex.Pattern; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.document.Chars; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.JavaComment; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * A rule that checks for illegal words in the comment text. * * @author Brian Remedios */ public class CommentContentRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Pattern> DISSALLOWED_TERMS_DESCRIPTOR = regexProperty("forbiddenRegex") .desc("Illegal terms or phrases") .defaultValue("idiot|jerk").build(); public CommentContentRule() { super(ASTCompilationUnit.class); definePropertyDescriptor(DISSALLOWED_TERMS_DESCRIPTOR); } @Override public Object visit(ASTCompilationUnit node, Object data) { Pattern pattern = getProperty(DISSALLOWED_TERMS_DESCRIPTOR); for (JavaComment comment : node.getComments()) { reportIllegalTerms(asCtx(data), comment, pattern, node); } return null; } private void reportIllegalTerms(RuleContext ctx, JavaComment comment, Pattern violationRegex, Node acu) { int lineNumber = comment.getReportLocation().getStartLine(); for (Chars line : comment.getFilteredLines(true)) { if (violationRegex.matcher(line).find()) { ctx.addViolationWithPosition( acu, lineNumber, lineNumber, "Line matches forbidden content regex ({0})", violationRegex.pattern() ); } lineNumber++; } } }
2,098
30.328358
109
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/documentation/CommentRequiredRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.documentation; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.JavadocCommentOwner; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.properties.PropertyBuilder.GenericPropertyBuilder; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * @author Brian Remedios */ public class CommentRequiredRule extends AbstractJavaRulechainRule { private static final Logger LOG = LoggerFactory.getLogger(CommentRequiredRule.class); // Used to pretty print a message private static final Map<String, String> DESCRIPTOR_NAME_TO_COMMENT_TYPE = new HashMap<>(); private static final PropertyDescriptor<CommentRequirement> ACCESSOR_CMT_DESCRIPTOR = requirementPropertyBuilder("accessorCommentRequirement", "Comments on getters and setters\"") .defaultValue(CommentRequirement.Ignored).build(); private static final PropertyDescriptor<CommentRequirement> OVERRIDE_CMT_DESCRIPTOR = requirementPropertyBuilder("methodWithOverrideCommentRequirement", "Comments on @Override methods") .defaultValue(CommentRequirement.Ignored).build(); private static final PropertyDescriptor<CommentRequirement> HEADER_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("headerCommentRequirement", "Deprecated! Header comments. Please use the property \"classCommentRequired\" instead.").build(); private static final PropertyDescriptor<CommentRequirement> CLASS_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("classCommentRequirement", "Class comments").build(); private static final PropertyDescriptor<CommentRequirement> FIELD_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("fieldCommentRequirement", "Field comments").build(); private static final PropertyDescriptor<CommentRequirement> PUB_METHOD_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("publicMethodCommentRequirement", "Public method and constructor comments").build(); private static final PropertyDescriptor<CommentRequirement> PROT_METHOD_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("protectedMethodCommentRequirement", "Protected method constructor comments").build(); private static final PropertyDescriptor<CommentRequirement> ENUM_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("enumCommentRequirement", "Enum comments").build(); private static final PropertyDescriptor<CommentRequirement> SERIAL_VERSION_UID_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("serialVersionUIDCommentRequired", "Serial version UID comments") .defaultValue(CommentRequirement.Ignored).build(); private static final PropertyDescriptor<CommentRequirement> SERIAL_PERSISTENT_FIELDS_CMT_REQUIREMENT_DESCRIPTOR = requirementPropertyBuilder("serialPersistentFieldsCommentRequired", "Serial persistent fields comments") .defaultValue(CommentRequirement.Ignored).build(); /** stores the resolved property values. This is necessary in order to transparently use deprecated properties. */ private final Map<PropertyDescriptor<CommentRequirement>, CommentRequirement> propertyValues = new HashMap<>(); public CommentRequiredRule() { super(ASTBodyDeclaration.class); definePropertyDescriptor(OVERRIDE_CMT_DESCRIPTOR); definePropertyDescriptor(ACCESSOR_CMT_DESCRIPTOR); definePropertyDescriptor(CLASS_CMT_REQUIREMENT_DESCRIPTOR); definePropertyDescriptor(HEADER_CMT_REQUIREMENT_DESCRIPTOR); definePropertyDescriptor(FIELD_CMT_REQUIREMENT_DESCRIPTOR); definePropertyDescriptor(PUB_METHOD_CMT_REQUIREMENT_DESCRIPTOR); definePropertyDescriptor(PROT_METHOD_CMT_REQUIREMENT_DESCRIPTOR); definePropertyDescriptor(ENUM_CMT_REQUIREMENT_DESCRIPTOR); definePropertyDescriptor(SERIAL_VERSION_UID_CMT_REQUIREMENT_DESCRIPTOR); definePropertyDescriptor(SERIAL_PERSISTENT_FIELDS_CMT_REQUIREMENT_DESCRIPTOR); } @Override public void start(RuleContext ctx) { propertyValues.put(ACCESSOR_CMT_DESCRIPTOR, getProperty(ACCESSOR_CMT_DESCRIPTOR)); propertyValues.put(OVERRIDE_CMT_DESCRIPTOR, getProperty(OVERRIDE_CMT_DESCRIPTOR)); propertyValues.put(FIELD_CMT_REQUIREMENT_DESCRIPTOR, getProperty(FIELD_CMT_REQUIREMENT_DESCRIPTOR)); propertyValues.put(PUB_METHOD_CMT_REQUIREMENT_DESCRIPTOR, getProperty(PUB_METHOD_CMT_REQUIREMENT_DESCRIPTOR)); propertyValues.put(PROT_METHOD_CMT_REQUIREMENT_DESCRIPTOR, getProperty(PROT_METHOD_CMT_REQUIREMENT_DESCRIPTOR)); propertyValues.put(ENUM_CMT_REQUIREMENT_DESCRIPTOR, getProperty(ENUM_CMT_REQUIREMENT_DESCRIPTOR)); propertyValues.put(SERIAL_VERSION_UID_CMT_REQUIREMENT_DESCRIPTOR, getProperty(SERIAL_VERSION_UID_CMT_REQUIREMENT_DESCRIPTOR)); propertyValues.put(SERIAL_PERSISTENT_FIELDS_CMT_REQUIREMENT_DESCRIPTOR, getProperty(SERIAL_PERSISTENT_FIELDS_CMT_REQUIREMENT_DESCRIPTOR)); CommentRequirement headerCommentRequirementValue = getProperty(HEADER_CMT_REQUIREMENT_DESCRIPTOR); boolean headerCommentRequirementValueOverridden = headerCommentRequirementValue != CommentRequirement.Required; CommentRequirement classCommentRequirementValue = getProperty(CLASS_CMT_REQUIREMENT_DESCRIPTOR); boolean classCommentRequirementValueOverridden = classCommentRequirementValue != CommentRequirement.Required; if (headerCommentRequirementValueOverridden && !classCommentRequirementValueOverridden) { LOG.warn("Rule CommentRequired uses deprecated property 'headerCommentRequirement'. " + "Future versions of PMD will remove support for this property. " + "Please use 'classCommentRequirement' instead!"); propertyValues.put(CLASS_CMT_REQUIREMENT_DESCRIPTOR, headerCommentRequirementValue); } else { propertyValues.put(CLASS_CMT_REQUIREMENT_DESCRIPTOR, classCommentRequirementValue); } } private void checkCommentMeetsRequirement(Object data, JavadocCommentOwner node, PropertyDescriptor<CommentRequirement> descriptor) { switch (propertyValues.get(descriptor)) { case Ignored: break; case Required: if (node.getJavadocComment() == null) { commentRequiredViolation(data, node, descriptor); } break; case Unwanted: if (node.getJavadocComment() != null) { commentRequiredViolation(data, node, descriptor); } break; default: break; } } // Adds a violation private void commentRequiredViolation(Object data, JavaNode node, PropertyDescriptor<CommentRequirement> descriptor) { addViolationWithMessage(data, node, DESCRIPTOR_NAME_TO_COMMENT_TYPE.get(descriptor.name()) + " are " + getProperty(descriptor).label.toLowerCase(Locale.ROOT)); } @Override public Object visit(ASTClassOrInterfaceDeclaration decl, Object data) { checkCommentMeetsRequirement(data, decl, CLASS_CMT_REQUIREMENT_DESCRIPTOR); return data; } @Override public Object visit(ASTConstructorDeclaration decl, Object data) { checkMethodOrConstructorComment(decl, data); return data; } @Override public Object visit(ASTMethodDeclaration decl, Object data) { if (decl.isOverridden()) { checkCommentMeetsRequirement(data, decl, OVERRIDE_CMT_DESCRIPTOR); } else if (JavaRuleUtil.isGetterOrSetter(decl)) { checkCommentMeetsRequirement(data, decl, ACCESSOR_CMT_DESCRIPTOR); } else { checkMethodOrConstructorComment(decl, data); } return data; } private void checkMethodOrConstructorComment(ASTMethodOrConstructorDeclaration decl, Object data) { if (decl.getVisibility() == Visibility.V_PUBLIC) { checkCommentMeetsRequirement(data, decl, PUB_METHOD_CMT_REQUIREMENT_DESCRIPTOR); } else if (decl.getVisibility() == Visibility.V_PROTECTED) { checkCommentMeetsRequirement(data, decl, PROT_METHOD_CMT_REQUIREMENT_DESCRIPTOR); } } @Override public Object visit(ASTFieldDeclaration decl, Object data) { if (JavaRuleUtil.isSerialVersionUID(decl)) { checkCommentMeetsRequirement(data, decl, SERIAL_VERSION_UID_CMT_REQUIREMENT_DESCRIPTOR); } else if (JavaRuleUtil.isSerialPersistentFields(decl)) { checkCommentMeetsRequirement(data, decl, SERIAL_PERSISTENT_FIELDS_CMT_REQUIREMENT_DESCRIPTOR); } else { checkCommentMeetsRequirement(data, decl, FIELD_CMT_REQUIREMENT_DESCRIPTOR); } return data; } @Override public Object visit(ASTEnumDeclaration decl, Object data) { checkCommentMeetsRequirement(data, decl, ENUM_CMT_REQUIREMENT_DESCRIPTOR); return data; } private boolean allCommentsAreIgnored() { return getProperty(OVERRIDE_CMT_DESCRIPTOR) == CommentRequirement.Ignored && getProperty(ACCESSOR_CMT_DESCRIPTOR) == CommentRequirement.Ignored && (getProperty(CLASS_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored || getProperty(HEADER_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored) && getProperty(FIELD_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored && getProperty(PUB_METHOD_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored && getProperty(PROT_METHOD_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored && getProperty(ENUM_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored && getProperty(SERIAL_VERSION_UID_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored && getProperty(SERIAL_PERSISTENT_FIELDS_CMT_REQUIREMENT_DESCRIPTOR) == CommentRequirement.Ignored; } @Override public String dysfunctionReason() { return allCommentsAreIgnored() ? "All comment types are ignored" : null; } private enum CommentRequirement { Required("Required"), Ignored("Ignored"), Unwanted("Unwanted"); private static final List<String> LABELS = buildValueLabels(); private static final Map<String, CommentRequirement> MAPPINGS; private final String label; static { Map<String, CommentRequirement> tmp = new HashMap<>(); for (CommentRequirement r : values()) { tmp.put(r.label, r); } MAPPINGS = Collections.unmodifiableMap(tmp); } CommentRequirement(String theLabel) { label = theLabel; } private static List<String> buildValueLabels() { List<String> labels = new ArrayList<>(values().length); for (CommentRequirement r : values()) { labels.add(r.label); } return Collections.unmodifiableList(labels); } public static List<String> labels() { return LABELS; } public static Map<String, CommentRequirement> mappings() { return MAPPINGS; } } // pre-filled builder private static GenericPropertyBuilder<CommentRequirement> requirementPropertyBuilder(String name, String commentType) { DESCRIPTOR_NAME_TO_COMMENT_TYPE.put(name, commentType); return PropertyFactory.enumProperty(name, CommentRequirement.mappings()) .desc(commentType + ". Possible values: " + CommentRequirement.labels()) .defaultValue(CommentRequirement.Required); } }
12,931
46.719557
163
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/multithreading/UnsynchronizedStaticFormatterRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.multithreading; import java.text.Format; import java.util.Arrays; import java.util.List; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTSynchronizedStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Using a Formatter (e.g. SimpleDateFormatter, DecimalFormatter) which is static can cause * unexpected results when used in a multi-threaded environment. This rule will * find static Formatters which are used in an unsynchronized * manner. * * @author Allan Caplan * @see <a href="https://sourceforge.net/p/pmd/feature-requests/226/">feature #226 Check for SimpleDateFormat as singleton?</a> */ public class UnsynchronizedStaticFormatterRule extends AbstractJavaRulechainRule { private static final List<String> THREAD_SAFE_FORMATTER = Arrays.asList( "org.apache.commons.lang3.time.FastDateFormat" ); private static final PropertyDescriptor<Boolean> ALLOW_METHOD_LEVEL_SYNC = PropertyFactory.booleanProperty("allowMethodLevelSynchronization") .desc("If true, method level synchronization is allowed as well as synchronized block. Otherwise" + " only synchronized blocks are allowed.") .defaultValue(false) .build(); private Class<?> formatterClassToCheck = Format.class; public UnsynchronizedStaticFormatterRule() { super(ASTFieldDeclaration.class); definePropertyDescriptor(ALLOW_METHOD_LEVEL_SYNC); } UnsynchronizedStaticFormatterRule(Class<?> formatterClassToCheck) { this(); this.formatterClassToCheck = formatterClassToCheck; } @Override public Object visit(ASTFieldDeclaration node, Object data) { if (!node.hasModifiers(JModifier.STATIC)) { return data; } ASTClassOrInterfaceType cit = node.descendants(ASTClassOrInterfaceType.class).first(); if (cit == null || !TypeTestUtil.isA(formatterClassToCheck, cit)) { return data; } ASTVariableDeclaratorId var = node.descendants(ASTVariableDeclaratorId.class).first(); for (String formatter: THREAD_SAFE_FORMATTER) { if (TypeTestUtil.isA(formatter, var)) { return data; } } for (ASTNamedReferenceExpr ref : var.getLocalUsages()) { ASTMethodCall methodCall = null; if (ref.getParent() instanceof ASTMethodCall) { methodCall = (ASTMethodCall) ref.getParent(); } // ignore usages, that don't call a method. if (methodCall == null) { continue; } Node n = ref; // is there a block-level synch? ASTSynchronizedStatement syncStatement = ref.ancestors(ASTSynchronizedStatement.class).first(); if (syncStatement != null) { ASTExpression lockExpression = syncStatement.getLockExpression(); if (JavaAstUtils.isReferenceToSameVar(lockExpression, methodCall.getQualifier())) { continue; } } // method level synch enabled and used? if (getProperty(ALLOW_METHOD_LEVEL_SYNC)) { ASTMethodDeclaration method = ref.ancestors(ASTMethodDeclaration.class).first(); if (method != null && method.hasModifiers(JModifier.SYNCHRONIZED, JModifier.STATIC)) { continue; } } addViolation(data, n); } return data; } }
4,443
39.4
127
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/multithreading/NonThreadSafeSingletonRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.multithreading; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.ASTSynchronizedStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.properties.PropertyDescriptor; public class NonThreadSafeSingletonRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> CHECK_NON_STATIC_METHODS_DESCRIPTOR = booleanProperty( "checkNonStaticMethods") .desc("Check for non-static methods. Do not set this to false and checkNonStaticFields to true.") .defaultValue(true).build(); private static final PropertyDescriptor<Boolean> CHECK_NON_STATIC_FIELDS_DESCRIPTOR = booleanProperty( "checkNonStaticFields") .desc("Check for non-static fields. Do not set this to true and checkNonStaticMethods to false.") .defaultValue(false).build(); private Set<String> fields = new HashSet<>(); private boolean checkNonStaticMethods = true; private boolean checkNonStaticFields = true; public NonThreadSafeSingletonRule() { super(ASTFieldDeclaration.class, ASTMethodDeclaration.class); definePropertyDescriptor(CHECK_NON_STATIC_METHODS_DESCRIPTOR); definePropertyDescriptor(CHECK_NON_STATIC_FIELDS_DESCRIPTOR); } @Override public void start(RuleContext ctx) { fields.clear(); checkNonStaticMethods = getProperty(CHECK_NON_STATIC_METHODS_DESCRIPTOR); checkNonStaticFields = getProperty(CHECK_NON_STATIC_FIELDS_DESCRIPTOR); } @Override public Object visit(ASTFieldDeclaration node, Object data) { if (checkNonStaticFields || node.hasModifiers(JModifier.STATIC)) { for (ASTVariableDeclaratorId varId : node.getVarIds()) { fields.add(varId.getName()); } } return data; } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (checkNonStaticMethods && !node.hasModifiers(JModifier.STATIC) || node.hasModifiers(JModifier.SYNCHRONIZED)) { return data; } List<ASTIfStatement> ifStatements = node.descendants(ASTIfStatement.class).toList(); for (ASTIfStatement ifStatement : ifStatements) { if (ifStatement.getCondition().descendants(ASTNullLiteral.class).isEmpty()) { continue; } ASTNamedReferenceExpr n = ifStatement.getCondition().descendants(ASTNamedReferenceExpr.class).first(); if (n == null || !fields.contains(n.getName())) { continue; } List<ASTAssignmentExpression> assignments = ifStatement.descendants(ASTAssignmentExpression.class).toList(); boolean violation = false; for (ASTAssignmentExpression assignment : assignments) { if (assignment.ancestors(ASTSynchronizedStatement.class).nonEmpty()) { continue; } ASTAssignableExpr left = assignment.getLeftOperand(); if (left instanceof ASTNamedReferenceExpr) { JVariableSymbol referencedSym = ((ASTNamedReferenceExpr) left).getReferencedSym(); if (referencedSym instanceof JFieldSymbol) { String name = ((ASTNamedReferenceExpr) left).getName(); if (fields.contains(name)) { violation = true; } } } } if (violation) { addViolation(data, ifStatement); } } return data; } }
4,713
40.716814
120
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/multithreading/DoubleCheckedLockingRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.multithreading; import java.lang.reflect.Modifier; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTPrimitiveType; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTSynchronizedStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JLocalVariableSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; /** * <pre> * void method() { * if (x == null) { * synchronized(this){ * if (x == null) { * x = new | method(); * } * } * } * } * </pre> * * <p>The error is when one uses the value assigned within a synchronized * section, outside of a synchronized section.</p> * * <pre> * if (x == null) // is outside of synchronized section * x = new | method(); * </pre> * * <p>Very very specific check for double checked locking.</p> * * @author CL Gilbert (dnoyeb@users.sourceforge.net) */ public class DoubleCheckedLockingRule extends AbstractJavaRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (node.isVoid() || node.getResultTypeNode() instanceof ASTPrimitiveType || node.getBody() == null) { return data; } List<ASTReturnStatement> rsl = node.descendants(ASTReturnStatement.class).toList(); if (rsl.size() != 1) { return data; } ASTReturnStatement rs = rsl.get(0); ASTExpression returnExpr = rs.getExpr(); if (!(returnExpr instanceof ASTNamedReferenceExpr)) { return data; } JVariableSymbol returnVariable = ((ASTNamedReferenceExpr) returnExpr).getReferencedSym(); // With Java5 and volatile keyword, DCL is no longer an issue if (returnVariable instanceof JFieldSymbol && Modifier.isVolatile(((JFieldSymbol) returnVariable).getModifiers())) { return data; } // if the return variable is local and only written with the volatile // field, then it's ok, too if (isLocalOnlyStoredWithVolatileField(node, returnVariable)) { return data; } List<ASTIfStatement> isl = node.findDescendantsOfType(ASTIfStatement.class); if (isl.size() == 2) { ASTIfStatement outerIf = isl.get(0); if (JavaRuleUtil.isNullCheck(outerIf.getCondition(), returnVariable)) { // find synchronized List<ASTSynchronizedStatement> ssl = outerIf.findDescendantsOfType(ASTSynchronizedStatement.class); 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); if (assignments.size() == 1 && JavaAstUtils.isReferenceToVar(assignments.get(0).getLeftOperand(), returnVariable)) { addViolation(data, node); } } } } } return data; } private boolean isLocalOnlyStoredWithVolatileField(ASTMethodDeclaration method, JVariableSymbol local) { ASTExpression initializer; if (local instanceof JLocalVariableSymbol) { ASTVariableDeclaratorId id = local.tryGetNode(); if (id == null) { return false; } initializer = id.getInitializer(); } else { // the return variable name doesn't seem to be a local variable return false; } return (initializer == null || isVolatileFieldReference(initializer)) && method.descendants(ASTAssignmentExpression.class) .filter(it -> JavaAstUtils.isReferenceToVar(it.getLeftOperand(), local)) .all(it -> isVolatileFieldReference(it.getRightOperand())); } private boolean isVolatileFieldReference(@Nullable ASTExpression initializer) { if (initializer instanceof ASTNamedReferenceExpr) { JVariableSymbol fieldSym = ((ASTNamedReferenceExpr) initializer).getReferencedSym(); return fieldSym instanceof JFieldSymbol && Modifier.isVolatile(((JFieldSymbol) fieldSym).getModifiers()); } else { return false; } } }
5,598
38.153846
125
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/InvalidLogMessageFormatRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.util.CollectionUtil.immutableSetOf; import java.util.OptionalInt; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTArrayAllocation; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass; import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.AssignmentEntry; import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.DataflowResult; import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.ReachingDefinitionSet; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.util.CollectionUtil; public class InvalidLogMessageFormatRule extends AbstractJavaRulechainRule { /** * Finds placeholder for ParameterizedMessages and format specifiers * for StringFormattedMessages. */ private static final Pattern PLACEHOLDER_AND_FORMAT_SPECIFIER = Pattern.compile("(\\{})|(%(?:\\d\\$)?(?:\\w+)?(?:\\d+)?(?:\\.\\d+)?\\w)"); private static final Set<String> SLF4J = immutableSetOf("trace", "debug", "info", "warn", "error"); private static final Set<String> APACHE_SLF4J = immutableSetOf("trace", "debug", "info", "warn", "error", "fatal", "all"); /** * Whitelisted methods of net.logstash.logback.argument.StructuredArguments */ private static final Set<String> STRUCTURED_ARGUMENTS_METHODS = immutableSetOf( "a", "array", "defer", "e", "entries", "f", "fields", "keyValue", "kv", "r", "raw", "v", "value"); public InvalidLogMessageFormatRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall call, Object data) { if (isLoggerCall(call, "org.slf4j.Logger", SLF4J) || isLoggerCall(call, "org.apache.logging.log4j.Logger", APACHE_SLF4J)) { ASTArgumentList args = call.getArguments(); ASTExpression messageParam = args.toStream().first(it -> TypeTestUtil.isA(String.class, it)); if (messageParam == null) { return null; } OptionalInt expectedArgs = expectedArguments0(messageParam); if (!expectedArgs.isPresent()) { // ignore if we couldn't analyze the message parameter return null; } int expectedArguments = expectedArgs.getAsInt(); int providedArguments = args.size() - (messageParam.getIndexInParent() + 1); if (providedArguments == 1 && JavaAstUtils.isArrayInitializer(args.getLastChild())) { providedArguments = ((ASTArrayAllocation) args.getLastChild()).getArrayInitializer().length(); } else if (TypeTestUtil.isA(Throwable.class, args.getLastChild()) && providedArguments > expectedArguments) { // Remove throwable param, since it is shown separately. // But only, if it is not used as a placeholder argument providedArguments--; } // remove any logstash structured arguments at the end // but only, if there are not enough placeholders if (providedArguments > expectedArguments) { int removed = removePotentialStructuredArguments(providedArguments - expectedArguments, args); providedArguments -= removed; } if (providedArguments < expectedArguments) { addViolationWithMessage( data, call, "Missing arguments," + getExpectedMessage(providedArguments, expectedArguments)); } else if (providedArguments > expectedArguments) { addViolationWithMessage( data, call, "Too many arguments," + getExpectedMessage(providedArguments, expectedArguments)); } } return null; } private boolean isLoggerCall(ASTMethodCall call, String loggerType, Set<String> methodNames) { return TypeTestUtil.isA(loggerType, call.getQualifier()) && methodNames.contains(call.getMethodName()); } private static int countPlaceHolders(@NonNull String constValue) { int result = 0; Matcher matcher = PLACEHOLDER_AND_FORMAT_SPECIFIER.matcher(constValue); while (matcher.find()) { String format = matcher.group(); if (!"%%".equals(format) && !"%n".equals(format)) { result++; } } return result; } private static OptionalInt expectedArguments0(final ASTExpression node) { if (node.getConstValue() instanceof String) { return OptionalInt.of(countPlaceHolders((String) node.getConstValue())); } else if (node instanceof ASTNamedReferenceExpr) { DataflowResult dataflow = DataflowPass.getDataflowResult(node.getRoot()); ReachingDefinitionSet reaching = dataflow.getReachingDefinitions((ASTNamedReferenceExpr) node); if (reaching.isNotFullyKnown()) { return OptionalInt.empty(); } AssignmentEntry assignment = CollectionUtil.asSingle(reaching.getReaching()); if (assignment == null) { return OptionalInt.empty(); } ASTExpression rhs = assignment.getRhsAsExpression(); if (rhs != null && rhs.getConstValue() instanceof String) { return OptionalInt.of(countPlaceHolders((String) rhs.getConstValue())); } } return OptionalInt.empty(); } private String getExpectedMessage(final int providedArguments, final int expectedArguments) { return " expected " + expectedArguments + (expectedArguments > 1 ? " arguments " : " argument ") + "but found " + providedArguments; } /** * Removes up to {@code maxArgumentsToRemove} arguments from the end of the {@code argumentList}, * if the argument is a method call to one of the whitelisted StructuredArguments methods. * * @param maxArgumentsToRemove * @param argumentList */ private int removePotentialStructuredArguments(int maxArgumentsToRemove, ASTArgumentList argumentList) { int removed = 0; int lastIndex = argumentList.size() - 1; while (argumentList.size() > 0 && removed < maxArgumentsToRemove) { ASTExpression argument = argumentList.get(lastIndex); if (isStructuredArgumentMethodCall(argument)) { removed++; } else { // stop if something else is encountered break; } lastIndex--; } return removed; } private boolean isStructuredArgumentMethodCall(ASTExpression argument) { if (argument instanceof ASTMethodCall) { ASTMethodCall methodCall = (ASTMethodCall) argument; @Nullable ASTExpression qualifier = methodCall.getQualifier(); return TypeTestUtil.isA("net.logstash.logback.argument.StructuredArguments", qualifier) || STRUCTURED_ARGUMENTS_METHODS.contains(methodCall.getMethodName()); } return false; } }
7,930
42.103261
126
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/DetachedTestCaseRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil; public class DetachedTestCaseRule extends AbstractJavaRulechainRule { public DetachedTestCaseRule() { super(ASTClassOrInterfaceDeclaration.class); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, final Object data) { NodeStream<ASTMethodDeclaration> methods = node.getDeclarations(ASTMethodDeclaration.class); if (methods.any(TestFrameworksUtil::isTestMethod)) { // looks like a test case methods.filter(m -> m.getArity() == 0 && m.isVoid() && !m.getModifiers().hasAny(JModifier.STATIC, JModifier.PRIVATE, JModifier.PROTECTED)) // the method itself has no annotation .filter(it -> it.getDeclaredAnnotations().isEmpty()) .forEach(m -> addViolation(data, m)); } return null; } }
1,408
39.257143
109
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/AvoidUsingOctalValuesRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.lang.java.ast.ASTNumericLiteral; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; public class AvoidUsingOctalValuesRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> STRICT_METHODS_DESCRIPTOR = booleanProperty("strict") .desc("Detect violations between 00 and 07") .defaultValue(false) .build(); public AvoidUsingOctalValuesRule() { super(ASTNumericLiteral.class); definePropertyDescriptor(STRICT_METHODS_DESCRIPTOR); } @Override public Object visit(ASTNumericLiteral node, Object data) { if (node.getBase() == 8) { if (getProperty(STRICT_METHODS_DESCRIPTOR) || !isBetweenZeroAnd7(node)) { addViolation(data, node); } } return null; } private boolean isBetweenZeroAnd7(ASTNumericLiteral node) { long value = node.getConstValue().longValue(); return 0 <= value && value <= 7; } }
1,326
30.595238
85
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/CheckSkipResultRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; public class CheckSkipResultRule extends AbstractJavaRulechainRule { private static final InvocationMatcher SKIP_METHOD = InvocationMatcher.parse("java.io.InputStream#skip(_*)"); public CheckSkipResultRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall call, Object data) { if (SKIP_METHOD.matchesCall(call) && !isResultUsed(call)) { addViolation(data, call); } return null; } private boolean isResultUsed(ASTMethodCall call) { return !(call.getParent() instanceof ASTExpressionStatement); } }
1,011
30.625
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/SingletonClassReturningNewInstanceRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.ast.NodeStream.DescendantNodeStream; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class SingletonClassReturningNewInstanceRule extends AbstractJavaRulechainRule { public SingletonClassReturningNewInstanceRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (node.isVoid() || !"getInstance".equals(node.getName())) { return data; } DescendantNodeStream<ASTReturnStatement> rsl = node.descendants(ASTReturnStatement.class); if (returnsNewInstances(rsl) || returnsLocalVariables(rsl)) { addViolation(data, node); } return data; } private boolean returnsNewInstances(NodeStream<ASTReturnStatement> returns) { return returns.descendants(ASTConstructorCall.class).nonEmpty(); } private boolean returnsLocalVariables(NodeStream<ASTReturnStatement> returns) { return returns.children(ASTVariableAccess.class).filter(JavaAstUtils::isReferenceToLocal).nonEmpty(); } }
1,629
36.906977
109
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/NonSerializableClassRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import static net.sourceforge.pmd.properties.PropertyFactory.stringProperty; import java.io.Externalizable; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTRecordDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.ASTType; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.ast.TypeNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.JTypeVar; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; // Note: This rule has been formerly known as "BeanMembersShouldSerialize". public class NonSerializableClassRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<String> PREFIX_DESCRIPTOR = stringProperty("prefix") .desc("deprecated! A variable prefix to skip, i.e., m_").defaultValue("").build(); private static final PropertyDescriptor<Boolean> CHECK_ABSTRACT_TYPES = booleanProperty("checkAbstractTypes") .desc("Enable to verify fields with abstract types like abstract classes, interfaces, generic types " + "or java.lang.Object. Enabling this might lead to more false positives, since the concrete " + "runtime type can actually be serializable.") .defaultValue(false) .build(); private static final String SERIAL_PERSISTENT_FIELDS_TYPE = "java.io.ObjectStreamField[]"; private static final String SERIAL_PERSISTENT_FIELDS_NAME = "serialPersistentFields"; private Map<ASTAnyTypeDeclaration, Set<String>> cachedPersistentFieldNames; public NonSerializableClassRule() { super(ASTVariableDeclaratorId.class, ASTClassOrInterfaceDeclaration.class, ASTEnumDeclaration.class, ASTRecordDeclaration.class); definePropertyDescriptor(PREFIX_DESCRIPTOR); definePropertyDescriptor(CHECK_ABSTRACT_TYPES); } @Override public void start(RuleContext ctx) { cachedPersistentFieldNames = new HashMap<>(); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { checkSerialPersistentFieldsField(node, data); return null; } @Override public Object visit(ASTEnumDeclaration node, Object data) { checkSerialPersistentFieldsField(node, data); return null; } @Override public Object visit(ASTRecordDeclaration node, Object data) { checkSerialPersistentFieldsField(node, data); return null; } private void checkSerialPersistentFieldsField(ASTAnyTypeDeclaration anyTypeDeclaration, Object data) { for (ASTFieldDeclaration field : anyTypeDeclaration.descendants(ASTFieldDeclaration.class)) { for (ASTVariableDeclaratorId varId : field) { if (SERIAL_PERSISTENT_FIELDS_NAME.equals(varId.getName())) { if (!TypeTestUtil.isA(SERIAL_PERSISTENT_FIELDS_TYPE, varId) || field.getVisibility() != AccessNode.Visibility.V_PRIVATE || !field.hasModifiers(JModifier.STATIC) || !field.hasModifiers(JModifier.FINAL)) { asCtx(data).addViolationWithMessage(varId, "The field ''{0}'' should be private static final with type ''{1}''.", varId.getName(), SERIAL_PERSISTENT_FIELDS_TYPE); } } } } } @Override public Object visit(ASTVariableDeclaratorId node, Object data) { ASTAnyTypeDeclaration typeDeclaration = node.ancestors(ASTAnyTypeDeclaration.class).first(); if (typeDeclaration == null // ignore non-serializable classes || !TypeTestUtil.isA(Serializable.class, typeDeclaration) // ignore Externalizable classes explicitly || TypeTestUtil.isA(Externalizable.class, typeDeclaration) // ignore manual serialization || hasManualSerializationMethod(typeDeclaration)) { return null; } if (isPersistentField(typeDeclaration, node) && isNotSerializable(node)) { asCtx(data).addViolation(node, node.getName(), typeDeclaration.getBinaryName(), node.getTypeMirror()); } return null; } private boolean hasManualSerializationMethod(ASTAnyTypeDeclaration node) { boolean hasWriteObject = false; boolean hasReadObject = false; boolean hasWriteReplace = false; boolean hasReadResolve = false; for (ASTBodyDeclaration decl : node.getDeclarations().toList()) { if (decl instanceof ASTMethodDeclaration) { ASTMethodDeclaration methodDeclaration = (ASTMethodDeclaration) decl; String methodName = methodDeclaration.getName(); int parameterCount = methodDeclaration.getFormalParameters().size(); ASTFormalParameter firstParameter = parameterCount > 0 ? methodDeclaration.getFormalParameters().get(0) : null; ASTType resultType = methodDeclaration.getResultTypeNode(); hasWriteObject |= "writeObject".equals(methodName) && parameterCount == 1 && TypeTestUtil.isA(ObjectOutputStream.class, firstParameter) && resultType.isVoid(); hasReadObject |= "readObject".equals(methodName) && parameterCount == 1 && TypeTestUtil.isA(ObjectInputStream.class, firstParameter) && resultType.isVoid(); hasWriteReplace |= "writeReplace".equals(methodName) && parameterCount == 0 && TypeTestUtil.isExactlyA(Object.class, resultType); hasReadResolve |= "readResolve".equals(methodName) && parameterCount == 0 && TypeTestUtil.isExactlyA(Object.class, resultType); } } return hasWriteObject && hasReadObject || hasWriteReplace && hasReadResolve; } private boolean isNotSerializable(TypeNode node) { JTypeMirror typeMirror = node.getTypeMirror(); JTypeDeclSymbol typeSymbol = typeMirror.getSymbol(); JClassSymbol classSymbol = null; if (typeSymbol instanceof JClassSymbol) { classSymbol = (JClassSymbol) typeSymbol; } boolean notSerializable = !TypeTestUtil.isA(Serializable.class, node) && !typeMirror.isPrimitive(); if (!getProperty(CHECK_ABSTRACT_TYPES) && classSymbol != null) { // exclude java.lang.Object, interfaces, abstract classes notSerializable &= !TypeTestUtil.isExactlyA(Object.class, node) && !classSymbol.isInterface() && !classSymbol.isAbstract(); } // exclude generic types if (!getProperty(CHECK_ABSTRACT_TYPES) && typeMirror instanceof JTypeVar) { notSerializable = false; } // exclude unresolved types in general if (typeSymbol != null && typeSymbol.isUnresolved()) { notSerializable = false; } return notSerializable; } private Set<String> determinePersistentFields(ASTAnyTypeDeclaration typeDeclaration) { if (cachedPersistentFieldNames.containsKey(typeDeclaration)) { return cachedPersistentFieldNames.get(typeDeclaration); } ASTVariableDeclarator persistentFieldsDecl = null; for (ASTFieldDeclaration field : typeDeclaration.descendants(ASTFieldDeclaration.class)) { if (field.getVisibility() == AccessNode.Visibility.V_PRIVATE && field.hasModifiers(JModifier.STATIC, JModifier.FINAL)) { for (ASTVariableDeclaratorId varId : field) { if (TypeTestUtil.isA(SERIAL_PERSISTENT_FIELDS_TYPE, varId) && SERIAL_PERSISTENT_FIELDS_NAME.equals(varId.getName())) { persistentFieldsDecl = varId.ancestors(ASTVariableDeclarator.class).first(); } } } } Set<String> fields = null; if (persistentFieldsDecl != null) { fields = persistentFieldsDecl.descendants(ASTStringLiteral.class).toStream() .map(ASTStringLiteral::getConstValue) .collect(Collectors.toSet()); if (fields.isEmpty()) { // field initializer might be a reference to a constant ASTExpression initializer = persistentFieldsDecl.getInitializer(); if (initializer instanceof ASTVariableAccess) { ASTVariableAccess variableAccess = (ASTVariableAccess) initializer; ASTVariableDeclaratorId reference = variableAccess.getReferencedSym().tryGetNode(); fields = reference.getParent().descendants(ASTStringLiteral.class).toStream() .map(ASTStringLiteral::getConstValue) .collect(Collectors.toSet()); } } } cachedPersistentFieldNames.put(typeDeclaration, fields); return fields; } private boolean isPersistentField(ASTAnyTypeDeclaration typeDeclaration, ASTVariableDeclaratorId node) { Set<String> persistentFields = determinePersistentFields(typeDeclaration); if (node.isField() && (persistentFields == null || persistentFields.contains(node.getName()))) { ASTFieldDeclaration field = node.ancestors(ASTFieldDeclaration.class).first(); return field != null && !field.hasModifiers(JModifier.STATIC) && !field.hasModifiers(JModifier.TRANSIENT); } return false; } }
11,235
47.431034
137
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/BeanMembersShouldSerializeRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; /** * @deprecated Please use {@link NonSerializableClassRule} instead. */ @Deprecated public class BeanMembersShouldSerializeRule extends NonSerializableClassRule { }
313
23.153846
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/CloneMethodMustImplementCloneableRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * The method clone() should only be implemented if the class implements the * Cloneable interface with the exception of a final method that only throws * CloneNotSupportedException. This version uses PMD's type resolution * facilities, and can detect if the class implements or extends a Cloneable * class * * @author acaplan */ public class CloneMethodMustImplementCloneableRule extends AbstractJavaRulechainRule { public CloneMethodMustImplementCloneableRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(final ASTMethodDeclaration node, final Object data) { if (!JavaAstUtils.isCloneMethod(node)) { return data; } ASTBlock body = node.getBody(); if (body != null && justThrowsCloneNotSupported(body)) { return data; } ASTAnyTypeDeclaration type = node.getEnclosingType(); if (type instanceof ASTClassOrInterfaceDeclaration && !TypeTestUtil.isA(Cloneable.class, type)) { // Nothing can save us now addViolation(data, node); } return data; } private static boolean justThrowsCloneNotSupported(ASTBlock body) { return body.size() == 1 && body.getChild(0) .asStream() .filterIs(ASTThrowStatement.class) .map(ASTThrowStatement::getExpr) .filter(it -> TypeTestUtil.isA(CloneNotSupportedException.class, it)) .nonEmpty(); } }
2,186
35.45
105
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/AvoidBranchingStatementAsLastInLoopRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement; import net.sourceforge.pmd.lang.java.ast.ASTContinueStatement; import net.sourceforge.pmd.lang.java.ast.ASTDoStatement; import net.sourceforge.pmd.lang.java.ast.ASTFinallyClause; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class AvoidBranchingStatementAsLastInLoopRule extends AbstractJavaRulechainRule { public static final String CHECK_FOR = "for"; public static final String CHECK_DO = "do"; public static final String CHECK_WHILE = "while"; private static final Map<String, String> LOOP_TYPES_MAPPINGS; private static final List<String> DEFAULTS = Arrays.asList(CHECK_FOR, CHECK_DO, CHECK_WHILE); static { Map<String, String> mappings = new HashMap<>(); mappings.put(CHECK_FOR, CHECK_FOR); mappings.put(CHECK_DO, CHECK_DO); mappings.put(CHECK_WHILE, CHECK_WHILE); LOOP_TYPES_MAPPINGS = Collections.unmodifiableMap(mappings); } // TODO I don't think we need this configurability. // I think we should tone that down to just be able to ignore some type of statement, // but I can't see a use case to e.g. report only breaks in 'for' loops but not in 'while'. public static final PropertyDescriptor<List<String>> CHECK_BREAK_LOOP_TYPES = propertyFor("break"); public static final PropertyDescriptor<List<String>> CHECK_CONTINUE_LOOP_TYPES = propertyFor("continue"); public static final PropertyDescriptor<List<String>> CHECK_RETURN_LOOP_TYPES = propertyFor("return"); public AvoidBranchingStatementAsLastInLoopRule() { super(ASTBreakStatement.class, ASTContinueStatement.class, ASTReturnStatement.class); definePropertyDescriptor(CHECK_BREAK_LOOP_TYPES); definePropertyDescriptor(CHECK_CONTINUE_LOOP_TYPES); definePropertyDescriptor(CHECK_RETURN_LOOP_TYPES); } @Override public Object visit(ASTBreakStatement node, Object data) { // skip breaks, that are within a switch statement if (node.ancestors().get(1) instanceof ASTSwitchStatement) { return data; } return check(CHECK_BREAK_LOOP_TYPES, node, data); } protected Object check(PropertyDescriptor<List<String>> property, Node node, Object data) { Node parent = node.getParent(); if (parent instanceof ASTBlock) { parent = parent.getParent(); 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); } } if (parent instanceof ASTForStatement || parent instanceof ASTForeachStatement) { if (hasPropertyValue(property, CHECK_FOR)) { super.addViolation(data, node); } } else if (parent instanceof ASTWhileStatement) { if (hasPropertyValue(property, CHECK_WHILE)) { super.addViolation(data, node); } } else if (parent instanceof ASTDoStatement) { if (hasPropertyValue(property, CHECK_DO)) { super.addViolation(data, node); } } return data; } protected boolean hasPropertyValue(PropertyDescriptor<List<String>> property, String value) { return getProperty(property).contains(value); } @Override public Object visit(ASTContinueStatement node, Object data) { return check(CHECK_CONTINUE_LOOP_TYPES, node, data); } @Override public Object visit(ASTReturnStatement node, Object data) { return check(CHECK_RETURN_LOOP_TYPES, node, data); } @Override public String dysfunctionReason() { return checksNothing() ? "All loop types are ignored" : null; } private static PropertyDescriptor<List<String>> propertyFor(String stmtName) { return PropertyFactory.enumListProperty("check" + StringUtils.capitalize(stmtName) + "LoopTypes", LOOP_TYPES_MAPPINGS) .desc("List of loop types in which " + stmtName + " statements will be checked") .defaultValue(DEFAULTS) .build(); } public boolean checksNothing() { return getProperty(CHECK_BREAK_LOOP_TYPES).isEmpty() && getProperty(CHECK_CONTINUE_LOOP_TYPES).isEmpty() && getProperty(CHECK_RETURN_LOOP_TYPES).isEmpty(); } }
5,320
37.839416
126
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/AssignmentToNonFinalStaticRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.AccessType; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; /** * @author Eric Olander * @since Created on October 24, 2004, 8:56 AM */ public class AssignmentToNonFinalStaticRule extends AbstractJavaRulechainRule { public AssignmentToNonFinalStaticRule() { super(ASTFieldAccess.class, ASTVariableAccess.class); } @Override public Object visit(ASTVariableAccess node, Object data) { checkAccess(node, data); return null; } @Override public Object visit(ASTFieldAccess node, Object data) { checkAccess(node, data); return null; } private void checkAccess(ASTNamedReferenceExpr node, Object data) { if (isInsideConstructor(node) && node.getAccessType() == AccessType.WRITE) { @Nullable JVariableSymbol symbol = node.getReferencedSym(); if (symbol != null && symbol.isField()) { JFieldSymbol field = (JFieldSymbol) symbol; if (field.isStatic() && !field.isFinal()) { addViolation(data, node, field.getSimpleName()); } } } } private boolean isInsideConstructor(ASTNamedReferenceExpr node) { return node.ancestors(ASTConstructorDeclaration.class).nonEmpty(); } }
1,969
33.561404
84
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/AssignmentInOperandRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertySource; /** * */ public class AssignmentInOperandRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> ALLOW_IF_DESCRIPTOR = booleanProperty("allowIf") .desc("Allow assignment within the conditional expression of an if statement") .defaultValue(false).build(); private static final PropertyDescriptor<Boolean> ALLOW_FOR_DESCRIPTOR = booleanProperty("allowFor") .desc("Allow assignment within the conditional expression of a for statement") .defaultValue(false).build(); private static final PropertyDescriptor<Boolean> ALLOW_WHILE_DESCRIPTOR = booleanProperty("allowWhile") .desc("Allow assignment within the conditional expression of a while statement") .defaultValue(false).build(); private static final PropertyDescriptor<Boolean> ALLOW_INCREMENT_DECREMENT_DESCRIPTOR = booleanProperty("allowIncrementDecrement") .desc("Allow increment or decrement operators within the conditional expression of an if, for, or while statement") .defaultValue(false).build(); public AssignmentInOperandRule() { super(ASTAssignmentExpression.class, ASTUnaryExpression.class); definePropertyDescriptor(ALLOW_IF_DESCRIPTOR); definePropertyDescriptor(ALLOW_FOR_DESCRIPTOR); definePropertyDescriptor(ALLOW_WHILE_DESCRIPTOR); definePropertyDescriptor(ALLOW_INCREMENT_DECREMENT_DESCRIPTOR); } @Override public Object visit(ASTAssignmentExpression node, Object data) { checkAssignment(node, (RuleContext) data); return null; } @Override public Object visit(ASTUnaryExpression node, Object data) { if (!getProperty(ALLOW_INCREMENT_DECREMENT_DESCRIPTOR) && !node.getOperator().isPure()) { checkAssignment(node, (RuleContext) data); } return null; } private void checkAssignment(ASTExpression impureExpr, RuleContext ctx) { ASTExpression toplevel = JavaAstUtils.getTopLevelExpr(impureExpr); JavaNode parent = toplevel.getParent(); if (parent instanceof ASTExpressionStatement) { // that's ok return; } if (parent instanceof ASTIfStatement && !getProperty(ALLOW_IF_DESCRIPTOR) || parent instanceof ASTWhileStatement && !getProperty(ALLOW_WHILE_DESCRIPTOR) || parent instanceof ASTForStatement && ((ASTForStatement) parent).getCondition() == toplevel && !getProperty(ALLOW_FOR_DESCRIPTOR)) { addViolation(ctx, impureExpr); } } public boolean allowsAllAssignments() { return getProperty(ALLOW_IF_DESCRIPTOR) && getProperty(ALLOW_FOR_DESCRIPTOR) && getProperty(ALLOW_WHILE_DESCRIPTOR) && getProperty(ALLOW_INCREMENT_DECREMENT_DESCRIPTOR); } /** * @see PropertySource#dysfunctionReason() */ @Override public String dysfunctionReason() { return allowsAllAssignments() ? "All assignment types allowed, no checks performed" : null; } }
4,119
40.616162
146
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/JUnitSpellingRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil; public class JUnitSpellingRule extends AbstractJavaRulechainRule { public JUnitSpellingRule() { super(ASTClassOrInterfaceDeclaration.class); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (TestFrameworksUtil.isJUnit3Class(node)) { node.getDeclarations(ASTMethodDeclaration.class) .filter(this::isViolation) .forEach(it -> addViolation(data, it)); } return null; } private boolean isViolation(ASTMethodDeclaration method) { if (method.getArity() != 0) { return false; } String name = method.getName(); return !"setUp".equals(name) && "setup".equalsIgnoreCase(name) || !"tearDown".equals(name) && "teardown".equalsIgnoreCase(name); } }
1,260
31.333333
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/ImplicitSwitchFallThroughRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.ast.GenericToken; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchFallthroughBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass; import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.DataflowResult; import net.sourceforge.pmd.util.OptionalBool; public class ImplicitSwitchFallThroughRule extends AbstractJavaRulechainRule { //todo should consider switch exprs private static final Pattern IGNORED_COMMENT = Pattern.compile("/[/*].*\\bfalls?[ -]?thr(ough|u)\\b.*", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); public ImplicitSwitchFallThroughRule() { super(ASTSwitchStatement.class); } @Override public Object visit(ASTSwitchStatement node, Object data) { DataflowResult dataflow = DataflowPass.getDataflowResult(node.getRoot()); for (ASTSwitchBranch branch : node.getBranches()) { if (branch instanceof ASTSwitchFallthroughBranch && branch != node.getLastChild()) { ASTSwitchFallthroughBranch fallthrough = (ASTSwitchFallthroughBranch) branch; OptionalBool bool = dataflow.switchBranchFallsThrough(branch); if (bool != OptionalBool.NO && fallthrough.getStatements().nonEmpty() && !nextBranchHasComment(branch)) { addViolation(data, branch.getNextBranch().getLabel()); } } else { return null; } } return null; } boolean nextBranchHasComment(ASTSwitchBranch branch) { JavaNode nextBranch = branch.getNextBranch(); if (nextBranch == null) { return false; } for (JavaccToken special : GenericToken.previousSpecials(nextBranch.getFirstToken())) { if (JavaAstUtils.isComment(special) && IGNORED_COMMENT.matcher(special.getImageCs()).find()) { return true; } } return false; } }
2,620
38.119403
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/SingleMethodSingletonRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; /** * Returns Checks if the singleton rule is used properly. */ public class SingleMethodSingletonRule extends AbstractJavaRulechainRule { public SingleMethodSingletonRule() { super(ASTClassOrInterfaceDeclaration.class); } /** * Checks for getInstance method usage in the same class. * @param node of ASTCLass * @param data of Object * @return Object */ @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { int count = node.descendants(ASTMethodDeclaration.class) .filter(m -> "getInstance".equals(m.getName())) .count(); if (count > 1) { addViolation(data, node); } return data; } }
1,094
27.815789
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/UselessOperationOnImmutableRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import java.math.BigDecimal; import java.math.BigInteger; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * An operation on an Immutable object (String, BigDecimal or BigInteger) won't * change the object itself. The result of the operation is a new object. * Therefore, ignoring the operation result is an error. */ public class UselessOperationOnImmutableRule extends AbstractJavaRulechainRule { public UselessOperationOnImmutableRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall node, Object data) { ASTExpression qualifier = node.getQualifier(); if (node.getParent() instanceof ASTExpressionStatement && qualifier != null) { // these types are immutable, so any method of those whose // result is ignored is a violation if (TypeTestUtil.isA(String.class, qualifier)) { if (!"getChars".equals(node.getMethodName())) { addViolation(data, node); } } else if (TypeTestUtil.isA(BigDecimal.class, qualifier) || TypeTestUtil.isA(BigInteger.class, qualifier)) { addViolation(data, node); } } return null; } }
1,656
34.255319
86
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/BrokenNullCheckRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.BinaryOp; import net.sourceforge.pmd.lang.java.ast.QualifiableExpression; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.StablePathMatcher; public class BrokenNullCheckRule extends AbstractJavaRulechainRule { public BrokenNullCheckRule() { super(ASTInfixExpression.class); } @Override public Object visit(ASTInfixExpression node, Object data) { checkBrokenNullCheck(node, (RuleContext) data); return data; } private void checkBrokenNullCheck(ASTInfixExpression enclosingConditional, RuleContext ctx) { ASTExpression left = enclosingConditional.getLeftOperand(); if (!(left instanceof ASTInfixExpression)) { return; } BinaryOp op = ((ASTInfixExpression) left).getOperator(); if (op != BinaryOp.EQ && op != BinaryOp.NE) { return; } else if (op == BinaryOp.NE && enclosingConditional.getOperator() == BinaryOp.CONDITIONAL_AND || op == BinaryOp.EQ && enclosingConditional.getOperator() == BinaryOp.CONDITIONAL_OR) { return; // not problematic } ASTNullLiteral nullLit = left.children(ASTNullLiteral.class).first(); if (nullLit == null) { return; } ASTExpression otherChild = JavaAstUtils.getOtherOperandIfInInfixExpr(nullLit); StablePathMatcher pathToNullVar = StablePathMatcher.matching(otherChild); if (pathToNullVar == null) { // cannot be matched, because it's not stable return; } NodeStream<ASTExpression> exprsToCheck = enclosingConditional.getRightOperand() .descendantsOrSelf() .filterIs(ASTExpression.class); for (ASTExpression subexpr : exprsToCheck) { NpeReason npeReason = willNpeWithReason(subexpr, pathToNullVar); if (npeReason != null) { addViolationWithMessage(ctx, subexpr, npeReason.formatMessage); } } } private static NpeReason willNpeWithReason(ASTExpression e, StablePathMatcher pathToNullVar) { if (e instanceof QualifiableExpression) { ASTExpression qualifier = ((QualifiableExpression) e).getQualifier(); if (pathToNullVar.matches(qualifier)) { return NpeReason.DEREFERENCE; } } if (e.getParent() instanceof ASTInfixExpression) { ASTInfixExpression infix = (ASTInfixExpression) e.getParent(); if (pathToNullVar.matches(e) && operatorUnboxesOperand(infix)) { return NpeReason.UNBOXING; } } return null; } private static boolean operatorUnboxesOperand(ASTInfixExpression infix) { BinaryOp operator = infix.getOperator(); if (operator == BinaryOp.INSTANCEOF) { return false; } boolean leftIsPrimitive = infix.getLeftOperand().getTypeMirror().isPrimitive(); boolean rightIsPrimitive = infix.getRightOperand().getTypeMirror().isPrimitive(); if (leftIsPrimitive != rightIsPrimitive) { return true; } else { assert !leftIsPrimitive || !rightIsPrimitive : "We know at least one of the operands is null"; // So both are reference types // With these ops, in this case no unboxing takes place return operator != BinaryOp.NE && operator != BinaryOp.EQ; } } enum NpeReason { DEREFERENCE("Dereferencing the qualifier of this expression will throw a NullPointerException"), UNBOXING("Unboxing this operand will throw a NullPointerException"); private final String formatMessage; NpeReason(String formatMessage) { this.formatMessage = formatMessage; } } }
4,485
37.34188
106
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/ConstructorCallsOverridableMethodRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.lang.reflect.Modifier; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.NonNull; import org.pcollections.PVector; import org.pcollections.TreePVector; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; /** * Searches through all methods and constructors called from constructors. It * marks as dangerous any call to overridable methods from non-private * constructors. It marks as dangerous any calls to dangerous private * constructors from non-private constructors. * * @author CL Gilbert (dnoyeb@users.sourceforge.net) * * TODO match parameter types. Aggressively strips off any package * names. Normal compares the names as is. TODO What about interface * declarations which can have internal classes */ public final class ConstructorCallsOverridableMethodRule extends AbstractJavaRulechainRule { private static final String MESSAGE = "Overridable method called during object construction: {0} "; private static final String MESSAGE_TRANSITIVE = "This method may call an overridable method during object construction: {0} (call stack: [{1}])"; // Maps methods to the method call stack that makes them unsafe // Safe methods are mapped to an empty stack // The method call stack (value of the map) is used for better messages private final Map<JMethodSymbol, Deque<JMethodSymbol>> safeMethods = new HashMap<>(); private static final Deque<JMethodSymbol> EMPTY_STACK = new LinkedList<>(); private static final Set<String> MAKE_FIELD_FINAL_CLASS_ANNOT = setOf( "lombok.Value" ); public ConstructorCallsOverridableMethodRule() { super(ASTConstructorDeclaration.class); } @Override public void start(RuleContext ctx) { super.start(ctx); safeMethods.clear(); } @Override public Object visit(ASTConstructorDeclaration node, Object data) { if (node.getEnclosingType().isFinal() || JavaAstUtils.hasAnyAnnotation(node.getEnclosingType(), MAKE_FIELD_FINAL_CLASS_ANNOT)) { return null; // then cannot be overridden } for (ASTMethodCall call : node.getBody().descendants(ASTMethodCall.class)) { Deque<JMethodSymbol> unsafetyReason = getUnsafetyReason(call, TreePVector.empty()); if (!unsafetyReason.isEmpty()) { JMethodSig overload = call.getOverloadSelectionInfo().getMethodType(); JMethodSig unsafeMethod = call.getTypeSystem().sigOf(unsafetyReason.getLast()); String message = unsafeMethod.equals(overload) ? MESSAGE : MESSAGE_TRANSITIVE; String lastMethod = PrettyPrintingUtil.prettyPrintOverload(unsafetyReason.getLast()); String stack = unsafetyReason.stream().map(PrettyPrintingUtil::prettyPrintOverload).collect(Collectors.joining(", ")); asCtx(data).addViolationWithMessage(call, message, lastMethod, stack); } } return null; } @NonNull private Deque<JMethodSymbol> getUnsafetyReason(ASTMethodCall call, PVector<ASTMethodDeclaration> recursionGuard) { if (!isCallOnThisInstance(call)) { return EMPTY_STACK; } OverloadSelectionResult overload = call.getOverloadSelectionInfo(); if (overload.isFailed()) { return EMPTY_STACK; } JMethodSymbol method = (JMethodSymbol) overload.getMethodType().getSymbol(); if (isOverridable(method)) { Deque<JMethodSymbol> stack = new LinkedList<>(); stack.addFirst(method); // the method itself return stack; } else { return getUnsafetyReason(method, recursionGuard); } } @NonNull private Deque<JMethodSymbol> getUnsafetyReason(JMethodSymbol method, PVector<ASTMethodDeclaration> recursionGuard) { if (method.isStatic()) { return EMPTY_STACK; // no access to this instance anyway } // we need to prove that all calls on this instance are safe ASTMethodDeclaration declaration = method.tryGetNode(); if (declaration == null) { return EMPTY_STACK; // no idea } else if (recursionGuard.contains(declaration)) { // being visited, assume body is safe return EMPTY_STACK; } // note we can't use computeIfAbsent because of comodification if (safeMethods.containsKey(method)) { return safeMethods.get(method); } PVector<ASTMethodDeclaration> deeperRecursion = recursionGuard.plus(declaration); for (ASTMethodCall call : NodeStream.of(declaration.getBody()) .descendants(ASTMethodCall.class) .filter(ConstructorCallsOverridableMethodRule::isCallOnThisInstance)) { Deque<JMethodSymbol> unsafetyReason = getUnsafetyReason(call, deeperRecursion); if (!unsafetyReason.isEmpty()) { // this method call is unsafe for some reason, // body is unsafe for the same reason safeMethods.putIfAbsent(method, new LinkedList<>(unsafetyReason)); safeMethods.get(method).addFirst(method); return safeMethods.get(method); } } // body is safe safeMethods.remove(method); return EMPTY_STACK; } private static boolean isCallOnThisInstance(ASTMethodCall call) { ASTExpression qualifier = call.getQualifier(); return qualifier == null || JavaAstUtils.isUnqualifiedThis(qualifier); } private static boolean isOverridable(JExecutableSymbol method) { // (assuming enclosing type is not final) // neither final nor private nor static return ((Modifier.FINAL | Modifier.PRIVATE | Modifier.STATIC) & method.getModifiers()) == 0; } }
7,008
40.97006
150
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/TestClassWithoutTestCasesRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil.isJUnit3Class; import static net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil.isJUnit5NestedClass; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class TestClassWithoutTestCasesRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Pattern> TEST_CLASS_PATTERN = PropertyFactory.regexProperty("testClassPattern") .defaultValue("^(?:.*\\.)?Test[^\\.]*$|^(?:.*\\.)?.*Tests?$|^(?:.*\\.)?.*TestCase$") .desc("Test class name pattern to identify test classes by their fully qualified name. " + "An empty pattern disables test class detection by name. Since PMD 6.51.0.") .build(); public TestClassWithoutTestCasesRule() { super(ASTClassOrInterfaceDeclaration.class); definePropertyDescriptor(TEST_CLASS_PATTERN); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (isJUnit3Class(node) || isJUnit5NestedClass(node) || isTestClassByPattern(node)) { boolean hasTests = node.getDeclarations(ASTMethodDeclaration.class) .any(TestFrameworksUtil::isTestMethod); boolean hasNestedTestClasses = node.getDeclarations(ASTAnyTypeDeclaration.class) .any(TestFrameworksUtil::isJUnit5NestedClass); if (!hasTests && !hasNestedTestClasses) { asCtx(data).addViolation(node, node.getSimpleName()); } } return null; } private boolean isTestClassByPattern(ASTClassOrInterfaceDeclaration node) { Pattern testClassPattern = getProperty(TEST_CLASS_PATTERN); if (testClassPattern.pattern().isEmpty()) { // detection by pattern is disabled return false; } if (node.isAbstract() || node.isInterface()) { return false; } String fullName = node.getCanonicalName(); return fullName != null && testClassPattern.matcher(fullName).find(); } }
2,697
41.15625
123
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/OverrideBothEqualsAndHashcodeRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTAnonymousClassDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTRecordDeclaration; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; public class OverrideBothEqualsAndHashcodeRule extends AbstractJavaRulechainRule { public OverrideBothEqualsAndHashcodeRule() { super(ASTClassOrInterfaceDeclaration.class, ASTRecordDeclaration.class, ASTAnonymousClassDeclaration.class); } private void visitTypeDecl(ASTAnyTypeDeclaration node, Object data) { if (TypeTestUtil.isA(Comparable.class, node)) { return; } ASTMethodDeclaration equalsMethod = null; ASTMethodDeclaration hashCodeMethod = null; for (ASTMethodDeclaration m : node.getDeclarations(ASTMethodDeclaration.class)) { if (JavaAstUtils.isEqualsMethod(m)) { equalsMethod = m; if (hashCodeMethod != null) { break; // shortcut } } else if (JavaAstUtils.isHashCodeMethod(m)) { hashCodeMethod = m; if (equalsMethod != null) { break; // shortcut } } } if (hashCodeMethod != null ^ equalsMethod != null) { ASTMethodDeclaration nonNullNode = equalsMethod == null ? hashCodeMethod : equalsMethod; asCtx(data).addViolation(nonNullNode); } } @Override public Object visit(ASTAnonymousClassDeclaration node, Object data) { visitTypeDecl(node, data); return null; } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface()) { return null; } visitTypeDecl(node, data); return null; } @Override public Object visit(ASTRecordDeclaration node, Object data) { visitTypeDecl(node, data); return null; } }
2,478
33.430556
89
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/SuspiciousOctalEscapeRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class SuspiciousOctalEscapeRule extends AbstractJavaRulechainRule { public SuspiciousOctalEscapeRule() { super(ASTStringLiteral.class); } @Override public Object visit(ASTStringLiteral node, Object data) { String image = node.getImage(); // trim quotes String s = image.substring(1, image.length() - 1); // process escape sequences int offset = 0; for (int slash = s.indexOf('\\', offset); slash != -1 && slash < s.length() - 1; slash = s.indexOf('\\', offset)) { String escapeSequence = s.substring(slash + 1); char first = escapeSequence.charAt(0); offset = slash + 1; // next offset - after slash if (isOctal(first)) { if (escapeSequence.length() > 1) { char second = escapeSequence.charAt(1); if (isOctal(second)) { if (escapeSequence.length() > 2) { char third = escapeSequence.charAt(2); if (isOctal(third)) { // this is either a three digit octal escape // or a two-digit // octal escape followed by an octal digit. // the value of // the first digit in the sequence // determines which is the // case if (first != '0' && first != '1' && first != '2' && first != '3') { // VIOLATION: it's a two-digit octal // escape followed by // an octal digit -- legal but very // confusing! addViolation(data, node, "\\" + first + second + " + " + third); } else { // if there is a 4th decimal digit, it // could never be part of // the escape sequence, which is // confusing if (escapeSequence.length() > 3) { char fourth = escapeSequence.charAt(3); if (isDecimal(fourth)) { addViolation(data, node, "\\" + first + second + third + " + " + fourth); } } } } else if (isDecimal(third)) { // this is a two-digit octal escape followed // by a decimal digit // legal but very confusing addViolation(data, node, "\\" + first + second + " + " + third); } } } else if (isDecimal(second)) { // this is a one-digit octal escape followed by a // decimal digit // legal but very confusing addViolation(data, node, "\\" + first + " + " + second); } } } else if (first == '\\') { offset++; } } return data; } private boolean isOctal(char c) { return c >= '0' && c <= '7'; } private boolean isDecimal(char c) { return c >= '0' && c <= '9'; } }
4,018
42.215054
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/IdempotentOperationsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.AssignmentOp; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class IdempotentOperationsRule extends AbstractJavaRulechainRule { public IdempotentOperationsRule() { super(ASTAssignmentExpression.class); } @Override public Object visit(ASTAssignmentExpression node, Object data) { if (node.getOperator() == AssignmentOp.ASSIGN && JavaAstUtils.isReferenceToSameVar(node.getLeftOperand(), node.getRightOperand())) { addViolation(data, node); } return null; } }
881
31.666667
98
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/JUnitStaticSuiteRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil.isJUnit3Class; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class JUnitStaticSuiteRule extends AbstractJavaRulechainRule { public JUnitStaticSuiteRule() { super(ASTClassOrInterfaceDeclaration.class); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (isJUnit3Class(node)) { ASTMethodDeclaration suiteMethod = node.getDeclarations(ASTMethodDeclaration.class) .filter(it -> "suite".equals(it.getName()) && it.getArity() == 0) .first(); if (suiteMethod != null && (suiteMethod.getVisibility() != Visibility.V_PUBLIC || !suiteMethod.isStatic())) { addViolation(data, suiteMethod); } } return null; } }
1,314
36.571429
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/AvoidDuplicateLiteralsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import static net.sourceforge.pmd.properties.PropertyFactory.intProperty; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; public class AvoidDuplicateLiteralsRule extends AbstractJavaRulechainRule { public static final PropertyDescriptor<Integer> THRESHOLD_DESCRIPTOR = intProperty("maxDuplicateLiterals") .desc("Max duplicate literals") .require(positive()).defaultValue(4).build(); public static final PropertyDescriptor<Integer> MINIMUM_LENGTH_DESCRIPTOR = intProperty("minimumLength").desc("Minimum string length to check").require(positive()).defaultValue(3).build(); public static final PropertyDescriptor<Boolean> SKIP_ANNOTATIONS_DESCRIPTOR = booleanProperty("skipAnnotations") .desc("Skip literals within annotations").defaultValue(false).build(); private static final PropertyDescriptor<List<String>> EXCEPTION_LIST_DESCRIPTOR = stringListProperty("exceptionList") .desc("List of literals to ignore. " + "A literal is ignored if its image can be found in this list. " + "Components of this list should not be surrounded by double quotes.") .defaultValue(Collections.emptyList()) .delim(',') .build(); private Map<String, SortedSet<ASTStringLiteral>> literals = new HashMap<>(); private Set<String> exceptions = new HashSet<>(); private int minLength; public AvoidDuplicateLiteralsRule() { super(ASTStringLiteral.class); definePropertyDescriptor(THRESHOLD_DESCRIPTOR); definePropertyDescriptor(MINIMUM_LENGTH_DESCRIPTOR); definePropertyDescriptor(SKIP_ANNOTATIONS_DESCRIPTOR); definePropertyDescriptor(EXCEPTION_LIST_DESCRIPTOR); } @Override public void start(RuleContext ctx) { super.start(ctx); literals.clear(); if (getProperty(EXCEPTION_LIST_DESCRIPTOR) != null) { exceptions = new HashSet<>(getProperty(EXCEPTION_LIST_DESCRIPTOR)); } minLength = 2 + getProperty(MINIMUM_LENGTH_DESCRIPTOR); } @Override public void end(RuleContext ctx) { processResults(ctx); super.end(ctx); } private void processResults(Object data) { int threshold = getProperty(THRESHOLD_DESCRIPTOR); for (Map.Entry<String, SortedSet<ASTStringLiteral>> entry : literals.entrySet()) { SortedSet<ASTStringLiteral> occurrences = entry.getValue(); if (occurrences.size() >= threshold) { ASTStringLiteral first = occurrences.first(); Object[] args = { first.toPrintableString(), occurrences.size(), first.getBeginLine(), }; addViolation(data, first, args); } } } @Override public Object visit(ASTStringLiteral node, Object data) { String image = node.getImage(); // just catching strings of 'minLength' chars or more (including the // enclosing quotes) if (image.length() < minLength) { return data; } // skip any exceptions if (exceptions.contains(image.substring(1, image.length() - 1))) { return data; } // Skip literals in annotations if (getProperty(SKIP_ANNOTATIONS_DESCRIPTOR) && node.ancestors(ASTAnnotation.class).nonEmpty()) { return data; } // This is a rulechain rule - the nodes might be visited out of order. Therefore sort the occurrences. SortedSet<ASTStringLiteral> occurrences = literals.computeIfAbsent(image, key -> new TreeSet<>(Node.COORDS_COMPARATOR)); occurrences.add(node); return data; } }
4,750
36.706349
192
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/CloseResourceRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTFinallyClause; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTTryStatement; import net.sourceforge.pmd.lang.java.ast.ASTType; import net.sourceforge.pmd.lang.java.ast.ASTTypeExpression; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.BinaryOp; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.TypeNode; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; 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.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Makes sure you close your database connections. It does this by looking for * code patterned like this: * * <pre> * Connection c = X; * try { * // do stuff, and maybe catch something * } finally { * c.close(); * } * </pre> * * @author original author unknown * @author Contribution from Pierre Mathien */ public class CloseResourceRule extends AbstractJavaRule { private static final String WRAPPING_TRY_WITH_RES_VAR_MESSAGE = "it is recommended to wrap resource ''{0}'' in try-with-resource declaration directly"; private static final String REASSIGN_BEFORE_CLOSED_MESSAGE = "''{0}'' is reassigned, but the original instance is not closed"; private static final String CLOSE_IN_FINALLY_BLOCK_MESSAGE = "''{0}'' is not closed within a finally block, thus might not be closed at all in case of exceptions"; private static final PropertyDescriptor<List<String>> CLOSE_TARGETS_DESCRIPTOR = stringListProperty("closeTargets") .desc("Methods which may close this resource") .emptyDefaultValue() .delim(',').build(); private static final PropertyDescriptor<List<String>> TYPES_DESCRIPTOR = stringListProperty("types") .desc("Affected types") .defaultValues("java.lang.AutoCloseable", "java.sql.Connection", "java.sql.Statement", "java.sql.ResultSet") .delim(',').build(); private static final PropertyDescriptor<Boolean> USE_CLOSE_AS_DEFAULT_TARGET = booleanProperty("closeAsDefaultTarget") .desc("Consider 'close' as a target by default").defaultValue(true).build(); private static final PropertyDescriptor<List<String>> ALLOWED_RESOURCE_TYPES = stringListProperty("allowedResourceTypes") .desc("Exact class names that do not need to be closed") .defaultValues("java.io.ByteArrayOutputStream", "java.io.ByteArrayInputStream", "java.io.StringWriter", "java.io.CharArrayWriter", "java.util.stream.Stream", "java.util.stream.IntStream", "java.util.stream.LongStream", "java.util.stream.DoubleStream") .build(); private static final PropertyDescriptor<Boolean> DETECT_CLOSE_NOT_IN_FINALLY = booleanProperty("closeNotInFinally") .desc("Detect if 'close' (or other closeTargets) is called outside of a finally-block").defaultValue(false).build(); private static final InvocationMatcher OBJECTS_NON_NULL = InvocationMatcher.parse("java.util.Objects#nonNull(_)"); private final Set<String> types = new HashSet<>(); private final Set<String> simpleTypes = new HashSet<>(); private final Set<String> closeTargets = new HashSet<>(); // keeps track of already reported violations to avoid duplicated violations for the same variable private final Set<String> reportedVarNames = new HashSet<>(); public CloseResourceRule() { definePropertyDescriptor(CLOSE_TARGETS_DESCRIPTOR); definePropertyDescriptor(TYPES_DESCRIPTOR); definePropertyDescriptor(USE_CLOSE_AS_DEFAULT_TARGET); definePropertyDescriptor(ALLOWED_RESOURCE_TYPES); definePropertyDescriptor(DETECT_CLOSE_NOT_IN_FINALLY); } @Override public void start(RuleContext ctx) { closeTargets.clear(); simpleTypes.clear(); types.clear(); if (getProperty(CLOSE_TARGETS_DESCRIPTOR) != null) { closeTargets.addAll(getProperty(CLOSE_TARGETS_DESCRIPTOR)); } if (getProperty(USE_CLOSE_AS_DEFAULT_TARGET)) { closeTargets.add("close"); } if (getProperty(TYPES_DESCRIPTOR) != null) { types.addAll(getProperty(TYPES_DESCRIPTOR)); for (String type : getProperty(TYPES_DESCRIPTOR)) { simpleTypes.add(toSimpleType(type)); } } } private static String toSimpleType(String fullyQualifiedClassName) { int lastIndexOf = fullyQualifiedClassName.lastIndexOf('.'); if (lastIndexOf > -1) { return fullyQualifiedClassName.substring(lastIndexOf + 1); } else { return fullyQualifiedClassName; } } @Override public Object visit(ASTConstructorDeclaration node, Object data) { checkForResources(node, data); return super.visit(node, data); } @Override public Object visit(ASTMethodDeclaration node, Object data) { checkForResources(node, data); return super.visit(node, data); } private void checkForResources(ASTMethodOrConstructorDeclaration methodOrConstructor, Object data) { reportedVarNames.clear(); Map<ASTVariableDeclaratorId, TypeNode> resVars = getResourceVariables(methodOrConstructor); for (Map.Entry<ASTVariableDeclaratorId, TypeNode> resVarEntry : resVars.entrySet()) { ASTVariableDeclaratorId resVar = resVarEntry.getKey(); TypeNode runtimeType = resVarEntry.getValue(); TypeNode resVarType = wrappedResourceTypeOrReturn(resVar, runtimeType); if (isWrappingResourceSpecifiedInTry(resVar)) { reportedVarNames.add(resVar.getName()); addViolationWithMessage(data, resVar, WRAPPING_TRY_WITH_RES_VAR_MESSAGE, new Object[] { resVar.getName() }); } else if (shouldVarOfTypeBeClosedInMethod(resVar, resVarType, methodOrConstructor)) { reportedVarNames.add(resVar.getName()); addCloseResourceViolation(resVar, runtimeType, data); } else if (isNotAllowedResourceType(resVarType)) { ASTExpressionStatement reassigningStatement = getFirstReassigningStatementBeforeBeingClosed(resVar, methodOrConstructor); if (reassigningStatement != null) { reportedVarNames.add(resVar.getName()); addViolationWithMessage(data, reassigningStatement, REASSIGN_BEFORE_CLOSED_MESSAGE, new Object[] { resVar.getName() }); } } } } private Map<ASTVariableDeclaratorId, TypeNode> getResourceVariables(ASTMethodOrConstructorDeclaration method) { Map<ASTVariableDeclaratorId, TypeNode> resVars = new HashMap<>(); if (method.getBody() == null) { return resVars; } List<ASTVariableDeclaratorId> vars = method.getBody().descendants(ASTVariableDeclaratorId.class) .filterNot(ASTVariableDeclaratorId::isFormalParameter) .filterNot(ASTVariableDeclaratorId::isExceptionBlockParameter) .filter(this::isVariableNotSpecifiedInTryWithResource) .filter(var -> isResourceTypeOrSubtype(var) || isNodeInstanceOfResourceType(getTypeOfVariable(var))) .filterNot(var -> var.isAnnotationPresent("lombok.Cleanup")) .toList(); for (ASTVariableDeclaratorId var : vars) { TypeNode varType = getTypeOfVariable(var); resVars.put(var, varType); } return resVars; } private TypeNode getTypeOfVariable(ASTVariableDeclaratorId var) { TypeNode runtimeType = getRuntimeTypeOfVariable(var); return runtimeType != null ? runtimeType : var.getTypeNode(); } private TypeNode getRuntimeTypeOfVariable(ASTVariableDeclaratorId var) { ASTExpression initExpr = var.getInitializer(); return var.isTypeInferred() || isRuntimeType(initExpr) ? initExpr : null; } private boolean isRuntimeType(ASTExpression expr) { if (expr == null || isMethodCall(expr) || expr instanceof ASTNullLiteral) { return false; } @Nullable JTypeDeclSymbol symbol = expr.getTypeMirror().getSymbol(); return symbol != null && !symbol.isUnresolved(); } private TypeNode wrappedResourceTypeOrReturn(ASTVariableDeclaratorId var, TypeNode defaultVal) { TypeNode wrappedResType = getWrappedResourceType(var); return wrappedResType != null ? wrappedResType : defaultVal; } private TypeNode getWrappedResourceType(ASTVariableDeclaratorId var) { ASTExpression initExpr = initializerExpressionOf(var); if (initExpr != null) { ASTConstructorCall resAlloc = getLastResourceAllocation(initExpr); if (resAlloc != null) { ASTExpression firstArgRes = getFirstArgumentVariableIfResource(resAlloc); return firstArgRes != null ? firstArgRes : resAlloc; } } return null; } private ASTExpression initializerExpressionOf(ASTVariableDeclaratorId var) { return var.getInitializer(); } private ASTConstructorCall getLastResourceAllocation(ASTExpression expr) { List<ASTConstructorCall> allocations = expr.descendantsOrSelf().filterIs(ASTConstructorCall.class).toList(); int lastAllocIndex = allocations.size() - 1; for (int allocIndex = lastAllocIndex; allocIndex >= 0; allocIndex--) { ASTConstructorCall allocation = allocations.get(allocIndex); if (isResourceTypeOrSubtype(allocation)) { return allocation; } } return null; } private ASTExpression getFirstArgumentVariableIfResource(ASTConstructorCall allocation) { ASTArgumentList argsList = allocation.getArguments(); if (argsList != null && argsList.size() > 0) { ASTExpression firstArg = argsList.get(0); return isNotMethodCall(firstArg) && isResourceTypeOrSubtype(firstArg) ? firstArg : null; } return null; } private boolean isNotMethodCall(ASTExpression expr) { return !isMethodCall(expr); } private boolean isMethodCall(ASTExpression expression) { return expression instanceof ASTMethodCall; } private boolean isWrappingResourceSpecifiedInTry(ASTVariableDeclaratorId var) { ASTVariableAccess wrappedVarName = getWrappedVariableName(var); if (wrappedVarName != null) { ASTVariableDeclaratorId 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; } } } } return false; } private boolean shouldVarOfTypeBeClosedInMethod(ASTVariableDeclaratorId var, TypeNode type, ASTMethodOrConstructorDeclaration method) { return isNotAllowedResourceType(type) && isNotWrappingResourceMethodParameter(var, method) && isResourceVariableUnclosed(var); } private boolean isNotAllowedResourceType(TypeNode varType) { return !isAllowedResourceType(varType); } private boolean isAllowedResourceType(TypeNode refType) { List<String> allowedResourceTypes = getProperty(ALLOWED_RESOURCE_TYPES); if (allowedResourceTypes != null) { for (String type : allowedResourceTypes) { // the check here must be a exact type match, since subclasses may override close() // and actually require closing if (TypeTestUtil.isExactlyA(type, refType)) { return true; } } } return false; } private boolean isNotWrappingResourceMethodParameter(ASTVariableDeclaratorId var, ASTMethodOrConstructorDeclaration method) { return !isWrappingResourceMethodParameter(var, method); } /** * Checks whether the variable is a resource and initialized from a method parameter. * @param var the resource variable that is being initialized * @param method the method or constructor in which the variable is declared * @return <code>true</code> if the variable is a resource and initialized from a method parameter. <code>false</code> * otherwise. */ private boolean isWrappingResourceMethodParameter(ASTVariableDeclaratorId var, ASTMethodOrConstructorDeclaration method) { ASTVariableAccess wrappedVarName = getWrappedVariableName(var); if (wrappedVarName != null) { ASTFormalParameters methodParams = method.getFormalParameters(); for (ASTFormalParameter param : methodParams) { if ((isResourceTypeOrSubtype(param) || wrappedVarName.getParent() instanceof ASTVariableDeclarator || wrappedVarName.getParent() instanceof ASTAssignmentExpression) && JavaAstUtils.isReferenceToVar(wrappedVarName, param.getVarId().getSymbol())) { return true; } } } return false; } private ASTVariableAccess getWrappedVariableName(ASTVariableDeclaratorId var) { ASTExpression initializer = var.getInitializer(); if (initializer != null) { return var.getInitializer().descendantsOrSelf().filterIs(ASTVariableAccess.class) .filter(usage -> !(usage.getParent() instanceof ASTMethodCall)).first(); } return null; } private boolean isResourceTypeOrSubtype(TypeNode refType) { @Nullable JTypeDeclSymbol symbol = refType.getTypeMirror().getSymbol(); return symbol != null && !symbol.isUnresolved() ? isNodeInstanceOfResourceType(refType) : nodeHasReferenceToResourceType(refType); } private boolean isNodeInstanceOfResourceType(TypeNode refType) { for (String resType : types) { if (TypeTestUtil.isA(resType, refType)) { return true; } } return false; } private boolean nodeHasReferenceToResourceType(TypeNode refType) { @Nullable JTypeDeclSymbol symbol = refType.getTypeMirror().getSymbol(); if (symbol != null) { String simpleTypeName = symbol.getSimpleName(); return isResourceTypeName(simpleTypeName); } return false; } private boolean isResourceTypeName(String typeName) { String simpleTypeName = toSimpleType(typeName); return types.contains(typeName) || simpleTypes.contains(simpleTypeName); } private boolean isResourceVariableUnclosed(ASTVariableDeclaratorId var) { return !isResourceVariableClosed(var); } private boolean isResourceVariableClosed(ASTVariableDeclaratorId var) { Node methodOfVar = getMethodOfNode(var); return hasTryStatementClosingResourceVariable(methodOfVar, var) || isReturnedByMethod(var, methodOfVar); } private Node getMethodOfNode(Node node) { Node parent = node.getParent(); while (isNotMethod(parent)) { parent = parent.getParent(); } return parent; } private boolean isNotMethod(Node node) { return !(node instanceof ASTBlock || node instanceof ASTConstructorDeclaration); } private boolean hasTryStatementClosingResourceVariable(Node node, ASTVariableDeclaratorId var) { List<ASTTryStatement> tryStatements = node.descendants(ASTTryStatement.class).crossFindBoundaries().toList(); for (ASTTryStatement tryStatement : tryStatements) { if (tryStatementClosesResourceVariable(tryStatement, var)) { return true; } } return false; } private boolean tryStatementClosesResourceVariable(ASTTryStatement tryStatement, ASTVariableDeclaratorId var) { if (tryStatement.getBeginLine() >= var.getBeginLine() && noneCriticalStatementsBetween(var, tryStatement)) { if (isTryWithResourceSpecifyingVariable(tryStatement, var)) { return true; } if (hasFinallyClause(tryStatement)) { ASTBlock finallyBody = tryStatement.getFinallyClause().getBody(); return blockClosesResourceVariable(finallyBody, var); } } return false; } private boolean noneCriticalStatementsBetween(ASTVariableDeclaratorId var, ASTTryStatement tryStatement) { return !anyCriticalStatementBetween(var, tryStatement); } private boolean anyCriticalStatementBetween(ASTVariableDeclaratorId var, ASTTryStatement tryStatement) { ASTStatement varStatement = var.ancestors(ASTStatement.class).first(); if (isNotNullInitialized(var) && areStatementsOfSameBlock(varStatement, tryStatement)) { for (ASTStatement bsBetween : getBlockStatementsBetween(varStatement, tryStatement)) { if (isCriticalStatement(bsBetween)) { return true; } } } return false; } private boolean isNotNullInitialized(ASTVariableDeclaratorId var) { return !hasNullInitializer(var); } private boolean hasNullInitializer(ASTVariableDeclaratorId var) { return var.getInitializer() instanceof ASTNullLiteral; } private boolean areStatementsOfSameBlock(ASTStatement bs0, ASTStatement bs1) { return bs0.getParent() == bs1.getParent(); } private List<ASTStatement> getBlockStatementsBetween(ASTStatement top, ASTStatement bottom) { List<ASTStatement> blockStatements = top.getParent().children(ASTStatement.class).toList(); int topIndex = blockStatements.indexOf(top); int bottomIndex = blockStatements.indexOf(bottom); return blockStatements.subList(topIndex + 1, bottomIndex); } private boolean isCriticalStatement(ASTStatement blockStatement) { boolean isVarDeclaration = blockStatement.descendantsOrSelf().filterIs(ASTLocalVariableDeclaration.class).nonEmpty(); boolean isAssignmentOperator = blockStatement.descendantsOrSelf().filterIs(ASTAssignmentExpression.class).nonEmpty(); return !isVarDeclaration && !isAssignmentOperator; } private boolean isTryWithResourceSpecifyingVariable(ASTTryStatement tryStatement, ASTVariableDeclaratorId varId) { return tryStatement.isTryWithResources() && isVariableSpecifiedInTryWithResource(varId, tryStatement); } private boolean isVariableNotSpecifiedInTryWithResource(ASTVariableDeclaratorId varId) { @Nullable ASTTryStatement tryStatement = varId.ancestors(ASTTryStatement.class) .filter(ASTTryStatement::isTryWithResources) .first(); return tryStatement == null || !isVariableSpecifiedInTryWithResource(varId, tryStatement); } private boolean isVariableSpecifiedInTryWithResource(ASTVariableDeclaratorId varId, ASTTryStatement tryWithResource) { // skip own resources - these are definitively closed if (tryWithResource.getResources().descendants(ASTVariableDeclaratorId.class).toList().contains(varId)) { return true; } List<ASTVariableAccess> usedVars = getResourcesSpecifiedInTryWith(tryWithResource); for (ASTVariableAccess res : usedVars) { if (JavaAstUtils.isReferenceToVar(res, varId.getSymbol())) { return true; } } return false; } private List<ASTVariableAccess> getResourcesSpecifiedInTryWith(ASTTryStatement tryWithResource) { return tryWithResource.getResources().descendantsOrSelf().filterIs(ASTVariableAccess.class).toList(); } private boolean hasFinallyClause(ASTTryStatement tryStatement) { return tryStatement.getFinallyClause() != null; } private boolean blockClosesResourceVariable(ASTBlock block, ASTVariableDeclaratorId variableToClose) { return hasNotConditionalCloseCallOnVariable(block, variableToClose) || hasMethodCallClosingResourceVariable(block, variableToClose); } private boolean hasNotConditionalCloseCallOnVariable(ASTBlock block, ASTVariableDeclaratorId variableToClose) { List<ASTMethodCall> methodCallsOnVariable = block.descendants(ASTMethodCall.class) .filter(call -> isMethodCallOnVariable(call, variableToClose)) .toList(); for (ASTMethodCall call : methodCallsOnVariable) { if (isCloseTargetMethodCall(call) && isNotConditional(block, call, variableToClose)) { return true; } } return false; } private boolean isMethodCallOnVariable(ASTExpression expr, ASTVariableDeclaratorId variable) { if (expr instanceof ASTMethodCall) { ASTMethodCall methodCall = (ASTMethodCall) expr; return JavaAstUtils.isReferenceToVar(methodCall.getQualifier(), variable.getSymbol()); } return false; } /** * Checks, whether the given node is inside an if condition, and if so, * whether this is a null check for the given varName. * * @param enclosingBlock * where to search for if statements * @param node * the node, where the call for the close is done * @param varName * 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. */ private boolean isNotConditional(ASTBlock enclosingBlock, Node node, ASTVariableDeclaratorId var) { ASTIfStatement ifStatement = findIfStatement(enclosingBlock, node); if (ifStatement != null) { // find expressions like: varName != null or null != varName if (ifStatement.getCondition() instanceof ASTInfixExpression) { ASTInfixExpression equalityExpr = (ASTInfixExpression) ifStatement.getCondition(); if (BinaryOp.NE == equalityExpr.getOperator()) { ASTExpression left = equalityExpr.getLeftOperand(); ASTExpression right = equalityExpr.getRightOperand(); if (JavaAstUtils.isReferenceToVar(left, var.getSymbol()) && isNullLiteral(right) || JavaAstUtils.isReferenceToVar(right, var.getSymbol()) && isNullLiteral(left)) { return true; } } } // find method call Objects.nonNull(varName) return isObjectsNonNull(ifStatement.getCondition(), var); } return true; } private boolean isObjectsNonNull(ASTExpression expression, ASTVariableDeclaratorId var) { if (OBJECTS_NON_NULL.matchesCall(expression)) { ASTMethodCall methodCall = (ASTMethodCall) expression; return JavaAstUtils.isReferenceToVar(methodCall.getArguments().get(0), var.getSymbol()); } return false; } private boolean isNullLiteral(JavaNode node) { return node instanceof ASTNullLiteral; } private ASTIfStatement findIfStatement(ASTBlock enclosingBlock, Node node) { ASTIfStatement ifStatement = node.ancestors(ASTIfStatement.class).first(); List<ASTIfStatement> allIfStatements = enclosingBlock.descendants(ASTIfStatement.class).toList(); if (ifStatement != null && allIfStatements.contains(ifStatement)) { return ifStatement; } return null; } private boolean hasMethodCallClosingResourceVariable(ASTBlock block, ASTVariableDeclaratorId variableToClose) { List<ASTMethodCall> methodCalls = block.descendants(ASTMethodCall.class).crossFindBoundaries().toList(); for (ASTMethodCall call : methodCalls) { if (isMethodCallClosingResourceVariable(call, variableToClose)) { return true; } } return false; } private boolean isMethodCallClosingResourceVariable(ASTExpression expr, ASTVariableDeclaratorId variableToClose) { if (!(expr instanceof ASTMethodCall)) { return false; } ASTMethodCall call = (ASTMethodCall) expr; return (isCloseTargetMethodCall(call) || hasChainedCloseTargetMethodCall(call)) && variableIsPassedToMethod(variableToClose, call); } private boolean isCloseTargetMethodCall(ASTMethodCall methodCall) { String fullName = methodCall.getMethodName(); if (methodCall.getQualifier() instanceof ASTTypeExpression) { fullName = methodCall.getQualifier().getText() + "." + fullName; } return closeTargets.contains(fullName); } private boolean hasChainedCloseTargetMethodCall(ASTMethodCall start) { ASTExpression walker = start; while (walker instanceof ASTMethodCall) { ASTMethodCall methodCall = (ASTMethodCall) walker; if (isCloseTargetMethodCall(methodCall)) { return true; } walker = methodCall.getQualifier(); } return false; } private boolean variableIsPassedToMethod(ASTVariableDeclaratorId varName, ASTMethodCall methodCall) { List<ASTNamedReferenceExpr> usedRefs = methodCall.getArguments().descendants(ASTNamedReferenceExpr.class).toList(); for (ASTNamedReferenceExpr ref : usedRefs) { if (varName.getSymbol().equals(ref.getReferencedSym())) { return true; } } return false; } private boolean isReturnedByMethod(ASTVariableDeclaratorId variable, Node method) { return method .descendants(ASTReturnStatement.class).crossFindBoundaries() .descendants(ASTVariableAccess.class) .filter(access -> !(access.getParent() instanceof ASTMethodCall)) .filter(access -> JavaAstUtils.isReferenceToVar(access, variable.getSymbol())) .nonEmpty(); } private void addCloseResourceViolation(ASTVariableDeclaratorId id, TypeNode type, Object data) { String resTypeName = getResourceTypeName(id, type); addViolation(data, id, resTypeName); } private String getResourceTypeName(ASTVariableDeclaratorId varId, TypeNode type) { if (type instanceof ASTType) { return PrettyPrintingUtil.prettyPrintType((ASTType) type); } @Nullable JTypeDeclSymbol symbol = type.getTypeMirror().getSymbol(); if (symbol != null) { return symbol.getSimpleName(); } @Nullable ASTLocalVariableDeclaration localVarDecl = varId.ancestors(ASTLocalVariableDeclaration.class).first(); if (localVarDecl != null && localVarDecl.getTypeNode() != null) { return PrettyPrintingUtil.prettyPrintType(localVarDecl.getTypeNode()); } return varId.getName(); } @Override public Object visit(ASTMethodCall node, Object data) { if (!getProperty(DETECT_CLOSE_NOT_IN_FINALLY)) { return super.visit(node, data); } if (isCloseTargetMethodCall(node) && node.getQualifier() instanceof ASTVariableAccess) { ASTVariableAccess closedVar = (ASTVariableAccess) node.getQualifier(); if (isNotInFinallyBlock(closedVar) && !reportedVarNames.contains(closedVar.getName())) { addViolationWithMessage(data, closedVar, CLOSE_IN_FINALLY_BLOCK_MESSAGE, new Object[] { closedVar.getName() }); } } return super.visit(node, data); } private boolean isNotInFinallyBlock(ASTVariableAccess closedVar) { return closedVar.ancestors(ASTFinallyClause.class).isEmpty(); } private ASTExpressionStatement getFirstReassigningStatementBeforeBeingClosed(ASTVariableDeclaratorId variable, ASTMethodOrConstructorDeclaration methodOrConstructor) { List<ASTExpressionStatement> statements = methodOrConstructor.descendants(ASTExpressionStatement.class).toList(); boolean variableClosed = false; boolean isInitialized = !hasNullInitializer(variable); ASTExpression initializingExpression = initializerExpressionOf(variable); for (ASTExpressionStatement statement : statements) { if (isClosingVariableStatement(statement, variable)) { variableClosed = true; } if (isAssignmentForVariable(statement, variable)) { ASTAssignmentExpression assignment = (ASTAssignmentExpression) statement.getFirstChild(); if (isInitialized && !variableClosed) { if (initializingExpression != null && !inSameIfBlock(statement, initializingExpression) && notInNullCheckIf(statement, variable) && isNotSelfAssignment(assignment)) { return statement; } } if (variableClosed) { variableClosed = false; } if (!isInitialized) { isInitialized = true; initializingExpression = statement.getExpr(); } } } return null; } private boolean isNotSelfAssignment(ASTAssignmentExpression assignment) { return assignment.getRightOperand().descendantsOrSelf().filterIs(ASTVariableAccess.class).filter(access -> { return JavaAstUtils.isReferenceToSameVar(access, assignment.getLeftOperand()); }).isEmpty(); } private boolean notInNullCheckIf(ASTExpressionStatement statement, ASTVariableDeclaratorId variable) { Node grandparent = statement.ancestors().get(1); if (grandparent instanceof ASTIfStatement) { ASTIfStatement ifStatement = (ASTIfStatement) grandparent; if (JavaRuleUtil.isNullCheck(ifStatement.getCondition(), variable.getSymbol())) { return false; } } return true; } private boolean inSameIfBlock(ASTExpressionStatement statement1, ASTExpression statement2) { List<ASTIfStatement> parents1 = statement1.ancestors(ASTIfStatement.class).toList(); List<ASTIfStatement> parents2 = statement2.ancestors(ASTIfStatement.class).toList(); parents1.retainAll(parents2); return !parents1.isEmpty(); } private boolean isClosingVariableStatement(ASTExpressionStatement statement, ASTVariableDeclaratorId variable) { return isMethodCallClosingResourceVariable(statement.getExpr(), variable) || isMethodCallOnVariable(statement.getExpr(), variable); } private boolean isAssignmentForVariable(ASTExpressionStatement statement, ASTVariableDeclaratorId variable) { if (statement == null || variable == null || !(statement.getExpr() instanceof ASTAssignmentExpression)) { return false; } ASTAssignmentExpression assignment = (ASTAssignmentExpression) statement.getExpr(); return JavaAstUtils.isReferenceToVar(assignment.getLeftOperand(), variable.getSymbol()); } }
34,112
43.302597
171
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/NullAssignmentRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; public class NullAssignmentRule extends AbstractJavaRulechainRule { public NullAssignmentRule() { super(ASTNullLiteral.class); } @Override public Object visit(ASTNullLiteral node, Object data) { if (node.getParent() instanceof ASTAssignmentExpression) { ASTAssignmentExpression assignment = (ASTAssignmentExpression) node.getParent(); if (isAssignmentToFinal(assignment)) { return data; } if (assignment.getRightOperand() == node) { addViolation(data, node); } } else if (node.getParent() instanceof ASTConditionalExpression) { if (isBadTernary((ASTConditionalExpression) node.getParent(), node)) { addViolation(data, node); } } return data; } private boolean isAssignmentToFinal(ASTAssignmentExpression n) { @NonNull ASTAssignableExpr leftOperand = n.getLeftOperand(); if (leftOperand instanceof ASTNamedReferenceExpr) { @Nullable JVariableSymbol symbol = ((ASTNamedReferenceExpr) leftOperand).getReferencedSym(); return symbol != null && symbol.isFinal(); } return false; } private boolean isBadTernary(ASTConditionalExpression ternary, ASTNullLiteral nullLiteral) { boolean isInitializer = false; ASTVariableDeclarator variableDeclarator = ternary.ancestors(ASTVariableDeclarator.class).first(); isInitializer = variableDeclarator != null && variableDeclarator.getInitializer() == ternary; boolean isThenOrElse = ternary.getThenBranch() == nullLiteral || ternary.getElseBranch() == nullLiteral; // check for nested ternaries... ASTConditionalExpression currentTernary = ternary; while (currentTernary.getParent() instanceof ASTConditionalExpression) { ASTConditionalExpression parentTernary = (ASTConditionalExpression) currentTernary.getParent(); isThenOrElse &= parentTernary.getThenBranch() == currentTernary || parentTernary.getElseBranch() == currentTernary; currentTernary = parentTernary; } boolean isAssignment = currentTernary.getParent() instanceof ASTAssignmentExpression; return isThenOrElse && isAssignment && !isInitializer; } }
3,181
39.794872
127
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/ProperCloneImplementationRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; public class ProperCloneImplementationRule extends AbstractJavaRulechainRule { public ProperCloneImplementationRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration method, Object data) { if (JavaAstUtils.isCloneMethod(method) && !method.isAbstract()) { ASTAnyTypeDeclaration enclosingType = method.getEnclosingType(); if (isNotFinal(enclosingType) && hasAnyAllocationOfClass(method, enclosingType)) { addViolation(data, method); } } return data; } private boolean isNotFinal(ASTAnyTypeDeclaration classOrInterfaceDecl) { return !classOrInterfaceDecl.hasModifiers(JModifier.FINAL); } private boolean hasAnyAllocationOfClass(ASTMethodDeclaration method, ASTAnyTypeDeclaration enclosingType) { @NonNull JClassSymbol typeSymbol = enclosingType.getTypeMirror().getSymbol(); return method.descendants(ASTConstructorCall.class) .filter(ctor -> ctor.getTypeMirror().getSymbol().equals(typeSymbol)) .nonEmpty(); } }
1,769
36.659574
111
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/errorprone/UnnecessaryCaseChangeRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.errorprone; import static java.util.Arrays.asList; import java.util.List; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class UnnecessaryCaseChangeRule extends AbstractJavaRulechainRule { private static final List<String> CASE_CHANGING_METHODS = asList("toLowerCase", "toUpperCase"); private static final List<String> EQUALITY_METHODS = asList("equals", "equalsIgnoreCase"); public UnnecessaryCaseChangeRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall node, Object data) { if (EQUALITY_METHODS.contains(node.getMethodName()) && node.getArguments().size() == 1) { if (isCaseChangingMethodCall(node.getQualifier()) || isCaseChangingMethodCall(node.getArguments().get(0))) { addViolation(data, node); } } return data; } /** * Checks for toLower/UpperCase method calls without arguments. * These method take an optional Locale as an argument - in that case, * these case conversions are considered deliberate. */ private boolean isCaseChangingMethodCall(ASTExpression expr) { if (expr instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) expr; return CASE_CHANGING_METHODS.contains(call.getMethodName()) && call.getArguments().size() == 0; } return false; } }
1,684
34.104167
107
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/xpath/internal/MatchesSignatureFunction.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.xpath.internal; import net.sourceforge.pmd.lang.java.ast.InvocationNode; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sf.saxon.trans.XPathException; public final class MatchesSignatureFunction extends BaseRewrittenFunction<InvocationMatcher, InvocationNode> { public static final MatchesSignatureFunction INSTANCE = new MatchesSignatureFunction(); private MatchesSignatureFunction() { super("matchesSig", InvocationNode.class); } @Override protected boolean matches(InvocationNode contextNode, String arg, InvocationMatcher parsedArg, boolean isConstant) throws XPathException { return parsedArg.matchesCall(contextNode); } @Override protected InvocationMatcher parseArgument(String arg) throws XPathException { try { return InvocationMatcher.parse(arg); } catch (IllegalArgumentException e) { throw new XPathException(e); } } }
1,096
30.342857
142
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/xpath/internal/NodeIsFunction.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.xpath.internal; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sf.saxon.trans.XPathException; public final class NodeIsFunction extends BaseRewrittenFunction<Class<?>, JavaNode> { public static final NodeIsFunction INSTANCE = new NodeIsFunction(); private NodeIsFunction() { super("nodeIs", JavaNode.class); } @Override protected Class<?> parseArgument(String arg) throws XPathException { try { return Class.forName("net.sourceforge.pmd.lang.java.ast.AST" + arg); } catch (ClassNotFoundException e) { throw new XPathException("No class named AST" + arg); } } @Override protected boolean matches(JavaNode contextNode, String arg, Class<?> parsedArg, boolean isConstant) throws XPathException { return parsedArg.isInstance(contextNode); } }
993
28.235294
127
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/xpath/internal/GetCommentOnFunction.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ 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.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.JavaComment; import net.sourceforge.pmd.lang.rule.xpath.internal.AstElementNode; import net.sf.saxon.expr.XPathContext; import net.sf.saxon.lib.ExtensionFunctionCall; import net.sf.saxon.om.EmptyAtomicSequence; import net.sf.saxon.om.Sequence; import net.sf.saxon.value.SequenceType; import net.sf.saxon.value.StringValue; /** * The XPath query "//VariableDeclarator[contains(getCommentOn(), * '//password')]" will find all variables declared that are annotated with the * password comment. * * @author Andy Throgmorton */ public class GetCommentOnFunction extends BaseJavaXPathFunction { public static final GetCommentOnFunction INSTANCE = new GetCommentOnFunction(); protected GetCommentOnFunction() { super("getCommentOn"); } @Override public SequenceType[] getArgumentTypes() { return new SequenceType[0]; } @Override public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) { return SequenceType.OPTIONAL_STRING; } @Override public boolean dependsOnFocus() { return true; } @Override public ExtensionFunctionCall makeCallExpression() { return new ExtensionFunctionCall() { @Override public Sequence call(XPathContext context, Sequence[] arguments) { Node contextNode = ((AstElementNode) context.getContextItem()).getUnderlyingNode(); int codeBeginLine = contextNode.getBeginLine(); int codeEndLine = contextNode.getEndLine(); List<JavaComment> commentList = contextNode.getFirstParentOfType(ASTCompilationUnit.class).getComments(); for (JavaComment comment : commentList) { if (comment.getBeginLine() == codeBeginLine || comment.getEndLine() == codeEndLine) { return new StringValue(comment.getText()); } } return EmptyAtomicSequence.INSTANCE; } }; } }
2,334
27.82716
121
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/xpath/internal/BaseRewrittenFunction.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.xpath.internal; import static net.sourceforge.pmd.lang.java.rule.xpath.internal.BaseContextNodeTestFun.SINGLE_STRING_SEQ; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.rule.xpath.internal.AstElementNode; import net.sf.saxon.expr.Expression; import net.sf.saxon.expr.StaticContext; import net.sf.saxon.expr.StringLiteral; import net.sf.saxon.expr.XPathContext; import net.sf.saxon.lib.ExtensionFunctionCall; import net.sf.saxon.om.Sequence; import net.sf.saxon.trans.XPathException; import net.sf.saxon.value.BooleanValue; import net.sf.saxon.value.SequenceType; /** * A context node test function that may parse its string argument early * if it is a string literal. * * @param <S> Type of state into which the argument is parsed * @param <N> Type of node the function applies. The function will return * false for other kinds of node. */ // TODO could move that up to pmd-core abstract class BaseRewrittenFunction<S, N extends Node> extends BaseJavaXPathFunction { private final Class<N> contextNodeType; protected BaseRewrittenFunction(String localName, Class<N> contextNodeType) { super(localName); this.contextNodeType = contextNodeType; } @Override public SequenceType[] getArgumentTypes() { return SINGLE_STRING_SEQ; } @Override public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) { return SequenceType.SINGLE_BOOLEAN; } @Override public boolean dependsOnFocus() { return true; } /** * Parse the argument into the state. This is called at build time * if the arg is constant, otherwise it's anyway called before {@link #matches(Node, String, Object, boolean)} * is called. */ protected abstract S parseArgument(String arg) throws XPathException; /** * Compute the result of the function. * * @param contextNode Context node * @param arg Value of the argument * @param parsedArg Result of {@link #parseArgument(String)} on the argument * @param isConstant Whether the argument is constant (it was parsed in all cases) * * @return Whether the function matches */ protected abstract boolean matches(N contextNode, String arg, S parsedArg, boolean isConstant) throws XPathException; @Override public ExtensionFunctionCall makeCallExpression() { return new ExtensionFunctionCall() { private S constantState; private boolean isConstant; @Override public Expression rewrite(StaticContext context, Expression[] arguments) throws XPathException { // If the argument is a string literal then we can preload // the class, and check that it's valid at expression build time Expression firstArg = arguments[0]; // this expression has been type checked so there is an argument if (firstArg instanceof StringLiteral) { String name = ((StringLiteral) firstArg).getStringValue(); try { constantState = parseArgument(name); } catch (XPathException e) { e.setIsStaticError(true); throw e; } isConstant = true; } return null; } @Override public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException { Node node = ((AstElementNode) context.getContextItem()).getUnderlyingNode(); if (!contextNodeType.isInstance(node)) { // we could report that as an error return BooleanValue.FALSE; } String arg = arguments[0].head().getStringValue(); S parsedArg = isConstant ? constantState : parseArgument(arg); return BooleanValue.get(matches((N) node, arg, parsedArg, isConstant)); } }; } }
4,258
34.491667
121
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/xpath/internal/GetModifiersFun.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.xpath.internal; import java.util.Set; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTModifierList; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.rule.xpath.internal.AstElementNode; import net.sourceforge.pmd.util.CollectionUtil; import net.sf.saxon.expr.XPathContext; import net.sf.saxon.lib.ExtensionFunctionCall; import net.sf.saxon.om.Sequence; import net.sf.saxon.value.EmptySequence; import net.sf.saxon.value.SequenceExtent; import net.sf.saxon.value.SequenceType; import net.sf.saxon.value.StringValue; /** * The two functions {@code modifiers} and {@code explicitModifiers}. */ public final class GetModifiersFun extends BaseJavaXPathFunction { private static final SequenceType[] ARGTYPES = {}; private final boolean explicit; public static final GetModifiersFun GET_EFFECTIVE = new GetModifiersFun("modifiers", false); public static final GetModifiersFun GET_EXPLICIT = new GetModifiersFun("explicitModifiers", true); private GetModifiersFun(String localName, boolean explicit) { super(localName); this.explicit = explicit; } @Override public SequenceType[] getArgumentTypes() { return ARGTYPES; } @Override public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) { return SequenceType.STRING_SEQUENCE; } @Override public boolean dependsOnFocus() { return true; } @Override public ExtensionFunctionCall makeCallExpression() { return new ExtensionFunctionCall() { @Override public Sequence call(XPathContext context, Sequence[] arguments) { Node contextNode = ((AstElementNode) context.getContextItem()).getUnderlyingNode(); if (contextNode instanceof AccessNode) { ASTModifierList modList = ((AccessNode) contextNode).getModifiers(); Set<JModifier> mods = explicit ? modList.getExplicitModifiers() : modList.getEffectiveModifiers(); return new SequenceExtent(CollectionUtil.map(mods, mod -> new StringValue(mod.getToken()))); } else { return EmptySequence.getInstance(); } } }; } }
2,542
33.364865
112
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/xpath/internal/BaseJavaXPathFunction.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.xpath.internal; import net.sourceforge.pmd.lang.java.JavaLanguageModule; import net.sourceforge.pmd.lang.rule.xpath.impl.AbstractXPathFunctionDef; abstract class BaseJavaXPathFunction extends AbstractXPathFunctionDef { protected BaseJavaXPathFunction(String localName) { super(localName, JavaLanguageModule.TERSE_NAME); } }
474
28.6875
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/xpath/internal/BaseContextNodeTestFun.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.xpath.internal; import java.util.function.BiPredicate; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.Annotatable; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.TypeNode; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.lang.rule.xpath.internal.AstElementNode; import net.sf.saxon.expr.XPathContext; import net.sf.saxon.lib.ExtensionFunctionCall; import net.sf.saxon.om.Sequence; import net.sf.saxon.trans.XPathException; import net.sf.saxon.value.BooleanValue; import net.sf.saxon.value.SequenceType; /** * XPath function {@code pmd-java:typeIs(typeName as xs:string) as xs:boolean} * and {@code typeIsExactly}. * * <p>Example XPath 2.0: {@code //ClassOrInterfaceType[pmd-java:typeIs('java.lang.String')]} * * <p>Returns true if the type of the node matches, false otherwise. */ public class BaseContextNodeTestFun<T extends JavaNode> extends BaseJavaXPathFunction { static final SequenceType[] SINGLE_STRING_SEQ = {SequenceType.SINGLE_STRING}; private final Class<T> klass; private final BiPredicate<String, T> checker; public static final BaseJavaXPathFunction TYPE_IS_EXACTLY = new BaseContextNodeTestFun<>(TypeNode.class, "typeIsExactly", TypeTestUtil::isExactlyA); public static final BaseJavaXPathFunction TYPE_IS = new BaseContextNodeTestFun<>(TypeNode.class, "typeIs", TypeTestUtil::isA); public static final BaseJavaXPathFunction HAS_ANNOTATION = new BaseContextNodeTestFun<>(Annotatable.class, "hasAnnotation", (name, node) -> node.isAnnotationPresent(name)); protected BaseContextNodeTestFun(Class<T> klass, String localName, BiPredicate<String, T> checker) { super(localName); this.klass = klass; this.checker = checker; } @Override public SequenceType[] getArgumentTypes() { return SINGLE_STRING_SEQ; } @Override public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) { return SequenceType.SINGLE_BOOLEAN; } @Override public boolean dependsOnFocus() { return true; } @Override public ExtensionFunctionCall makeCallExpression() { return new ExtensionFunctionCall() { @Override public Sequence call(XPathContext context, Sequence[] arguments) throws XPathException { Node contextNode = ((AstElementNode) context.getContextItem()).getUnderlyingNode(); String fullTypeName = arguments[0].head().getStringValue(); return BooleanValue.get(klass.isInstance(contextNode) && checker.test(fullTypeName, (T) contextNode)); } }; } }
2,848
36.486842
176
java