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/rule/xpath/internal/MetricFunction.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.ast.Node; import net.sourceforge.pmd.lang.metrics.LanguageMetricsProvider; import net.sourceforge.pmd.lang.metrics.Metric; import net.sourceforge.pmd.lang.metrics.MetricOptions; 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.BigDecimalValue; import net.sf.saxon.value.EmptySequence; import net.sf.saxon.value.SequenceType; /** * Implements the {@code metric()} XPath function. Takes the * string name of a metric and the context node and returns * the result if the metric can be computed, otherwise returns * {@link Double#NaN}. * * @author Clément Fournier * @since 6.0.0 */ public final class MetricFunction extends BaseJavaXPathFunction { public static final MetricFunction INSTANCE = new MetricFunction(); private MetricFunction() { super("metric"); } @Override public SequenceType[] getArgumentTypes() { return new SequenceType[] {SequenceType.SINGLE_STRING}; } @Override public SequenceType getResultType(SequenceType[] suppliedArgumentTypes) { return SequenceType.OPTIONAL_DECIMAL; } @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 metricKey = arguments[0].head().getStringValue(); double metric = getMetric(contextNode, metricKey); return Double.isFinite(metric) ? new BigDecimalValue(metric) : EmptySequence.getInstance(); } }; } static String badMetricKeyMessage(String constantName) { return String.format("'%s' is not the name of a metric", constantName); } private static double getMetric(Node n, String metricKeyName) throws XPathException { LanguageMetricsProvider provider = n.getAstInfo().getLanguageProcessor().services().getLanguageMetricsProvider(); Metric<?, ?> metric = provider.getMetricWithName(metricKeyName); if (metric == null) { throw new XPathException(badMetricKeyMessage(metricKeyName)); } Number computed = Metric.compute(metric, n, MetricOptions.emptyOptions()); return computed == null ? Double.NaN : computed.doubleValue(); } }
2,931
30.191489
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/MissingOverrideRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; /** * Flags missing @Override annotations. * * @author Clément Fournier * @since 6.2.0 */ public class MissingOverrideRule extends AbstractJavaRulechainRule { public MissingOverrideRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (node.isOverridden() && !node.isAnnotationPresent(Override.class)) { addViolation(data, node, new Object[] { PrettyPrintingUtil.displaySignature(node) }); } return data; } }
899
27.125
97
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/PrimitiveWrapperInstantiationRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTBooleanLiteral; 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.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; public class PrimitiveWrapperInstantiationRule extends AbstractJavaRulechainRule { private static final InvocationMatcher BOOLEAN_VALUEOF_MATCHER = InvocationMatcher.parse("java.lang.Boolean#valueOf(_)"); public PrimitiveWrapperInstantiationRule() { super(ASTConstructorCall.class, ASTMethodCall.class); } @Override public Object visit(ASTConstructorCall node, Object data) { ASTClassOrInterfaceType type = node.firstChild(ASTClassOrInterfaceType.class); if (type == null) { return data; } if (TypeTestUtil.isA(Double.class, type) || TypeTestUtil.isA(Float.class, type) || TypeTestUtil.isA(Long.class, type) || TypeTestUtil.isA(Integer.class, type) || TypeTestUtil.isA(Short.class, type) || TypeTestUtil.isA(Byte.class, type) || TypeTestUtil.isA(Character.class, type)) { addViolation(data, node, type.getSimpleName()); } else if (TypeTestUtil.isA(Boolean.class, type)) { checkArguments(node.getArguments(), node, data); } return data; } /** * Finds calls of "Boolean.valueOf". */ @Override public Object visit(ASTMethodCall node, Object data) { if (BOOLEAN_VALUEOF_MATCHER.matchesCall(node)) { checkArguments(node.getArguments(), node, data); } return data; } private void checkArguments(ASTArgumentList arguments, JavaNode node, Object data) { if (arguments == null || arguments.size() != 1) { return; } boolean isNewBoolean = node instanceof ASTConstructorCall; String messagePart = isNewBoolean ? "Do not use `new Boolean" : "Do not use `Boolean.valueOf"; ASTStringLiteral stringLiteral = getFirstArgStringLiteralOrNull(arguments); ASTBooleanLiteral boolLiteral = getFirstArgBooleanLiteralOrNull(arguments); if (stringLiteral != null) { if ("\"true\"".equals(stringLiteral.getImage())) { addViolationWithMessage(data, node, messagePart + "(\"true\")`, prefer `Boolean.TRUE`"); } else if ("\"false\"".equals(stringLiteral.getImage())) { addViolationWithMessage(data, node, messagePart + "(\"false\")`, prefer `Boolean.FALSE`"); } else { addViolationWithMessage(data, node, messagePart + "(\"...\")`, prefer `Boolean.valueOf`"); } } else if (boolLiteral != null) { if (boolLiteral.isTrue()) { addViolationWithMessage(data, node, messagePart + "(true)`, prefer `Boolean.TRUE`"); } else { addViolationWithMessage(data, node, messagePart + "(false)`, prefer `Boolean.FALSE`"); } } else if (isNewBoolean) { // any argument with "new Boolean", might be a variable access addViolationWithMessage(data, node, messagePart + "(...)`, prefer `Boolean.valueOf`"); } } private static ASTStringLiteral getFirstArgStringLiteralOrNull(ASTArgumentList arguments) { if (arguments.size() == 1) { ASTExpression firstArg = arguments.get(0); if (firstArg instanceof ASTStringLiteral) { return (ASTStringLiteral) firstArg; } } return null; } private static ASTBooleanLiteral getFirstArgBooleanLiteralOrNull(ASTArgumentList arguments) { if (arguments.size() == 1) { ASTExpression firstArg = arguments.get(0); if (firstArg instanceof ASTBooleanLiteral) { return (ASTBooleanLiteral) firstArg; } } return null; } }
4,574
40.216216
125
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UnusedFormalParameterRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; 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.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; public class UnusedFormalParameterRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> CHECKALL_DESCRIPTOR = booleanProperty("checkAll").desc("Check all methods, including non-private ones").defaultValue(false).build(); public UnusedFormalParameterRule() { super(ASTConstructorDeclaration.class, ASTMethodDeclaration.class); definePropertyDescriptor(CHECKALL_DESCRIPTOR); } @Override public Object visit(ASTConstructorDeclaration node, Object data) { check(node, data); return data; } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (node.getVisibility() != Visibility.V_PRIVATE && !getProperty(CHECKALL_DESCRIPTOR)) { return data; } if (node.getBody() != null && !node.hasModifiers(JModifier.DEFAULT) && !JavaRuleUtil.isSerializationReadObject(node) && !node.isOverridden()) { check(node, data); } return data; } private void check(ASTMethodOrConstructorDeclaration node, Object data) { for (ASTFormalParameter formal : node.getFormalParameters()) { ASTVariableDeclaratorId varId = formal.getVarId(); if (JavaAstUtils.isNeverUsed(varId) && !JavaRuleUtil.isExplicitUnusedVarName(varId.getName())) { addViolation(data, varId, new Object[] { node instanceof ASTMethodDeclaration ? "method" : "constructor", varId.getName(), }); } } } }
2,483
39.721311
185
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidReassigningCatchVariablesRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import org.checkerframework.checker.nullness.qual.NonNull; 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.ASTCatchParameter; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class AvoidReassigningCatchVariablesRule extends AbstractJavaRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTCatchParameter.class); } @Override public Object visit(ASTCatchParameter catchParam, Object data) { ASTVariableDeclaratorId caughtExceptionId = catchParam.getVarId(); for (ASTNamedReferenceExpr usage : caughtExceptionId.getLocalUsages()) { if (usage.getAccessType() == AccessType.WRITE) { addViolation(data, usage, caughtExceptionId.getName()); } } return data; } }
1,263
35.114286
81
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidReassigningLoopVariablesRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static java.util.Arrays.asList; import static net.sourceforge.pmd.properties.PropertyFactory.enumProperty; import static net.sourceforge.pmd.util.CollectionUtil.associateBy; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.NodeStream; 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.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement; import net.sourceforge.pmd.lang.java.ast.ASTContinueStatement; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTForUpdate; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTLocalClassStatement; import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; 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.util.StringUtil.CaseConvention; public class AvoidReassigningLoopVariablesRule extends AbstractJavaRulechainRule { private static final Map<String, ForeachReassignOption> FOREACH_REASSIGN_VALUES = associateBy(asList(ForeachReassignOption.values()), ForeachReassignOption::getDisplayName); private static final PropertyDescriptor<ForeachReassignOption> FOREACH_REASSIGN = enumProperty("foreachReassign", FOREACH_REASSIGN_VALUES) .defaultValue(ForeachReassignOption.DENY) .desc("how/if foreach control variables may be reassigned") .build(); private static final Map<String, ForReassignOption> FOR_REASSIGN_VALUES = associateBy(asList(ForReassignOption.values()), ForReassignOption::getDisplayName); private static final PropertyDescriptor<ForReassignOption> FOR_REASSIGN = enumProperty("forReassign", FOR_REASSIGN_VALUES) .defaultValue(ForReassignOption.DENY) .desc("how/if for control variables may be reassigned") .build(); public AvoidReassigningLoopVariablesRule() { super(ASTForStatement.class, ASTForeachStatement.class); definePropertyDescriptor(FOREACH_REASSIGN); definePropertyDescriptor(FOR_REASSIGN); } @Override public Object visit(ASTForeachStatement loopStmt, Object data) { ForeachReassignOption behavior = getProperty(FOREACH_REASSIGN); if (behavior == ForeachReassignOption.ALLOW) { return data; } ASTVariableDeclaratorId loopVar = loopStmt.getVarId(); boolean ignoreNext = behavior == ForeachReassignOption.FIRST_ONLY; for (ASTNamedReferenceExpr usage : loopVar.getLocalUsages()) { if (usage.getAccessType() == AccessType.WRITE) { if (ignoreNext) { ignoreNext = false; continue; } addViolation(data, usage, loopVar.getName()); } else { ignoreNext = false; } } return null; } @Override public Object visit(ASTForStatement loopStmt, Object data) { ForReassignOption behavior = getProperty(FOR_REASSIGN); if (behavior == ForReassignOption.ALLOW) { return data; } NodeStream<ASTVariableDeclaratorId> loopVars = JavaAstUtils.getLoopVariables(loopStmt); if (behavior == ForReassignOption.DENY) { ASTForUpdate update = loopStmt.firstChild(ASTForUpdate.class); for (ASTVariableDeclaratorId loopVar : loopVars) { for (ASTNamedReferenceExpr usage : loopVar.getLocalUsages()) { if (usage.getAccessType() == AccessType.WRITE) { if (update != null && usage.ancestors(ASTForUpdate.class).first() == update) { continue; } addViolation(data, usage, loopVar.getName()); } } } } else { Set<String> loopVarNames = loopVars.collect(Collectors.mapping(ASTVariableDeclaratorId::getName, Collectors.toSet())); Set<String> labels = JavaAstUtils.getStatementLabels(loopStmt); new ControlFlowCtx(false, loopVarNames, (RuleContext) data, labels, false, false).roamStatementsForExit(loopStmt.getBody()); } return null; } class ControlFlowCtx { private final boolean guarded; private boolean mayExit; private final Set<String> loopVarNames; private final RuleContext ruleCtx; private final Set<String> outerLoopNames; private final boolean breakHidden; private final boolean continueHidden; ControlFlowCtx(boolean guarded, Set<String> loopVarNames, RuleContext ctx, Set<String> outerLoopNames, boolean breakHidden, boolean continueHidden) { this.guarded = guarded; this.loopVarNames = loopVarNames; this.ruleCtx = ctx; this.outerLoopNames = outerLoopNames; this.breakHidden = breakHidden; this.continueHidden = continueHidden; } ControlFlowCtx withGuard(boolean isGuarded) { return copy(isGuarded, breakHidden, continueHidden); } ControlFlowCtx copy(boolean isGuarded, boolean breakHidden, boolean continueHidden) { return new ControlFlowCtx(isGuarded, loopVarNames, ruleCtx, outerLoopNames, breakHidden, continueHidden); } private boolean roamStatementsForExit(JavaNode node) { if (node == null) { return false; } NodeStream<? extends JavaNode> unwrappedBlock = node instanceof ASTBlock ? ((ASTBlock) node).toStream() : NodeStream.of(node); return roamStatementsForExit(unwrappedBlock); } // return true if any statement may exit the outer loop abruptly // This way increments of variables are allowed if they are guarded by a conditional private boolean roamStatementsForExit(NodeStream<? extends JavaNode> stmts) { for (JavaNode stmt : stmts) { if (stmt instanceof ASTThrowStatement || stmt instanceof ASTReturnStatement) { return true; } else if (stmt instanceof ASTBreakStatement) { String label = ((ASTBreakStatement) stmt).getLabel(); return label != null && outerLoopNames.contains(label) || !breakHidden; } else if (stmt instanceof ASTContinueStatement) { String label = ((ASTContinueStatement) stmt).getLabel(); return label != null && outerLoopNames.contains(label) || !continueHidden; } // note that we mean to use |= and not shortcut evaluation if (stmt instanceof ASTLoopStatement) { ASTStatement body = ((ASTLoopStatement) stmt).getBody(); for (JavaNode child : stmt.children()) { if (child != body) { // NOPMD checkVorViolations(child); } } mayExit |= copy(true, true, true).roamStatementsForExit(body); } else if (stmt instanceof ASTSwitchStatement) { ASTSwitchStatement switchStmt = (ASTSwitchStatement) stmt; checkVorViolations(switchStmt.getTestedExpression()); mayExit |= copy(true, true, false).roamStatementsForExit(switchStmt.getBranches()); } else if (stmt instanceof ASTIfStatement) { ASTIfStatement ifStmt = (ASTIfStatement) stmt; checkVorViolations(ifStmt.getCondition()); mayExit |= withGuard(true).roamStatementsForExit(ifStmt.getThenBranch()); mayExit |= withGuard(this.guarded).roamStatementsForExit(ifStmt.getElseBranch()); } else if (stmt instanceof ASTExpression) { // these two catch-all clauses implement other statements & eg switch branches checkVorViolations(stmt); } else if (!(stmt instanceof ASTLocalClassStatement)) { mayExit |= roamStatementsForExit(stmt.children()); } } return mayExit; } private void checkVorViolations(JavaNode node) { if (node == null) { return; } final boolean onlyConsiderWrite = guarded || mayExit; node.descendants(ASTNamedReferenceExpr.class) .filter(it -> loopVarNames.contains(it.getName())) .filter(it -> onlyConsiderWrite ? JavaAstUtils.isVarAccessStrictlyWrite(it) : JavaAstUtils.isVarAccessReadAndWrite(it)) .forEach(it -> addViolation(ruleCtx, it, it.getName())); } } private enum ForeachReassignOption { /** * Deny reassigning the 'foreach' control variable */ DENY, /** * Allow reassigning the 'foreach' control variable if it is the first statement in the loop body. */ FIRST_ONLY, /** * Allow reassigning the 'foreach' control variable. */ ALLOW; /** * The RuleDocGenerator uses toString() to determine the default value. * * @return the mapped property value instead of the enum name */ @Override public String toString() { return getDisplayName(); } public String getDisplayName() { return CaseConvention.SCREAMING_SNAKE_CASE.convertTo(CaseConvention.CAMEL_CASE, name()); } } private enum ForReassignOption { /** * Deny reassigning a 'for' control variable. */ DENY, /** * Allow skipping elements by incrementing/decrementing the 'for' control variable. */ SKIP, /** * Allow reassigning the 'for' control variable. */ ALLOW; /** * The RuleDocGenerator uses toString() to determine the default value. * * @return the mapped property value instead of the enum name */ @Override public String toString() { return getDisplayName(); } public String getDisplayName() { return CaseConvention.SCREAMING_SNAKE_CASE.convertTo(CaseConvention.CAMEL_CASE, name()); } } }
11,516
39.696113
157
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/JUnitAssertionsShouldIncludeMessageRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.InvocationMatcher.CompoundInvocationMatcher; public class JUnitAssertionsShouldIncludeMessageRule extends AbstractJavaRulechainRule { private final CompoundInvocationMatcher checks = InvocationMatcher.parseAll( "_#assertEquals(_,_)", "_#assertTrue(_)", "_#assertFalse(_)", "_#assertSame(_,_)", "_#assertNotSame(_,_)", "_#assertNull(_)", "_#assertNotNull(_)", "_#assertArrayEquals(_,_)", "_#assertThat(_,_)", "_#fail()", "_#assertEquals(float,float,float)", "_#assertEquals(double,double,double)" ); public JUnitAssertionsShouldIncludeMessageRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall node, Object data) { if (TestFrameworksUtil.isCallOnAssertionContainer(node)) { if (checks.anyMatch(node)) { addViolation(data, node); } } return null; } }
1,489
32.111111
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/SimplifiableTestAssertionRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isBooleanLiteral; 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.ASTBooleanLiteral; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTList; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.BinaryOp; 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.TestFrameworksUtil; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind; /** * */ public class SimplifiableTestAssertionRule extends AbstractJavaRulechainRule { private static final InvocationMatcher OBJECT_EQUALS = InvocationMatcher.parse("_#equals(java.lang.Object)"); public SimplifiableTestAssertionRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall node, Object data) { final boolean isAssertTrue = isAssertionCall(node, "assertTrue"); final boolean isAssertFalse = isAssertionCall(node, "assertFalse"); if (isAssertTrue || isAssertFalse) { ASTArgumentList args = node.getArguments(); ASTExpression lastArg = args.getLastChild(); ASTInfixExpression eq = asEqualityExpr(lastArg); if (eq != null) { boolean isPositive = isPositiveEqualityExpr(eq) == isAssertTrue; final String suggestion; if (JavaAstUtils.isNullLiteral(eq.getLeftOperand()) || JavaAstUtils.isNullLiteral(eq.getRightOperand())) { // use assertNull/assertNonNull suggestion = isPositive ? "assertNull" : "assertNonNull"; } else { if (isPrimitive(eq.getLeftOperand()) || isPrimitive(eq.getRightOperand())) { suggestion = isPositive ? "assertEquals" : "assertNotEquals"; } else { suggestion = isPositive ? "assertSame" : "assertNotSame"; } } addViolation(data, node, suggestion); } else { @Nullable ASTExpression negatedExprOperand = getNegatedExprOperand(lastArg); if (OBJECT_EQUALS.matchesCall(negatedExprOperand)) { //assertTrue(!a.equals(b)) String suggestion = isAssertTrue ? "assertNotEquals" : "assertEquals"; addViolation(data, node, suggestion); } else if (negatedExprOperand != null) { //assertTrue(!something) String suggestion = isAssertTrue ? "assertFalse" : "assertTrue"; addViolation(data, node, suggestion); } else if (OBJECT_EQUALS.matchesCall(lastArg)) { //assertTrue(a.equals(b)) String suggestion = isAssertTrue ? "assertEquals" : "assertNotEquals"; addViolation(data, node, suggestion); } } } boolean isAssertEquals = isAssertionCall(node, "assertEquals"); boolean isAssertNotEquals = isAssertionCall(node, "assertNotEquals"); if (isAssertEquals || isAssertNotEquals) { ASTArgumentList argList = node.getArguments(); if (argList.size() >= 2) { ASTExpression comp0 = getChildRev(argList, -1); ASTExpression comp1 = getChildRev(argList, -2); if (isBooleanLiteral(comp0) ^ isBooleanLiteral(comp1)) { if (isBooleanLiteral(comp1)) { ASTExpression tmp = comp0; comp0 = comp1; comp1 = tmp; } // now the literal is in comp0 and the other is some expr if (comp1.getTypeMirror().isPrimitive(PrimitiveTypeKind.BOOLEAN)) { ASTBooleanLiteral literal = (ASTBooleanLiteral) comp0; String suggestion = literal.isTrue() == isAssertEquals ? "assertTrue" : "assertFalse"; addViolation(data, node, suggestion); } } } } return null; } private boolean isPrimitive(ASTExpression node) { return node.getTypeMirror().isPrimitive(); } /** * Returns a child with an offset from the end. Eg {@code getChildRev(list, -1)} * returns the last child. */ private static <T extends JavaNode> T getChildRev(@NonNull ASTList<T> list, int i) { assert i < 0 : "Expecting negative offset"; return list.get(list.getNumChildren() + i); } private boolean isAssertionCall(ASTMethodCall call, String methodName) { return call.getMethodName().equals(methodName) && !call.getOverloadSelectionInfo().isFailed() && TestFrameworksUtil.isCallOnAssertionContainer(call); } private ASTInfixExpression asEqualityExpr(ASTExpression node) { if (JavaAstUtils.isInfixExprWithOperator(node, BinaryOp.EQUALITY_OPS)) { return (ASTInfixExpression) node; } return null; } private boolean isPositiveEqualityExpr(ASTInfixExpression node) { return node != null && node.getOperator() == BinaryOp.EQ; } private static ASTExpression getNegatedExprOperand(ASTExpression node) { if (JavaAstUtils.isBooleanNegation(node)) { return ((ASTUnaryExpression) node).getOperand(); } return null; } }
6,238
40.872483
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AbstractClassWithoutAbstractMethodRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class AbstractClassWithoutAbstractMethodRule extends AbstractJavaRulechainRule { public AbstractClassWithoutAbstractMethodRule() { super(ASTClassOrInterfaceDeclaration.class); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface() || !node.isAbstract() || doesExtend(node) || doesImplement(node)) { return data; } if (node.getDeclarations(ASTMethodDeclaration.class).none(ASTMethodDeclaration::isAbstract)) { addViolation(data, node); } return data; } private boolean doesExtend(ASTClassOrInterfaceDeclaration node) { return node.getSuperClassTypeNode() != null; } private boolean doesImplement(ASTClassOrInterfaceDeclaration node) { return !node.getSuperInterfaceTypeNodes().isEmpty(); } }
1,233
31.473684
102
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidReassigningParametersRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; 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.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class AvoidReassigningParametersRule extends AbstractJavaRulechainRule { public AvoidReassigningParametersRule() { super(ASTMethodDeclaration.class, ASTConstructorDeclaration.class); } @Override public Object visit(ASTMethodDeclaration node, Object data) { lookForViolations(node, data); return data; } @Override public Object visit(ASTConstructorDeclaration node, Object data) { lookForViolations(node, data); return data; } private void lookForViolations(ASTMethodOrConstructorDeclaration node, Object data) { for (ASTFormalParameter formal : node.getFormalParameters()) { ASTVariableDeclaratorId varId = formal.getVarId(); for (ASTNamedReferenceExpr usage : varId.getLocalUsages()) { if (usage.getAccessType() == AccessType.WRITE) { addViolation(data, usage, varId.getName()); // only the first assignment should be reported break; } } } } }
1,787
35.489796
89
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UnusedLocalVariableRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; 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.rule.RuleTargetSelector; public class UnusedLocalVariableRule extends AbstractJavaRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTLocalVariableDeclaration.class); } @Override public Object visit(ASTLocalVariableDeclaration decl, Object data) { for (ASTVariableDeclaratorId varId : decl.getVarIds()) { if (JavaAstUtils.isNeverUsed(varId) && !JavaRuleUtil.isExplicitUnusedVarName(varId.getName())) { addViolation(data, varId, varId.getName()); } } return data; } }
1,213
33.685714
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UnusedAssignmentRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.UnaryOp; 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.JavaRuleUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class UnusedAssignmentRule extends AbstractJavaRulechainRule { /* Detects unused assignments. This performs a reaching definition analysis. This makes the assumption that there is no dead code. Since we have the reaching definitions at each variable usage, we could also use that to detect other kinds of bug, eg conditions that are always true, or dereferences that will always NPE. In the general case though, this is complicated and better left to a DFA library, eg google Z3. This analysis may be used as-is to detect switch labels that fall-through, which could be useful to improve accuracy of other rules. TODO * labels on arbitrary statements (currently only loops) * explicit ctor call (hard to impossible without type res, or at least proper graph algorithms like toposort) -> this is pretty invisible as it causes false negatives, not FPs * test ternary expr * more precise exception handling: since we have access to the overload for method & ctors, we can know where its thrown exceptions may end up in enclosing catches. * extract the reaching definition analysis, to exploit control flow information in rules + symbol table. The following are needed to implement scoping of pattern variables, and are already computed by this analysis: * whether a switch may fall through * whether a statement always completes abruptly * whether a statement never completes abruptly because of break DONE * conditionals * loops * switch * loop labels * try/catch/finally * lambdas * constructors + initializers * anon class * test this.field in ctors * foreach var should be reassigned from one iter to another * test local class/anonymous class * shortcut conditionals have their own control-flow * parenthesized expressions * conditional exprs in loops * ignore variables that start with 'ignore' * ignore params of native methods * ignore params of abstract methods */ private static final PropertyDescriptor<Boolean> CHECK_PREFIX_INCREMENT = PropertyFactory.booleanProperty("checkUnusedPrefixIncrement") .desc("Report expressions like ++i that may be replaced with (i + 1)") .defaultValue(false) .build(); private static final PropertyDescriptor<Boolean> REPORT_UNUSED_VARS = PropertyFactory.booleanProperty("reportUnusedVariables") .desc("Report variables that are only initialized, and never read at all. " + "The rule UnusedVariable already cares for that, but you can enable it if needed") .defaultValue(false) .build(); public UnusedAssignmentRule() { super(ASTCompilationUnit.class); definePropertyDescriptor(CHECK_PREFIX_INCREMENT); definePropertyDescriptor(REPORT_UNUSED_VARS); } @Override public Object visit(ASTCompilationUnit node, Object data) { DataflowResult result = DataflowPass.getDataflowResult(node); reportFinished(result, (RuleContext) data); return data; } private void reportFinished(DataflowResult result, RuleContext ruleCtx) { for (AssignmentEntry entry : result.getUnusedAssignments()) { if (entry.isUnaryReassign() && isIgnorablePrefixIncrement(entry.getLocation())) { continue; } Set<AssignmentEntry> killers = result.getKillers(entry); final String reason; if (killers.isEmpty()) { // var went out of scope before being used (no assignment kills it, yet it's unused) if (entry.isField()) { // assignments to fields don't really go out of scope continue; } else if (suppressUnusedVariableRuleOverlap(entry)) { // see REPORT_UNUSED_VARS property continue; } // This is a "DU" anomaly, the others are "DD" reason = null; } else if (killers.size() == 1) { AssignmentEntry k = killers.iterator().next(); if (k.getLocation().equals(entry.getLocation())) { // assignment reassigns itself, only possible in a loop if (suppressUnusedVariableRuleOverlap(entry)) { continue; } else if (entry.isForeachVar()) { reason = null; } else { reason = "reassigned every iteration"; } } else { reason = "overwritten on line " + k.getLine(); } } else { reason = joinLines("overwritten on lines ", killers); } if (reason == null && JavaRuleUtil.isExplicitUnusedVarName(entry.getVarId().getName())) { // Then the variable is never used (cf UnusedVariable) // We ignore those that start with "ignored", as that is standard // practice for exceptions, and may be useful for resources/foreach vars continue; } addViolationWithMessage(ruleCtx, entry.getLocation(), makeMessage(entry, reason, entry.isField())); } } private boolean suppressUnusedVariableRuleOverlap(AssignmentEntry entry) { return !getProperty(REPORT_UNUSED_VARS) && (entry.isInitializer() || entry.isBlankDeclaration()); } private static String getKind(ASTVariableDeclaratorId id) { if (id.isField()) { return "field"; } else if (id.isResourceDeclaration()) { return "resource"; } else if (id.isExceptionBlockParameter()) { return "exception parameter"; } else if (id.getNthParent(3) instanceof ASTForeachStatement) { return "loop variable"; } else if (id.isFormalParameter()) { return "parameter"; } return "variable"; } private boolean isIgnorablePrefixIncrement(JavaNode assignment) { if (assignment instanceof ASTUnaryExpression) { // the variable value is used if it was found somewhere else // than in statement position UnaryOp op = ((ASTUnaryExpression) assignment).getOperator(); return !getProperty(CHECK_PREFIX_INCREMENT) && !op.isPure() && op.isPrefix() && !(assignment.getParent() instanceof ASTExpressionStatement); } return false; } private static String makeMessage(AssignmentEntry assignment, @Nullable String reason, boolean isField) { // if reason is null, then the variable is unused (at most assigned to) StringBuilder result = new StringBuilder(64); if (assignment.isInitializer()) { result.append(isField ? "the field initializer for" : "the initializer for variable"); } else if (assignment.isBlankDeclaration()) { if (reason != null) { result.append("the initial value of "); } result.append(getKind(assignment.getVarId())); } else { // regular assignment if (assignment.isUnaryReassign()) { result.append("the updated value of "); } else { result.append("the value assigned to "); } result.append(isField ? "field" : "variable"); } result.append(" ''").append(assignment.getVarId().getName()).append("''"); result.append(" is never used"); if (reason != null) { result.append(" (").append(reason).append(")"); } result.setCharAt(0, Character.toUpperCase(result.charAt(0))); return result.toString(); } private static String joinLines(String prefix, Set<AssignmentEntry> killers) { StringBuilder sb = new StringBuilder(prefix); List<AssignmentEntry> sorted = new ArrayList<>(killers); sorted.sort(Comparator.naturalOrder()); sb.append(sorted.get(0).getLine()); for (int i = 1; i < sorted.size() - 1; i++) { sb.append(", ").append(sorted.get(i).getLine()); } sb.append(" and ").append(sorted.get(sorted.size() - 1).getLine()); return sb.toString(); } }
10,057
41.982906
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LiteralsFirstInComparisonsRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.util.CollectionUtil.listOf; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.lang.reflect.Modifier; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.RuleContext; 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.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; public class LiteralsFirstInComparisonsRule extends AbstractJavaRulechainRule { private static final Set<String> STRING_COMPARISONS = setOf("equalsIgnoreCase", "compareTo", "compareToIgnoreCase", "contentEquals"); public LiteralsFirstInComparisonsRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall call, Object data) { if ("equals".equals(call.getMethodName()) && call.getArguments().size() == 1 && isEqualsObjectAndNotAnOverload(call)) { checkArgs((RuleContext) data, call); } else if (STRING_COMPARISONS.contains(call.getMethodName()) && call.getArguments().size() == 1 && TypeTestUtil.isDeclaredInClass(String.class, call.getMethodType())) { checkArgs((RuleContext) data, call); } return data; } private boolean isEqualsObjectAndNotAnOverload(ASTMethodCall call) { return call.getOverloadSelectionInfo().isFailed() // failed selection is considered probably equals(Object) || call.getMethodType().getFormalParameters().equals(listOf(call.getTypeSystem().OBJECT)); } private boolean isConstantString(JavaNode node) { if (node instanceof ASTNamedReferenceExpr) { ASTNamedReferenceExpr reference = (ASTNamedReferenceExpr) node; @Nullable JFieldSymbol symbol = null; if (reference.getReferencedSym() instanceof JFieldSymbol) { symbol = (JFieldSymbol) reference.getReferencedSym(); } if (symbol != null && symbol.isFinal() && Modifier.isStatic(symbol.getModifiers())) { return reference.getTypeMirror().getSymbol() .equals(reference.getTypeSystem().getClassSymbol(String.class)); } } return node instanceof ASTStringLiteral; } private void checkArgs(RuleContext ctx, ASTMethodCall call) { ASTExpression arg = call.getArguments().get(0); ASTExpression qualifier = call.getQualifier(); if (!isConstantString(qualifier) && (arg instanceof ASTStringLiteral || isConstantString(arg))) { addViolation(ctx, call); } } }
3,240
38.048193
115
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UseCollectionIsEmptyRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.util.Collection; import java.util.Map; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * Detect structures like "foo.size() == 0" and suggest replacing them with * foo.isEmpty(). Will also find != 0 (replaceable with !isEmpty()). * * @author Jason Bennett */ public class UseCollectionIsEmptyRule extends AbstractJavaRulechainRule { public UseCollectionIsEmptyRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall call, Object data) { if ((TypeTestUtil.isA(Collection.class, call.getQualifier()) || TypeTestUtil.isA(Map.class, call.getQualifier())) && isSizeZeroCheck(call)) { addViolation(data, call); } return null; } private static boolean isSizeZeroCheck(ASTMethodCall call) { return "size".equals(call.getMethodName()) && call.getArguments().size() == 0 && JavaRuleUtil.isZeroChecked(call); } }
1,330
29.953488
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/JUnitTestContainsTooManyAssertsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; 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; import net.sourceforge.pmd.properties.constraints.NumericConstraints; public class JUnitTestContainsTooManyAssertsRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Integer> MAX_ASSERTS = PropertyFactory.intProperty("maximumAsserts") .desc("Maximum number of assert calls in a test method") .require(NumericConstraints.positive()) .defaultValue(1) .build(); public JUnitTestContainsTooManyAssertsRule() { super(ASTMethodDeclaration.class); definePropertyDescriptor(MAX_ASSERTS); } @Override public Object visit(ASTMethodDeclaration method, Object data) { ASTBlock body = method.getBody(); if (body != null && TestFrameworksUtil.isTestMethod(method)) { int assertCount = body.descendants(ASTMethodCall.class) .filter(TestFrameworksUtil::isProbableAssertCall) .count(); if (assertCount > getProperty(MAX_ASSERTS)) { addViolation(data, method); } } return data; } }
1,761
38.155556
84
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/JUnitUseExpectedRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil.isJUnitMethod; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTTryStatement; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; /** * This rule finds code like this: * * <pre> * public void testFoo() { * try { * doSomething(); * fail(&quot;should have thrown an exception&quot;); * } catch (Exception e) { * } * } * </pre> * * In JUnit 4, use * * <pre> * &#064;Test(expected = Exception.class) * </pre> * * @author acaplan * */ public class JUnitUseExpectedRule extends AbstractJavaRulechainRule { public JUnitUseExpectedRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration node, Object data) { ASTBlock body = node.getBody(); if (body != null && isJUnitMethod(node)) { body.descendants(ASTTryStatement.class) .filter(this::isWeirdTry) .forEach(it -> addViolation(data, it)); } return null; } private boolean isWeirdTry(ASTTryStatement tryStmt) { ASTStatement lastStmt = tryStmt.getBody().getLastChild(); return (lastStmt instanceof ASTThrowStatement || lastStmt instanceof ASTExpressionStatement && isFailStmt((ASTExpressionStatement) lastStmt)) && tryStmt.getCatchClauses().any(it -> it.getBody().size() == 0); } private boolean isFailStmt(ASTExpressionStatement stmt) { if (stmt.getExpr() instanceof ASTMethodCall) { ASTMethodCall expr = (ASTMethodCall) stmt.getExpr(); return "fail".equals(expr.getMethodName()); } return false; } }
2,235
29.630137
107
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AvoidUsingHardCodedIPRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static java.util.Arrays.asList; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class AvoidUsingHardCodedIPRule extends AbstractJavaRulechainRule { private enum AddressKinds { IPV4("IPv4"), IPV6("IPv6"), IPV4_MAPPED_IPV6("IPv4 mapped IPv6"); private final String label; AddressKinds(String label) { this.label = label; } } private static final PropertyDescriptor<List<AddressKinds>> CHECK_ADDRESS_TYPES_DESCRIPTOR = PropertyFactory.enumListProperty("checkAddressTypes", AddressKinds.class, k -> k.label) .desc("Check for IP address types.") .defaultValue(asList(AddressKinds.values())) .build(); // Provides 4 capture groups that can be used for additional validation private static final String IPV4_REGEXP = "([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})"; // Uses IPv4 pattern, but changes the groups to be non-capture private static final String IPV6_REGEXP = "(?:(?:[0-9a-fA-F]{1,4})?\\:)+(?:[0-9a-fA-F]{1,4}|" + IPV4_REGEXP.replace("(", "(?:") + ")?"; private static final Pattern IPV4_PATTERN = Pattern.compile("^" + IPV4_REGEXP + "$"); private static final Pattern IPV6_PATTERN = Pattern.compile("^" + IPV6_REGEXP + "$"); private final Set<AddressKinds> kindsToCheck = EnumSet.noneOf(AddressKinds.class); public AvoidUsingHardCodedIPRule() { super(ASTStringLiteral.class); definePropertyDescriptor(CHECK_ADDRESS_TYPES_DESCRIPTOR); } @Override public void start(RuleContext ctx) { kindsToCheck.clear(); kindsToCheck.addAll(getProperty(CHECK_ADDRESS_TYPES_DESCRIPTOR)); } @Override public Object visit(ASTStringLiteral node, Object data) { final String image = node.getConstValue(); // Note: We used to check the addresses using // InetAddress.getByName(String), but that's extremely slow, // so we created more robust checking methods. if (image.length() > 0) { final char firstChar = Character.toUpperCase(image.charAt(0)); boolean checkIPv4 = kindsToCheck.contains(AddressKinds.IPV4); boolean checkIPv6 = kindsToCheck.contains(AddressKinds.IPV6); boolean checkIPv4MappedIPv6 = kindsToCheck.contains(AddressKinds.IPV4_MAPPED_IPV6); if (checkIPv4 && isIPv4(firstChar, image) || isIPv6(firstChar, image, checkIPv6, checkIPv4MappedIPv6)) { addViolation(data, node); } } return data; } private boolean isLatinDigit(char c) { return '0' <= c && c <= '9'; } private boolean isHexCharacter(char c) { return isLatinDigit(c) || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f'; } private boolean isIPv4(final char firstChar, final String s) { // Quick check before using Regular Expression // 1) At least 7 characters // 2) 1st character must be a digit from '0' - '9' // 3) Must contain at least 1 . (period) if (s.length() < 7 || !isLatinDigit(firstChar) || s.indexOf('.') < 0) { return false; } Matcher matcher = IPV4_PATTERN.matcher(s); if (matcher.matches()) { // All octets in range [0, 255] for (int i = 1; i <= matcher.groupCount(); i++) { int octet = Integer.parseInt(matcher.group(i)); if (octet < 0 || octet > 255) { return false; } } return true; } else { return false; } } private boolean isIPv6(final char firstChar, String s, final boolean checkIPv6, final boolean checkIPv4MappedIPv6) { // Quick check before using Regular Expression // 1) At least 3 characters // 2) 1st must be a Hex number or a : (colon) // 3) Must contain at least 2 colons (:) if (s.length() < 3 || !(isHexCharacter(firstChar) || firstChar == ':') || StringUtils.countMatches(s, ':') < 2) { return false; } Matcher matcher = IPV6_PATTERN.matcher(s); if (matcher.matches()) { // Account for leading or trailing :: before splitting on : boolean zeroSubstitution = false; if (s.startsWith("::")) { s = s.substring(2); zeroSubstitution = true; } else if (s.endsWith("::")) { s = s.substring(0, s.length() - 2); zeroSubstitution = true; } // String.split() doesn't produce an empty String in the trailing // case, but it does in the leading. if (s.endsWith(":")) { return false; } // All the intermediate parts must be hexadecimal, or int count = 0; boolean ipv4Mapped = false; String[] parts = s.split(":"); for (int i = 0; i < parts.length; i++) { final String part = parts[i]; // An empty part indicates :: was encountered. There can only be // 1 such instance. if (part.length() == 0) { if (zeroSubstitution) { return false; } else { zeroSubstitution = true; } continue; } else { count++; } // Should be a hexadecimal number in range [0, 65535] try { int value = Integer.parseInt(part, 16); if (value < 0 || value > 65535) { return false; } } catch (NumberFormatException e) { // The last part can be a standard IPv4 address. if (i != parts.length - 1 || !isIPv4(part.charAt(0), part)) { return false; } ipv4Mapped = true; } } // IPv6 addresses are 128 bit, are we that long? if (zeroSubstitution) { if (ipv4Mapped) { return checkIPv4MappedIPv6 && 1 <= count && count <= 6; } else { return checkIPv6 && 1 <= count && count <= 7; } } else { if (ipv4Mapped) { return checkIPv4MappedIPv6 && count == 7; } else { return checkIPv6 && count == 8; } } } else { return false; } } @Override public String dysfunctionReason() { return !getProperty(CHECK_ADDRESS_TYPES_DESCRIPTOR).isEmpty() ? null : "No address types specified"; } }
7,514
35.304348
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/CheckResultSetRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.sql.ResultSet; import java.util.Set; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * Rule that verifies, that the return values of next(), first(), last(), etc. * calls to a java.sql.ResultSet are actually verified. */ public class CheckResultSetRule extends AbstractJavaRule { private static final Set<String> METHODS = setOf("next", "previous", "last", "first"); @Override public Object visit(ASTWhileStatement node, Object data) { return data; } @Override public Object visit(ASTReturnStatement node, Object data) { return data; } @Override public Object visit(ASTIfStatement node, Object data) { return data; } @Override public Object visit(ASTMethodCall node, Object data) { if (isResultSetMethod(node)) { addViolation(data, node); } return super.visit(node, data); } private boolean isResultSetMethod(ASTMethodCall node) { return METHODS.contains(node.getMethodName()) && TypeTestUtil.isDeclaredInClass(ResultSet.class, node.getMethodType()); } }
1,635
28.745455
90
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/ForLoopCanBeForeachRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.lang.ast.NodeStream.empty; import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.INT; import java.util.Iterator; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTArrayAccess; 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.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; 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.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTStatementExpressionList; 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.BinaryOp; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * @author Clément Fournier * @since 6.0.0 */ public class ForLoopCanBeForeachRule extends AbstractJavaRulechainRule { private static final InvocationMatcher ITERATOR_CALL = InvocationMatcher.parse("java.lang.Iterable#iterator()"); private static final InvocationMatcher ITERATOR_NEXT = InvocationMatcher.parse("java.util.Iterator#next()"); private static final InvocationMatcher ITERATOR_HAS_NEXT = InvocationMatcher.parse("java.util.Iterator#hasNext()"); private static final InvocationMatcher COLLECTION_SIZE = InvocationMatcher.parse("java.util.Collection#size()"); private static final InvocationMatcher LIST_GET = InvocationMatcher.parse("java.util.List#get(int)"); public ForLoopCanBeForeachRule() { super(ASTForStatement.class); } @Override public Object visit(ASTForStatement forLoop, Object data) { final @Nullable ASTStatement init = forLoop.getInit(); final @Nullable ASTStatementExpressionList update = forLoop.getUpdate(); final ASTExpression guardCondition = forLoop.getCondition(); if (init == null && update == null || guardCondition == null) { return data; } // checked to be either Iterator or int ASTVariableDeclaratorId index = getIndexVarDeclaration(init, update); if (index == null) { return data; } if (index.getTypeMirror().isPrimitive(INT)) { ASTNamedReferenceExpr iterable = findIterableFromCondition(guardCondition, index); if (iterable != null) { if (isReplaceableArrayLoop(forLoop, index, iterable) || isReplaceableListLoop(forLoop, index, iterable)) { addViolation(data, forLoop); } } } else if (TypeTestUtil.isA(Iterator.class, index.getTypeMirror())) { if (isReplaceableIteratorLoop(index, forLoop)) { addViolation(data, forLoop); } return data; } return data; } /** Finds the declaration of the index variable and its occurrences, null to abort */ private @Nullable ASTVariableDeclaratorId getIndexVarDeclaration(@Nullable ASTStatement init, ASTStatementExpressionList update) { if (init == null) { return guessIndexVarFromUpdate(update); } else if (init instanceof ASTLocalVariableDeclaration) { NodeStream<ASTVariableDeclaratorId> varIds = ((ASTLocalVariableDeclaration) init).getVarIds(); if (varIds.count() == 1) { ASTVariableDeclaratorId first = varIds.firstOrThrow(); if (ITERATOR_CALL.matchesCall(first.getInitializer()) || JavaAstUtils.isLiteralInt(first.getInitializer(), 0)) { return first; } } } return null; } /** * @return the variable name if there's only one update statement of the form i++ or ++i. */ private @Nullable ASTVariableDeclaratorId guessIndexVarFromUpdate(ASTStatementExpressionList update) { return NodeStream.of(update) .filter(it -> it.getNumChildren() == 1) .firstChild(ASTUnaryExpression.class) .map(this::asIPlusPlus) .first(); } private @Nullable ASTVariableDeclaratorId asIPlusPlus(ASTExpression update) { return NodeStream.of(update) .filterIs(ASTUnaryExpression.class) .filter(it -> it.getOperator().isIncrement()) .map(ASTUnaryExpression::getOperand) .filterIs(ASTVariableAccess.class) .firstOpt() .map(ASTNamedReferenceExpr::getReferencedSym) .map(JVariableSymbol::tryGetNode) .orElse(null); } /** * Gets the name of the iterable array or list. The condition has the form i < arr.length or i < coll.size() * * @param indexVar The index variable * * @return The name, or null if it couldn't be found or the guard condition is not safe to refactor (then abort) */ private @Nullable ASTNamedReferenceExpr findIterableFromCondition(ASTExpression guardCondition, ASTVariableDeclaratorId indexVar) { if (!JavaAstUtils.isInfixExprWithOperator(guardCondition, BinaryOp.COMPARISON_OPS)) { return null; } ASTInfixExpression condition = (ASTInfixExpression) guardCondition; BinaryOp op = condition.getOperator(); if (!JavaAstUtils.isReferenceToVar(condition.getLeftOperand(), indexVar.getSymbol())) { return null; } NodeStream<ASTExpression> rhs = empty(); if (op == BinaryOp.LT) { // i < rhs rhs = NodeStream.of(condition.getRightOperand()); } else if (op == BinaryOp.LE) { // i <= rhs - 1 rhs = NodeStream.of(condition.getRightOperand()) .filterIs(ASTInfixExpression.class) .filter(it -> it.getOperator() == BinaryOp.SUB) .filter(it -> JavaAstUtils.isLiteralInt(it.getRightOperand(), 1)) .map(ASTInfixExpression::getLeftOperand); } if (rhs.isEmpty()) { return null; } ASTExpression sizeExpr = rhs.get(0); ASTExpression iterableExpr = null; if (sizeExpr instanceof ASTFieldAccess && "length".equals(((ASTFieldAccess) sizeExpr).getName())) { iterableExpr = ((ASTFieldAccess) sizeExpr).getQualifier(); } else if (COLLECTION_SIZE.matchesCall(sizeExpr)) { iterableExpr = ((ASTMethodCall) sizeExpr).getQualifier(); } if (!(iterableExpr instanceof ASTNamedReferenceExpr) || ((ASTNamedReferenceExpr) iterableExpr).getReferencedSym() == null) { return null; } return (ASTNamedReferenceExpr) iterableExpr; } private boolean isReplaceableArrayLoop(ASTForStatement loop, ASTVariableDeclaratorId index, ASTNamedReferenceExpr arrayDeclaration) { return arrayDeclaration.getTypeMirror().isArray() && occurrencesMatch(loop, index, arrayDeclaration, (i, iterable, expr) -> isArrayAccessIndex(expr, iterable)); } private boolean isReplaceableListLoop(ASTForStatement loop, ASTVariableDeclaratorId index, ASTNamedReferenceExpr listDeclaration) { return TypeTestUtil.isA(List.class, listDeclaration.getTypeMirror()) && occurrencesMatch(loop, index, listDeclaration, (i, iterable, expr) -> isListGetIndex(expr, iterable)); } private boolean isArrayAccessIndex(ASTNamedReferenceExpr usage, ASTNamedReferenceExpr arrayVar) { if (!(usage.getParent() instanceof ASTArrayAccess)) { return false; } ASTArrayAccess arrayAccess = (ASTArrayAccess) usage.getParent(); return arrayAccess.getAccessType() == AccessType.READ && JavaAstUtils.isReferenceToSameVar(arrayAccess.getQualifier(), arrayVar); } private boolean isListGetIndex(ASTNamedReferenceExpr usage, ASTNamedReferenceExpr listVar) { return usage.getParent() instanceof ASTArgumentList && LIST_GET.matchesCall(usage.getParent().getParent()) && JavaAstUtils.isReferenceToSameVar(((ASTMethodCall) usage.getParent().getParent()).getQualifier(), listVar); } private interface OccurrenceMatcher { boolean matches(ASTVariableDeclaratorId index, ASTNamedReferenceExpr iterable, ASTNamedReferenceExpr indexOcc1); } private boolean occurrencesMatch(ASTForStatement loop, ASTVariableDeclaratorId index, ASTNamedReferenceExpr collection, OccurrenceMatcher getMatcher) { for (ASTNamedReferenceExpr usage : index.getLocalUsages()) { ASTExpression toplevel = JavaAstUtils.getTopLevelExpr(usage); boolean isInUpdateOrCond = loop.getUpdate() == toplevel.getParent() || loop.getCondition() == toplevel; if (!isInUpdateOrCond && !getMatcher.matches(index, collection, usage)) { return false; } } return true; } private static boolean isReplaceableIteratorLoop(ASTVariableDeclaratorId var, ASTForStatement stmt) { List<ASTNamedReferenceExpr> usages = var.getLocalUsages(); if (usages.size() != 2) { return false; } ASTNamedReferenceExpr u1 = usages.get(0); ASTNamedReferenceExpr u2 = usages.get(1); return isHasNextInCondition(u1, stmt) && isNextInLoop(u2, stmt) || isNextInLoop(u1, stmt) && isHasNextInCondition(u2, stmt); } private static boolean isNextInLoop(ASTNamedReferenceExpr u1, ASTForStatement stmt) { return ITERATOR_NEXT.matchesCall(u1.getParent()) && u1.ancestors().any(it -> it == stmt); } private static boolean isHasNextInCondition(ASTNamedReferenceExpr u1, ASTForStatement forStmt) { return forStmt.getCondition() == u1.getParent() && ITERATOR_HAS_NEXT.matchesCall(u1.getParent()); } }
11,298
41.318352
135
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UseTryWithResourcesRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.util.List; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFinallyClause; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTTryStatement; import net.sourceforge.pmd.lang.java.ast.ASTTypeExpression; import net.sourceforge.pmd.lang.java.ast.TypeNode; 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; public final class UseTryWithResourcesRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<List<String>> CLOSE_METHODS = stringListProperty("closeMethods") .desc("Method names in finally block, which trigger this rule") .defaultValues("close", "closeQuietly") .delim(',') .build(); public UseTryWithResourcesRule() { super(ASTTryStatement.class); definePropertyDescriptor(CLOSE_METHODS); } @Override public Object visit(ASTTryStatement node, Object data) { boolean isJava9OrLater = node.getLanguageVersion().compareToVersion("9") >= 0; ASTFinallyClause finallyClause = node.getFinallyClause(); if (finallyClause != null) { List<ASTMethodCall> methods = finallyClause.descendants(ASTMethodCall.class) .filter(m -> getProperty(CLOSE_METHODS).contains(m.getMethodName())) .toList(); for (ASTMethodCall method : methods) { ASTExpression closeTarget = method.getQualifier(); if (!(closeTarget instanceof ASTTypeExpression) // ignore static method calls && TypeTestUtil.isA(AutoCloseable.class, closeTarget) && (isJava9OrLater || JavaAstUtils.isReferenceToLocal(closeTarget)) || hasAutoClosableArguments(method)) { addViolation(data, node); break; // only report the first closeable } } } return data; } private boolean hasAutoClosableArguments(ASTMethodCall method) { return method.getArguments().children() .filter(e -> TypeTestUtil.isA(AutoCloseable.class, (TypeNode) e)) .nonEmpty(); } }
2,709
40.692308
93
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/PreserveStackTraceRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.util.HashSet; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTInitializer; import net.sourceforge.pmd.lang.java.ast.ASTList; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.InvocationNode; 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.JavaRuleUtil; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.InvocationMatcher.CompoundInvocationMatcher; public class PreserveStackTraceRule extends AbstractJavaRulechainRule { // todo dfa private static final InvocationMatcher INIT_CAUSE = InvocationMatcher.parse("java.lang.Throwable#initCause(_)"); private static final CompoundInvocationMatcher ALLOWED_GETTERS = InvocationMatcher.parseAll( "java.lang.Throwable#fillInStackTrace()", // returns this "java.lang.reflect.InvocationTargetException#getTargetException()", // allowed, to unwrap reflection frames "java.lang.reflect.InvocationTargetException#getCause()", // this is equivalent to getTargetException, see javadoc // same rationale as for InvocationTargetException "java.security.PrivilegedActionException#getException()", "java.security.PrivilegedActionException#getCause()" ); private final Set<ASTVariableDeclaratorId> recursingOnVars = new HashSet<>(); public PreserveStackTraceRule() { super(ASTCatchClause.class); } @Override public Object visit(ASTCatchClause catchStmt, Object data) { ASTVariableDeclaratorId exceptionParam = catchStmt.getParameter().getVarId(); if (JavaRuleUtil.isExplicitUnusedVarName(exceptionParam.getName())) { // ignore those return null; } // Inspect all the throw stmt inside the catch stmt for (ASTThrowStatement throwStatement : catchStmt.getBody().descendants(ASTThrowStatement.class)) { ASTExpression thrownExpr = throwStatement.getExpr(); if (!exprConsumesException(exceptionParam, thrownExpr, true)) { addViolation(data, thrownExpr, exceptionParam.getName()); } } recursingOnVars.clear(); return null; } private boolean exprConsumesException(ASTVariableDeclaratorId exceptionParam, ASTExpression expr, boolean mayBeSelf) { if (expr instanceof ASTConstructorCall) { // new Exception(e) return ctorConsumesException(exceptionParam, (ASTConstructorCall) expr); } else if (expr instanceof ASTMethodCall) { return methodConsumesException(exceptionParam, (ASTMethodCall) expr); } else if (expr instanceof ASTCastExpression) { ASTExpression innermost = JavaAstUtils.peelCasts(expr); return exprConsumesException(exceptionParam, innermost, mayBeSelf); } else if (expr instanceof ASTConditionalExpression) { ASTConditionalExpression ternary = (ASTConditionalExpression) expr; return exprConsumesException(exceptionParam, ternary.getThenBranch(), mayBeSelf) && exprConsumesException(exceptionParam, ternary.getElseBranch(), mayBeSelf); } else if (expr instanceof ASTVariableAccess) { JVariableSymbol referencedSym = ((ASTVariableAccess) expr).getReferencedSym(); if (referencedSym == null) { return true; // invalid code, avoid FP } ASTVariableDeclaratorId decl = referencedSym.tryGetNode(); if (decl == exceptionParam) { return mayBeSelf; } else if (decl == null || decl.isFormalParameter() || decl.isField()) { return false; } if (!this.recursingOnVars.add(decl)) { // already recursing on this variable, avoid stackoverflow return false; } // if any of the initializer and usages consumes the variable, // answer true. if (exprConsumesException(exceptionParam, decl.getInitializer(), mayBeSelf)) { return true; } for (ASTNamedReferenceExpr usage : decl.getLocalUsages()) { if (assignmentRhsConsumesException(exceptionParam, decl, usage)) { return true; } if (JavaAstUtils.followingCallChain(usage).any(it -> consumesExceptionNonRecursive(exceptionParam, it))) { return true; } } return false; } else { // assume it doesn't return false; } } private boolean assignmentRhsConsumesException(ASTVariableDeclaratorId exceptionParam, ASTVariableDeclaratorId lhsVariable, ASTNamedReferenceExpr usage) { if (usage.getIndexInParent() == 0) { ASTExpression assignmentRhs = JavaAstUtils.getOtherOperandIfInAssignmentExpr(usage); boolean rhsIsSelfReferential = NodeStream.of(assignmentRhs) .descendantsOrSelf() .filterIs(ASTVariableAccess.class) .any(it -> JavaAstUtils.isReferenceToVar(it, lhsVariable.getSymbol())); return !rhsIsSelfReferential && exprConsumesException(exceptionParam, assignmentRhs, true); } return false; } private boolean ctorConsumesException(ASTVariableDeclaratorId exceptionParam, ASTConstructorCall ctorCall) { return ctorCall.isAnonymousClass() && callsInitCauseInAnonInitializer(exceptionParam, ctorCall) || anArgumentConsumesException(exceptionParam, ctorCall); } private boolean consumesExceptionNonRecursive(ASTVariableDeclaratorId exceptionParam, ASTExpression expr) { if (expr instanceof ASTConstructorCall) { return ctorConsumesException(exceptionParam, (ASTConstructorCall) expr); } return expr instanceof InvocationNode && anArgumentConsumesException(exceptionParam, (InvocationNode) expr); } private boolean methodConsumesException(ASTVariableDeclaratorId exceptionParam, ASTMethodCall call) { if (anArgumentConsumesException(exceptionParam, call)) { return true; } ASTExpression qualifier = call.getQualifier(); if (qualifier == null) { return false; } boolean mayBeSelf = ALLOWED_GETTERS.anyMatch(call); return exprConsumesException(exceptionParam, qualifier, mayBeSelf); } private boolean callsInitCauseInAnonInitializer(ASTVariableDeclaratorId exceptionParam, ASTConstructorCall ctorCall) { return NodeStream.of(ctorCall.getAnonymousClassDeclaration()) .flatMap(ASTAnyTypeDeclaration::getDeclarations) .map(NodeStream.asInstanceOf(ASTFieldDeclaration.class, ASTInitializer.class)) .descendants().filterIs(ASTMethodCall.class) .any(it -> isInitCauseWithTargetInArg(exceptionParam, it)); } private boolean isInitCauseWithTargetInArg(ASTVariableDeclaratorId exceptionSym, JavaNode expr) { return INIT_CAUSE.matchesCall(expr) && anArgumentConsumesException(exceptionSym, (ASTMethodCall) expr); } private boolean anArgumentConsumesException(@NonNull ASTVariableDeclaratorId exceptionParam, InvocationNode thrownExpr) { for (ASTExpression arg : ASTList.orEmptyStream(thrownExpr.getArguments())) { if (exprConsumesException(exceptionParam, arg, true)) { return true; } } return false; } }
8,853
44.173469
158
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/LooseCouplingRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.util.Collection; import java.util.List; import java.util.Map; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTArrayAllocation; import net.sourceforge.pmd.lang.java.ast.ASTArrayType; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTClassLiteral; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExtendsList; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTModuleProvidesDirective; import net.sourceforge.pmd.lang.java.ast.ASTSuperExpression; import net.sourceforge.pmd.lang.java.ast.ASTThisExpression; import net.sourceforge.pmd.lang.java.ast.ASTTypeExpression; import net.sourceforge.pmd.lang.java.ast.JavaNode; 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; public class LooseCouplingRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<List<String>> ALLOWED_TYPES = PropertyFactory.stringListProperty("allowedTypes") .desc("Exceptions to the rule") .defaultValues("java.util.Properties") .build(); public LooseCouplingRule() { super(ASTClassOrInterfaceType.class); definePropertyDescriptor(ALLOWED_TYPES); } @Override public Object visit(ASTClassOrInterfaceType node, Object data) { if (isConcreteCollectionType(node) && !isInOverriddenMethodSignature(node) && !isInAllowedSyntacticCtx(node) && !isAllowedType(node) && !isTypeParameter(node)) { addViolation(data, node, node.getSimpleName()); } return null; } private boolean isInAllowedSyntacticCtx(ASTClassOrInterfaceType node) { JavaNode parent = node.getParent(); return parent instanceof ASTConstructorCall // new ArrayList<>() || parent instanceof ASTTypeExpression // instanceof, method reference || parent instanceof ASTCastExpression // if we allow instanceof, we should allow cast || parent instanceof ASTClassLiteral // ArrayList.class || parent instanceof ASTClassOrInterfaceType // AbstractMap.SimpleEntry || parent instanceof ASTExtendsList // extends AbstractMap<...> || parent instanceof ASTThisExpression // Enclosing.this || parent instanceof ASTSuperExpression // Enclosing.super || parent instanceof ASTModuleProvidesDirective // provides <interface> with <implementation> || parent instanceof ASTArrayType && parent.getParent() instanceof ASTArrayAllocation; } private boolean isAllowedType(ASTClassOrInterfaceType node) { for (String allowed : getProperty(ALLOWED_TYPES)) { if (TypeTestUtil.isA(allowed, node)) { return true; } } return false; } private boolean isConcreteCollectionType(ASTClassOrInterfaceType node) { return (TypeTestUtil.isA(Collection.class, node) || TypeTestUtil.isA(Map.class, node)) && !node.getTypeMirror().isInterface(); } private static boolean isInOverriddenMethodSignature(JavaNode node) { JavaNode ancestor = node.ancestors().map(NodeStream.asInstanceOf(ASTMethodDeclaration.class, ASTBlock.class)).first(); // when it's in a signature and not the body return ancestor instanceof ASTMethodDeclaration && ((ASTMethodDeclaration) ancestor).isOverridden(); } private boolean isTypeParameter(ASTClassOrInterfaceType node) { return node.getTypeMirror().isTypeVariable(); } }
4,222
43.452632
126
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/JUnitTestsShouldIncludeAssertRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; 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 JUnitTestsShouldIncludeAssertRule extends AbstractJavaRulechainRule { public JUnitTestsShouldIncludeAssertRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration method, Object data) { ASTBlock body = method.getBody(); if (body != null && TestFrameworksUtil.isTestMethod(method) && !TestFrameworksUtil.isExpectAnnotated(method) && body.descendants(ASTMethodCall.class) .none(TestFrameworksUtil::isProbableAssertCall)) { addViolation(data, method); } return data; } }
1,110
32.666667
82
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/GuardLogStatementRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; 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.ASTMethodReference; 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.ast.BinaryOp; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Check that log.debug, log.trace, log.error, etc... statements are guarded by * some test expression on log.isDebugEnabled() or log.isTraceEnabled(). * * @author Romain Pelisse - &lt;belaran@gmail.com&gt; * @author Heiko Rupp - &lt;hwr@pilhuhn.de&gt; * @author Tammo van Lessen - provided original XPath expression * */ public class GuardLogStatementRule extends AbstractJavaRulechainRule { /* * guard methods and log levels: * * log4j + apache commons logging (jakarta): * trace -> isTraceEnabled * debug -> isDebugEnabled * info -> isInfoEnabled * warn -> isWarnEnabled * error -> isErrorEnabled * * * java util: * log(Level.FINE) -> isLoggable * finest -> isLoggable * finer -> isLoggable * fine -> isLoggable * info -> isLoggable * warning -> isLoggable * severe -> isLoggable */ private static final PropertyDescriptor<List<String>> LOG_LEVELS = stringListProperty("logLevels") .desc("LogLevels to guard") .defaultValues("trace", "debug", "info", "warn", "error", "log", "finest", "finer", "fine", "info", "warning", "severe") .delim(',') .build(); private static final PropertyDescriptor<List<String>> GUARD_METHODS = stringListProperty("guardsMethods") .desc("Method use to guard the log statement") .defaultValues("isTraceEnabled", "isDebugEnabled", "isInfoEnabled", "isWarnEnabled", "isErrorEnabled", "isLoggable") .delim(',').build(); private final Map<String, String> guardStmtByLogLevel = new HashMap<>(12); /* * java util methods, that need special handling, e.g. they require an argument, which * determines the log level */ private static final String JAVA_UTIL_LOG_METHOD = "log"; private static final String JAVA_UTIL_LOG_GUARD_METHOD = "isLoggable"; public GuardLogStatementRule() { super(ASTExpressionStatement.class); definePropertyDescriptor(LOG_LEVELS); definePropertyDescriptor(GUARD_METHODS); } @Override public void start(RuleContext ctx) { extractProperties(); } @Override public Object visit(ASTExpressionStatement node, Object data) { ASTExpression expr = node.getExpr(); if (!(expr instanceof ASTMethodCall)) { return null; } ASTMethodCall methodCall = (ASTMethodCall) expr; String logLevel = getLogLevelName(methodCall); if (logLevel != null && guardStmtByLogLevel.containsKey(logLevel)) { if (needsGuard(methodCall) && !hasGuard(methodCall, logLevel)) { addViolation(data, node); } } return null; } private boolean needsGuard(ASTMethodCall node) { if (node.getArguments().size() == 0) { return false; } ASTArgumentList argumentList = node.getArguments(); for (ASTExpression child : argumentList) { if (child.descendantsOrSelf() .filterIs(ASTInfixExpression.class) .filter(n -> n.getOperator() == BinaryOp.ADD) .nonEmpty() && TypeTestUtil.isA(String.class, child)) { // only consider the first String argument - which is the log message - and return here return !isConstantStringExpression(child); } } return true; } private boolean isConstantStringExpression(ASTExpression expr) { if (expr == null) { return false; } if (expr instanceof ASTStringLiteral) { return true; } if (expr instanceof ASTVariableAccess) { ASTVariableAccess var = (ASTVariableAccess) expr; if (var.isCompileTimeConstant()) { return true; } JVariableSymbol symbol = var.getReferencedSym(); if (symbol == null) { return false; } if (!var.getReferencedSym().isFinal()) { return false; } @Nullable ASTVariableDeclaratorId declaratorId = symbol.tryGetNode(); if (declaratorId != null) { return isConstantStringExpression(declaratorId.getInitializer()); } } if (expr instanceof ASTInfixExpression) { ASTInfixExpression infix = (ASTInfixExpression) expr; if (isConstantStringExpression(infix.getLeftOperand()) && isConstantStringExpression(infix.getRightOperand())) { return true; } } return false; } private boolean hasGuard(ASTMethodCall node, String logLevel) { ASTIfStatement ifStatement = node.ancestors(ASTIfStatement.class).first(); if (ifStatement == null) { return false; } for (ASTMethodCall maybeAGuardCall : ifStatement.getCondition().descendantsOrSelf().filterIs(ASTMethodCall.class)) { String guardMethodName = maybeAGuardCall.getMethodName(); // the guard is adapted to the actual log statement if (!guardStmtByLogLevel.get(logLevel).contains(guardMethodName)) { continue; } if (JAVA_UTIL_LOG_GUARD_METHOD.equals(guardMethodName)) { // java.util.logging: guard method with argument. Verify the log level if (logLevel.equals(getJutilLogLevelInFirstArg(maybeAGuardCall))) { return true; } } else { return true; } } return false; } /** * Determines the log level, that is used. It is either the called method name * itself or - in case java util logging is used, then it is the first argument of * the method call (if it exists). * * @param methodCall the method call * * @return the log level or <code>null</code> if it could not be determined */ private @Nullable String getLogLevelName(ASTMethodCall methodCall) { String methodName = methodCall.getMethodName(); if (!JAVA_UTIL_LOG_METHOD.equals(methodName)) { if (isUnguardedAccessOk(methodCall, 0)) { return null; } return methodName; // probably logger.warn(...) } // else it's java.util.logging, eg // LOGGER.log(Level.FINE, "m") if (isUnguardedAccessOk(methodCall, 1)) { return null; } return getJutilLogLevelInFirstArg(methodCall); } private @Nullable String getJutilLogLevelInFirstArg(ASTMethodCall methodCall) { ASTExpression firstArg = methodCall.getArguments().toStream().get(0); if (TypeTestUtil.isA("java.util.logging.Level", firstArg) && firstArg instanceof ASTNamedReferenceExpr) { return ((ASTNamedReferenceExpr) firstArg).getName().toLowerCase(Locale.ROOT); } return null; } private boolean isUnguardedAccessOk(ASTMethodCall call, int messageArgIndex) { // return true if the statement has limited overhead even if unguarded, // so that we can ignore it return call.getArguments().toStream() .drop(messageArgIndex) // remove the level argument if needed .all(it -> it instanceof ASTStringLiteral || it instanceof ASTLambdaExpression || it instanceof ASTVariableAccess || it instanceof ASTMethodReference); } private void extractProperties() { if (guardStmtByLogLevel.isEmpty()) { List<String> logLevels = new ArrayList<>(super.getProperty(LOG_LEVELS)); List<String> guardMethods = new ArrayList<>(super.getProperty(GUARD_METHODS)); if (guardMethods.isEmpty() && !logLevels.isEmpty()) { throw new IllegalArgumentException("Can't specify logLevels without specifying guardMethods."); } if (logLevels.size() > guardMethods.size()) { // reuse the last guardMethod for the remaining log levels int needed = logLevels.size() - guardMethods.size(); String lastGuard = guardMethods.get(guardMethods.size() - 1); for (int i = 0; i < needed; i++) { guardMethods.add(lastGuard); } } if (logLevels.size() != guardMethods.size()) { throw new IllegalArgumentException("For each logLevel a guardMethod must be specified."); } buildGuardStatementMap(logLevels, guardMethods); } } private void buildGuardStatementMap(List<String> logLevels, List<String> guardMethods) { for (int i = 0; i < logLevels.size(); i++) { String logLevel = logLevels.get(i); if (guardStmtByLogLevel.containsKey(logLevel)) { String combinedGuard = guardStmtByLogLevel.get(logLevel); combinedGuard += "|" + guardMethods.get(i); guardStmtByLogLevel.put(logLevel, combinedGuard); } else { guardStmtByLogLevel.put(logLevel, guardMethods.get(i)); } } } }
10,891
37.624113
170
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UnusedPrivateMethodRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodReference; import net.sourceforge.pmd.lang.java.ast.ASTModifierList; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.MethodUsage; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.AbstractIgnoredAnnotationRule; import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.util.CollectionUtil; /** * This rule detects private methods, that are not used and can therefore be * deleted. */ public class UnusedPrivateMethodRule extends AbstractIgnoredAnnotationRule { private static final Set<String> SERIALIZATION_METHODS = setOf("readObject", "writeObject", "readResolve", "writeReplace"); @Override protected Collection<String> defaultSuppressionAnnotations() { return Collections.singletonList("java.lang.Deprecated"); } @Override public Object visit(ASTCompilationUnit file, Object param) { // We do three traversals: // - one to find methods referenced by Junit5 MethodSource annotations // - one to find the "interesting methods", ie those that may be violations // - another to find the possible usages. We only try to resolve // method calls/method refs that may refer to a method in the // first set, ie, not every call in the file. Set<String> methodsUsedByAnnotations = file.descendants(ASTMethodDeclaration.class) .children(ASTModifierList.class) .children(ASTAnnotation.class) .filter(t -> TypeTestUtil.isA("org.junit.jupiter.params.provider.MethodSource", t)) .descendants(ASTStringLiteral.class) .toStream() .map(ASTStringLiteral::getConstValue) .collect(Collectors.toSet()); Map<String, Set<ASTMethodDeclaration>> consideredNames = file.descendants(ASTMethodDeclaration.class) .crossFindBoundaries() // get methods whose usages are all in this file // TODO we could use getEffectiveVisibility here, but we need to consider overrides then. .filter(it -> it.getVisibility() == Visibility.V_PRIVATE) .filter(it -> !hasIgnoredAnnotation(it) && !hasExcludedName(it) && !(it.getArity() == 0 && methodsUsedByAnnotations.contains(it.getName()))) .toStream() .collect(Collectors.groupingBy(ASTMethodDeclaration::getName, HashMap::new, CollectionUtil.toMutableSet())); file.descendants() .crossFindBoundaries() .map(NodeStream.<MethodUsage>asInstanceOf(ASTMethodCall.class, ASTMethodReference.class)) .forEach(ref -> { String methodName = ref.getMethodName(); // the considered names might be mutated during the traversal if (!consideredNames.containsKey(methodName)) { return; } JExecutableSymbol sym; if (ref instanceof ASTMethodCall) { sym = ((ASTMethodCall) ref).getMethodType().getSymbol(); } else if (ref instanceof ASTMethodReference) { sym = ((ASTMethodReference) ref).getReferencedMethod().getSymbol(); } else { return; } JavaNode reffed = sym.tryGetNode(); if (reffed instanceof ASTMethodDeclaration && ref.ancestors(ASTMethodDeclaration.class).first() != reffed) { // remove from set, but only if it is called outside of itself Set<ASTMethodDeclaration> remainingUnused = consideredNames.get(methodName); if (remainingUnused != null && remainingUnused.remove(reffed) // note: side-effect && remainingUnused.isEmpty()) { consideredNames.remove(methodName); // clear this name } } }); // those that remain are unused consideredNames.forEach((name, unused) -> { for (ASTMethodDeclaration m : unused) { addViolation(param, m, PrettyPrintingUtil.displaySignature(m)); } }); return null; } private boolean hasExcludedName(ASTMethodDeclaration node) { return SERIALIZATION_METHODS.contains(node.getName()); } }
5,414
43.385246
124
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/UnusedPrivateFieldRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.util.ArrayList; import java.util.List; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; 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.JavaNode; 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; public class UnusedPrivateFieldRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<List<String>> IGNORED_FIELD_NAMES = PropertyFactory.stringListProperty("ignoredFieldNames") .defaultValues("serialVersionUID", "serialPersistentFields") .desc("Field Names that are ignored from the unused check") .build(); private static final PropertyDescriptor<List<String>> REPORT_FOR_ANNOTATIONS_DESCRIPTOR = PropertyFactory.stringListProperty("reportForAnnotations") .desc("Fully qualified names of the annotation types that should be reported anyway. If an unused field " + "has any of these annotations, then it is reported. If it has any other annotation, then " + "it is still considered to used and is not reported.") .defaultValue(new ArrayList<>()) .build(); public UnusedPrivateFieldRule() { super(ASTAnyTypeDeclaration.class); definePropertyDescriptor(IGNORED_FIELD_NAMES); definePropertyDescriptor(REPORT_FOR_ANNOTATIONS_DESCRIPTOR); } @Override public Object visitJavaNode(JavaNode node, Object data) { if (node instanceof ASTAnyTypeDeclaration) { ASTAnyTypeDeclaration type = (ASTAnyTypeDeclaration) node; if (hasAnyAnnotation(type)) { return null; } for (ASTFieldDeclaration field : type.getDeclarations().filterIs(ASTFieldDeclaration.class)) { if (!isIgnored(field)) { for (ASTVariableDeclaratorId varId : field.getVarIds()) { if (JavaAstUtils.isNeverUsed(varId)) { addViolation(data, varId, varId.getName()); } } } } } return null; } private boolean isIgnored(ASTFieldDeclaration field) { return field.getVisibility() != Visibility.V_PRIVATE || isOK(field) || hasAnyAnnotation(field); } private boolean isOK(ASTFieldDeclaration field) { return field.getVarIds().any(it -> getProperty(IGNORED_FIELD_NAMES).contains(it.getName())); } private boolean hasAnyAnnotation(Annotatable node) { NodeStream<ASTAnnotation> declaredAnnotations = node.getDeclaredAnnotations(); for (String reportAnnotation : getProperty(REPORT_FOR_ANNOTATIONS_DESCRIPTOR)) { for (ASTAnnotation annotation: declaredAnnotations) { if (TypeTestUtil.isA(reportAnnotation, annotation)) { return false; } } } return !declaredAnnotations.isEmpty(); } }
3,757
41.224719
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/MethodReturnsInternalArrayRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.lang.reflect.Modifier; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTArrayAllocation; import net.sourceforge.pmd.lang.java.ast.ASTArrayDimExpr; import net.sourceforge.pmd.lang.java.ast.ASTArrayInitializer; import net.sourceforge.pmd.lang.java.ast.ASTArrayTypeDim; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; /** * Implementation note: this rule currently ignores return types of y.x.z, * currently it handles only local type fields. Created on Jan 17, 2005 */ public class MethodReturnsInternalArrayRule extends AbstractJavaRulechainRule { public MethodReturnsInternalArrayRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration method, Object data) { if (!method.getResultTypeNode().getTypeMirror().isArray() || method.getVisibility() == Visibility.V_PRIVATE) { return data; } for (ASTReturnStatement returnStmt : method.descendants(ASTReturnStatement.class)) { ASTExpression expr = returnStmt.getExpr(); if (expr instanceof ASTNamedReferenceExpr) { ASTNamedReferenceExpr reference = (ASTNamedReferenceExpr) expr; if (JavaAstUtils.isRefToFieldOfThisInstance(reference)) { addViolation(data, returnStmt, reference.getName()); } else { // considers static, non-final fields JVariableSymbol symbol = reference.getReferencedSym(); if (symbol instanceof JFieldSymbol) { JFieldSymbol field = (JFieldSymbol) symbol; if (field.isStatic() && isInternal(field) && !isZeroLengthArrayConstant(field)) { addViolation(data, returnStmt, reference.getName()); } } } } } return data; } private static boolean isInternal(JFieldSymbol field) { return !Modifier.isPublic(field.getModifiers()) // not public && !field.isUnresolved(); // must be resolved to avoid FPs } private static boolean isZeroLengthArrayConstant(JFieldSymbol sym) { return sym.isFinal() && NodeStream.of(sym.tryGetNode()) .map(ASTVariableDeclaratorId::getInitializer) .filter(MethodReturnsInternalArrayRule::isZeroLengthArrayExpr) .nonEmpty(); } private static boolean isZeroLengthArrayExpr(ASTExpression expr) { if (expr instanceof ASTArrayInitializer) { // {} return ((ASTArrayInitializer) expr).length() == 0; } else if (expr instanceof ASTArrayAllocation) { ASTArrayInitializer init = ((ASTArrayAllocation) expr).getArrayInitializer(); if (init != null) { // new int[] {} return init.length() == 0; } else { // new int[0] ASTArrayTypeDim lastChild = ((ASTArrayAllocation) expr).getTypeNode().getDimensions().getLastChild(); if (lastChild instanceof ASTArrayDimExpr) { return JavaAstUtils.isLiteralInt(((ASTArrayDimExpr) lastChild).getLengthExpression(), 0); } } } return false; } }
4,154
41.835052
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/ArrayIsStoredDirectlyRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; 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.ASTAssignableExpr.AccessType; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; 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.internal.JavaAstUtils; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * If a method or constructor receives an array as an argument, the array should * be cloned instead of directly stored. This prevents future changes from the * user from affecting the original array. */ public class ArrayIsStoredDirectlyRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> ALLOW_PRIVATE = PropertyFactory.booleanProperty("allowPrivate") .defaultValue(true) .desc("If true, allow private methods/constructors to store arrays directly") .build(); public ArrayIsStoredDirectlyRule() { super(ASTMethodDeclaration.class, ASTConstructorDeclaration.class); definePropertyDescriptor(ALLOW_PRIVATE); } @Override public Object visit(ASTConstructorDeclaration node, Object data) { checkAssignments((RuleContext) data, node); return data; } @Override public Object visit(ASTMethodDeclaration node, Object data) { checkAssignments((RuleContext) data, node); return data; } private void checkAssignments(RuleContext context, ASTMethodOrConstructorDeclaration method) { if (method.getVisibility() == Visibility.V_PRIVATE && getProperty(ALLOW_PRIVATE) || method.getBody() == null) { return; } nextFormal: for (ASTFormalParameter formal : method.getFormalParameters()) { if (formal.getTypeMirror().isArray()) { for (ASTNamedReferenceExpr usage : formal.getVarId().getLocalUsages()) { // We assume usages order corresponds to control-flow order // This may not hold, but it's as precise as the rule was before 7.0 if (usage.getAccessType() == AccessType.WRITE) { continue nextFormal; // variable is overwritten } // the RHS of an assignment if (usage.getParent() instanceof ASTAssignmentExpression && usage.getIndexInParent() == 1) { ASTAssignableExpr assigned = ((ASTAssignmentExpression) usage.getParent()).getLeftOperand(); if (JavaAstUtils.isRefToFieldOfThisInstance(assigned)) { addViolation(context, usage.getParent(), usage.getName()); } } } } } } }
3,508
42.320988
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AccessorMethodGenerationRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Objects; import java.util.Set; import net.sourceforge.pmd.RuleContext; 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.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JAccessibleElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JMethodSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.rule.AbstractRule; public class AccessorMethodGenerationRule extends AbstractJavaRulechainRule { private final Set<JavaNode> reportedNodes = new HashSet<>(); public AccessorMethodGenerationRule() { super(ASTFieldAccess.class, ASTVariableAccess.class, ASTMethodCall.class); } @Override public void end(RuleContext ctx) { super.end(ctx); reportedNodes.clear(); } @Override public Object visit(ASTFieldAccess node, Object data) { JFieldSymbol sym = node.getReferencedSym(); if (sym != null && sym.getConstValue() == null) { checkMemberAccess((RuleContext) data, node, sym); } return null; } @Override public Object visit(ASTVariableAccess node, Object data) { JVariableSymbol sym = node.getReferencedSym(); if (sym instanceof JFieldSymbol) { JFieldSymbol fieldSym = (JFieldSymbol) sym; if (((JFieldSymbol) sym).getConstValue() == null) { checkMemberAccess((RuleContext) data, node, fieldSym); } } return null; } @Override public Object visit(ASTMethodCall node, Object data) { JMethodSymbol symbol = (JMethodSymbol) node.getMethodType().getSymbol(); checkMemberAccess((RuleContext) data, node, symbol); return null; } private void checkMemberAccess(RuleContext data, ASTExpression node, JAccessibleElementSymbol symbol) { checkMemberAccess(this, data, node, symbol, this.reportedNodes); } static void checkMemberAccess(AbstractRule rule, RuleContext data, JavaNode refExpr, JAccessibleElementSymbol sym, Set<JavaNode> reportedNodes) { if (Modifier.isPrivate(sym.getModifiers()) && !Objects.equals(sym.getEnclosingClass(), refExpr.getEnclosingType().getSymbol())) { JavaNode node = sym.tryGetNode(); assert node != null : "Node should be in the same compilation unit"; if (reportedNodes.add(node)) { rule.addViolation(data, node, new String[] {stripPackageName(refExpr.getEnclosingType().getSymbol())}); } } } /** * Returns the canonical name without the package name. Eg for a * canonical name {@code com.github.Outer.Inner}, returns {@code Outer.Inner}. */ private static String stripPackageName(JClassSymbol symbol) { String p = symbol.getPackageName(); String canoName = symbol.getCanonicalName(); if (canoName == null) { return symbol.getSimpleName(); } if (p.isEmpty()) { return canoName; } return canoName.substring(p.length() + 1); //+1 for the dot } }
3,748
36.118812
149
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/AccessorClassGenerationRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.bestpractices; import java.util.HashSet; import java.util.Set; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; /** * 1. Note all private constructors. 2. Note all instantiations from outside of * the class by way of the private constructor. 3. Flag instantiations. * * <p> * Parameter types can not be matched because they can come as exposed members * of classes. In this case we have no way to know what the type is. We can make * a best effort though which can filter some? * </p> * * @author CL Gilbert (dnoyeb@users.sourceforge.net) * @author David Konecny (david.konecny@) * @author Romain PELISSE, belaran@gmail.com, patch bug#1807370 * @author Juan Martin Sotuyo Dodero (juansotuyo@gmail.com), complete rewrite */ public class AccessorClassGenerationRule extends AbstractJavaRulechainRule { private final Set<JavaNode> reportedNodes = new HashSet<>(); public AccessorClassGenerationRule() { super(ASTConstructorCall.class, ASTExplicitConstructorInvocation.class); } @Override public void end(RuleContext ctx) { super.end(ctx); reportedNodes.clear(); } @Override public Object visit(ASTConstructorCall node, Object data) { if (!node.isAnonymousClass()) { AccessorMethodGenerationRule.checkMemberAccess(this, (RuleContext) data, node, node.getMethodType().getSymbol(), this.reportedNodes); } return null; } @Override public Object visit(ASTExplicitConstructorInvocation node, Object data) { if (node.isSuper()) { AccessorMethodGenerationRule.checkMemberAccess(this, (RuleContext) data, node, node.getMethodType().getSymbol(), this.reportedNodes); } return null; } }
2,118
33.737705
145
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/InefficientEmptyStringCheckRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * This rule finds code which inefficiently determines empty strings. * * <p> * <pre> * str.trim().length()==0 * </pre> * or * <pre> * str.trim().isEmpty() * </pre> * (for the same reason) is quite inefficient as trim() causes a new String to * be created. A Smarter code to check for an empty string would be: * * <pre> * private boolean checkTrimEmpty(String str) { * for(int i = 0; i &lt; str.length(); i++) { * if(!Character.isWhitespace(str.charAt(i))) { * return false; * } * } * return true; * } * </pre> * or you can refer to Apache's <code>StringUtils#isBlank</code> * (in commons-lang), Spring's <code>StringUtils#hasText</code> (in the Spring * framework) or Google's <code>CharMatcher#whitespace</code> (in Guava) for * existing implementations (some might include the check for != null). * </p> * * @author acaplan */ public class InefficientEmptyStringCheckRule extends AbstractJavaRulechainRule { public InefficientEmptyStringCheckRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall call, Object data) { if (isTrimCall(call.getQualifier()) && (isLengthZeroCheck(call) || isIsEmptyCall(call))) { addViolation(data, call); } return null; } private static boolean isLengthZeroCheck(ASTMethodCall call) { return "length".equals(call.getMethodName()) && call.getArguments().size() == 0 && JavaRuleUtil.isZeroChecked(call); } private static boolean isTrimCall(ASTExpression expr) { if (expr instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) expr; return "trim".equals(call.getMethodName()) && call.getArguments().size() == 0 && TypeTestUtil.isA(String.class, call.getQualifier()); } return false; } private static boolean isIsEmptyCall(ASTExpression expr) { if (expr instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) expr; return "isEmpty".equals(call.getMethodName()) && call.getArguments().size() == 0; } return false; } }
2,701
30.418605
80
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/InefficientStringBufferingRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; 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.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTList; 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.JavaRuleUtil; /** * How this rule works: find additive expressions: + check that the addition is * between anything other than two literals if true and also the parent is * StringBuffer constructor or append, report a violation. * * @author mgriffa */ public class InefficientStringBufferingRule extends AbstractJavaRulechainRule { public InefficientStringBufferingRule() { super(ASTConstructorCall.class, ASTMethodCall.class); } @Override public Object visit(ASTMethodCall node, Object data) { if (JavaRuleUtil.isStringBuilderCtorOrAppend(node)) { checkArgument(node.getArguments(), (RuleContext) data); } return null; } @Override public Object visit(ASTConstructorCall node, Object data) { if (JavaRuleUtil.isStringBuilderCtorOrAppend(node)) { checkArgument(node.getArguments(), (RuleContext) data); } return null; } private void checkArgument(ASTArgumentList argList, RuleContext ctx) { ASTExpression arg = ASTList.singleOrNull(argList); if (JavaAstUtils.isStringConcatExpr(arg) // ignore concatenations that produce constants && !arg.isCompileTimeConstant()) { addViolation(ctx, arg); } } static boolean isInStringBufferOperationChain(Node node, String append) { // TODO this was replaced by something that doesn't really work // this was/is used by ConsecutiveLiteralAppendsRule if (!(node instanceof ASTExpression)) { return false; } Node parent = node.getParent(); return parent instanceof ASTMethodCall && JavaRuleUtil.isStringBuilderCtorOrAppend((ASTMethodCall) parent); } }
2,451
34.536232
80
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/UseStringBufferForStringAppendsRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import java.util.ArrayList; 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.ASTAssignableExpr.AccessType; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; 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 UseStringBufferForStringAppendsRule extends AbstractJavaRulechainRule { public UseStringBufferForStringAppendsRule() { super(ASTVariableDeclaratorId.class); } /** * This method is used to check whether user appends string directly instead of using StringBuffer or StringBuilder * @param node This is the expression of part of java code to be checked. * @param data This is the data to return. * @return Object This returns the data passed in. If violation happens, violation is added to data. */ @Override public Object visit(ASTVariableDeclaratorId node, Object data) { if (!TypeTestUtil.isA(String.class, node) || node.isForeachVariable()) { return data; } // Remember how often the variable has been used on the right hand side int usageCounter = 0; List<ASTNamedReferenceExpr> possibleViolations = new ArrayList<>(); for (ASTNamedReferenceExpr usage : node.getLocalUsages()) { if ((node.isField() || node.isFormalParameter()) && isNotWithinLoop(usage)) { // ignore if the field or formal parameter is *not* used within loops continue; } boolean isSimpleAssignment = false; if (usage.getParent() instanceof ASTAssignmentExpression) { ASTAssignmentExpression assignment = (ASTAssignmentExpression) usage.getParent(); // it is either a compound (a += x) if (assignment.isCompound()) { usageCounter++; } int usageOnRightHandSide = JavaAstUtils.flattenOperands(assignment.getRightOperand()) .filterIs(ASTNamedReferenceExpr.class) .filterMatching(ASTNamedReferenceExpr::getReferencedSym, node.getSymbol()) .count(); // or maybe a append in some way (a = a + x) // or a combination (a += a + x) usageCounter += usageOnRightHandSide; isSimpleAssignment = !assignment.isCompound() && usageOnRightHandSide == 0; } if (usage.getAccessType() == AccessType.WRITE && !isSimpleAssignment) { if (isWithinLoop(usage)) { // always report appends within a loop addViolation(data, usage); } else { possibleViolations.add(usage); } } } // only report, if it is used more than once // then all usage locations are reported if (usageCounter > 1) { possibleViolations.forEach(v -> addViolation(data, v)); } return data; } private boolean isNotWithinLoop(Node name) { return name.ancestors(ASTLoopStatement.class).isEmpty(); } private boolean isWithinLoop(Node name) { return !isNotWithinLoop(name); } }
3,813
37.918367
119
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/ConsecutiveLiteralAppendsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange; import java.util.HashSet; import java.util.Set; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTDoStatement; import net.sourceforge.pmd.lang.java.ast.ASTExpression; 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.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.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.ASTSwitchArrowBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchFallthroughBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.ASTWhileStatement; import net.sourceforge.pmd.lang.java.ast.InvocationNode; import net.sourceforge.pmd.lang.java.ast.TypeNode; 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.JavaRuleUtil; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * This rule finds concurrent calls to StringBuffer/Builder.append where String * literals are used. It would be much better to make these calls using one call * to <code>.append</code>. * * <p>Example:</p> * * <pre> * StringBuilder buf = new StringBuilder(); * buf.append(&quot;Hello&quot;); * buf.append(&quot; &quot;).append(&quot;World&quot;); * </pre> * * <p>This would be more eloquently put as:</p> * * <pre> * StringBuilder buf = new StringBuilder(); * buf.append(&quot;Hello World&quot;); * </pre> * * <p>The rule takes one parameter, threshold, which defines the lower limit of * consecutive appends before a violation is created. The default is 1.</p> */ public class ConsecutiveLiteralAppendsRule extends AbstractJavaRulechainRule { private static final Set<Class<?>> BLOCK_PARENTS; static { BLOCK_PARENTS = new HashSet<>(); BLOCK_PARENTS.add(ASTForStatement.class); BLOCK_PARENTS.add(ASTForeachStatement.class); BLOCK_PARENTS.add(ASTWhileStatement.class); BLOCK_PARENTS.add(ASTDoStatement.class); BLOCK_PARENTS.add(ASTIfStatement.class); BLOCK_PARENTS.add(ASTSwitchStatement.class); BLOCK_PARENTS.add(ASTMethodDeclaration.class); BLOCK_PARENTS.add(ASTCatchClause.class); BLOCK_PARENTS.add(ASTFinallyClause.class); BLOCK_PARENTS.add(ASTLambdaExpression.class); BLOCK_PARENTS.add(ASTSwitchArrowBranch.class); BLOCK_PARENTS.add(ASTSwitchFallthroughBranch.class); } private static final PropertyDescriptor<Integer> THRESHOLD_DESCRIPTOR = PropertyFactory.intProperty("threshold") .desc("Max consecutive appends") .require(inRange(1, 10)).defaultValue(1).build(); private ConsecutiveCounter counter = new ConsecutiveCounter(); public ConsecutiveLiteralAppendsRule() { super(ASTVariableDeclaratorId.class); definePropertyDescriptor(THRESHOLD_DESCRIPTOR); } @Override public Object visit(ASTVariableDeclaratorId node, Object data) { if (!isStringBuilderOrBuffer(node)) { return data; } counter.initThreshold(getProperty(THRESHOLD_DESCRIPTOR)); counter.reset(); checkConstructor(data, node); Node lastBlock = getFirstParentBlock(node); Node currentBlock = lastBlock; for (ASTNamedReferenceExpr namedReference : node.getLocalUsages()) { currentBlock = getFirstParentBlock(namedReference); // loop through method call chain Node current = namedReference; while (current.getParent() instanceof ASTMethodCall) { ASTMethodCall methodCall = (ASTMethodCall) current.getParent(); current = methodCall; if (JavaRuleUtil.isStringBuilderCtorOrAppend(methodCall)) { // append method call detected // see if it changed blocks if (currentBlock != null && lastBlock != null && !currentBlock.equals(lastBlock) || currentBlock == null ^ lastBlock == null) { checkForViolation(data); counter.reset(); } analyzeInvocation(data, methodCall); lastBlock = currentBlock; } else { // other method calls the stringbuilder variable, e.g. calling delete, toString, etc. checkForViolation(data); counter.reset(); } } if (!(namedReference.getParent() instanceof ASTMethodCall)) { // usage of the stringbuilder variable for any other purpose, e.g. as a argument for // a different method call checkForViolation(data); counter.reset(); } } checkForViolation(data); return data; } /** * Determine if the constructor contains (or ends with) a String Literal. * Also analyzes a possible method call chain for append calls. * * @param node */ private void checkConstructor(Object data, ASTVariableDeclaratorId node) { ASTExpression initializer = node.getInitializer(); if (initializer == null) { return; } ASTConstructorCall constructorCall = initializer.descendantsOrSelf().filterIs(ASTConstructorCall.class).first(); if (constructorCall == null) { return; } analyzeInvocation(data, constructorCall); // analyze chained calls to append Node parent = constructorCall.getParent(); while (parent instanceof ASTMethodCall) { analyzeInvocation(data, (ASTMethodCall) parent); parent = parent.getParent(); } } private void analyzeInvocation(Object data, InvocationNode invocation) { if (!(invocation instanceof ASTExpression)) { return; } if (!JavaRuleUtil.isStringBuilderCtorOrAppend((ASTExpression) invocation)) { return; } if (isAdditive(invocation)) { processAdditive(data, invocation); } else if (isAppendingVariablesOrFields(invocation) || isAppendingInvocationResult(invocation)) { checkForViolation(data); counter.reset(); } else if (invocation.getArguments().getFirstChild() instanceof ASTStringLiteral || invocation instanceof ASTMethodCall) { counter.count(invocation.getArguments().getFirstChild()); } } private void processAdditive(Object data, InvocationNode invocation) { ASTExpression firstArg = invocation.getArguments().getFirstChild(); if (firstArg.descendants(ASTNamedReferenceExpr.class).count() > 0) { // at least one variable/field access found checkForViolation(data); if (firstArg instanceof ASTInfixExpression) { ASTExpression rightOperand = ((ASTInfixExpression) firstArg).getRightOperand(); if (rightOperand instanceof ASTStringLiteral) { // argument ends with ... + "some string" counter.count(rightOperand); } } else { // continue with a fresh round counter.reset(); } } else { // no variables appended, compiler will take care of merging all the // string concats, we really only have 1 then counter.count(invocation.getArguments().getFirstChild()); } } /** * Checks to see if there is string concatenation in the node. * * This method checks if it's additive with respect to the append method * only. * * @param n * Node to check * @return true if the node has an additive expression (i.e. "Hello " + * Const.WORLD) */ private boolean isAdditive(InvocationNode n) { return JavaAstUtils.isStringConcatExpr(n.getArguments().getFirstChild()); } /** * Get the first parent. Keep track of the last node though. For If * statements it's the only way we can differentiate between if's and else's * * @param node The node to check * @return The first parent block */ private Node getFirstParentBlock(Node node) { Node parentNode = node.getParent(); Node lastNode = node; while (parentNode != null && !BLOCK_PARENTS.contains(parentNode.getClass())) { lastNode = parentNode; parentNode = parentNode.getParent(); } if (parentNode instanceof ASTIfStatement) { parentNode = lastNode; } return parentNode; } /** * Helper method checks to see if a violation occurred, and adds a * RuleViolation if it did */ private void checkForViolation(Object data) { if (counter.isViolation()) { assert counter.getReportNode() != null; String[] param = { String.valueOf(counter.getCounter()) }; addViolation(data, counter.getReportNode(), param); } } private boolean isAppendingVariablesOrFields(InvocationNode node) { return node.getArguments().descendants(ASTNamedReferenceExpr.class).count() > 0; } private boolean isAppendingInvocationResult(InvocationNode node) { return node.getArguments().getFirstChild() instanceof ASTMethodCall || node.getArguments().getFirstChild() instanceof ASTConstructorCall; } static boolean isStringBuilderOrBuffer(TypeNode node) { return TypeTestUtil.isA(StringBuffer.class, node) || TypeTestUtil.isA(StringBuilder.class, node); } private static final class ConsecutiveCounter { private int threshold; private int counter; private Node reportNode; public void initThreshold(int threshold) { this.threshold = threshold; } public void count(Node node) { if (counter == 0) { reportNode = node; } counter++; } public void reset() { counter = 0; reportNode = null; } public boolean isViolation() { return counter > threshold; } public int getCounter() { return counter; } public Node getReportNode() { return reportNode; } @Override public String toString() { return "counter=" + counter + ",threshold=" + threshold + ",node=" + reportNode; } } }
11,744
35.818182
120
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/AvoidInstantiatingObjectsInLoopsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import java.util.Collection; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTArrayAccess; import net.sourceforge.pmd.lang.java.ast.ASTArrayAllocation; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTBreakStatement; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTForInit; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; public class AvoidInstantiatingObjectsInLoopsRule extends AbstractJavaRulechainRule { public AvoidInstantiatingObjectsInLoopsRule() { super(ASTConstructorCall.class, ASTArrayAllocation.class); } @Override public Object visit(ASTConstructorCall node, Object data) { checkNode(node, data); return data; } @Override public Object visit(ASTArrayAllocation node, Object data) { checkNode(node, data); return data; } private void checkNode(JavaNode node, Object data) { if (notInsideLoop(node)) { return; } if (notAThrowStatement(node) && notAReturnStatement(node) && notBreakFollowing(node) && notArrayAssignment(node) && notCollectionAccess(node)) { addViolation(data, node); } } private boolean notArrayAssignment(JavaNode node) { JavaNode childOfAssignment = node.ancestorsOrSelf() .filter(n -> n.getParent() instanceof ASTAssignmentExpression).first(); if (childOfAssignment != null && childOfAssignment.getIndexInParent() == 1) { Node assignee = childOfAssignment.getParent().getFirstChild(); return !(assignee instanceof ASTArrayAccess); } return true; } private boolean notCollectionAccess(JavaNode node) { // checks whether the given ConstructorCall/ArrayAllocation is // part of a MethodCall on a Collection. return node.ancestors(ASTArgumentList.class) .filter(n -> n.getParent() instanceof ASTMethodCall) .filter(n -> TypeTestUtil.isA(Collection.class, ((ASTMethodCall) n.getParent()).getQualifier())) .isEmpty(); } private boolean notBreakFollowing(JavaNode node) { JavaNode statement = node.ancestors().filter(n -> n.getParent() instanceof ASTBlock).first(); return statement == null || !(statement.getNextSibling() instanceof ASTBreakStatement); } /** * This method is used to check whether this expression is a throw statement. * @param node This is the expression of part of java code to be checked. * @return boolean This returns whether the given constructor call is part of a throw statement */ private boolean notAThrowStatement(JavaNode node) { return !(node.getParent() instanceof ASTThrowStatement); } /** * This method is used to check whether this expression is a return statement. * @param node This is the expression of part of java code to be checked. * @return boolean This returns whether the given constructor call is part of a return statement */ private boolean notAReturnStatement(JavaNode node) { return !(node.getParent() instanceof ASTReturnStatement); } /** * This method is used to check whether this expression is not in a loop. * @param node This is the expression of part of java code to be checked. * @return boolean <code>false</code> if the given node is inside a loop, <code>true</code> otherwise */ private boolean notInsideLoop(Node node) { Node n = node; while (n != null) { if (n instanceof ASTLoopStatement) { return false; } else if (n instanceof ASTForInit) { /* * init part is not technically inside the loop. Skip parent * ASTForStatement but continue higher up to detect nested loops */ n = n.getParent(); } else if (n.getParent() instanceof ASTForeachStatement && n.getParent().getNumChildren() > 1 && n == n.getParent().getChild(1)) { // it is the second child of a ForeachStatement. // In that case, we can ignore this allocation expression, as // the second child // is the expression, over which to iterate. // Skip this parent but continue higher up // to detect nested loops n = n.getParent(); } n = n.getParent(); } return true; } }
5,372
39.398496
108
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/BigIntegerInstantiationRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.util.CollectionUtil; /** * Rule that marks instantiations of new {@link BigInteger} or {@link BigDecimal} objects, when there is a well-known * constant available, such as {@link BigInteger#ZERO}. */ public class BigIntegerInstantiationRule extends AbstractJavaRulechainRule { private static final Set<String> CONSTANTS = CollectionUtil.setOf("0", "0.", "1"); public BigIntegerInstantiationRule() { super(ASTConstructorCall.class); } @Override public Object visit(ASTConstructorCall node, Object data) { LanguageVersion languageVersion = node.getTextDocument().getLanguageVersion(); boolean jdk15 = languageVersion.compareToVersion("1.5") >= 0; boolean jdk9 = languageVersion.compareToVersion("9") >= 0; if (TypeTestUtil.isA(BigInteger.class, node) || jdk15 && TypeTestUtil.isA(BigDecimal.class, node)) { @NonNull ASTArgumentList arguments = node.getArguments(); if (arguments.size() == 1) { ASTExpression firstArg = arguments.get(0); Object constValue = firstArg.getConstValue(); if (CONSTANTS.contains(constValue) || jdk15 && "10".equals(constValue) || jdk9 && "2".equals(constValue) || Integer.valueOf(0).equals(constValue) || Integer.valueOf(1).equals(constValue) || jdk15 && Integer.valueOf(10).equals(constValue)) { addViolation(data, node); } } } return data; } }
2,278
36.360656
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/UseIndexOfCharRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; 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.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * */ public class UseIndexOfCharRule extends AbstractJavaRulechainRule { public UseIndexOfCharRule() { super(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall node, Object data) { if ("indexOf".equals(node.getMethodName()) || "lastIndexOf".equals(node.getMethodName())) { if (TypeTestUtil.isA(String.class, node.getQualifier()) && node.getArguments().size() >= 1) { // there are two overloads of each ASTExpression arg = node.getArguments().get(0); if (arg instanceof ASTStringLiteral && ((ASTStringLiteral) arg).getConstValue().length() == 1) { addViolation(data, node); } } } return data; } }
1,226
32.162162
112
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/AppendCharacterWithCharRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * This rule finds the following: * * <pre> * StringBuffer.append(&quot;c&quot;); // appends a single character * </pre> * * <p>It is preferable to use</p> * * <pre>StringBuffer.append('c'); // appends a single character</pre> * * @see <a href="https://sourceforge.net/p/pmd/feature-requests/381/">feature request #381 Single character StringBuffer.append </a> */ public class AppendCharacterWithCharRule extends AbstractJavaRulechainRule { public AppendCharacterWithCharRule() { super(ASTStringLiteral.class); } @Override public Object visit(ASTStringLiteral node, Object data) { if (node.getParent() instanceof ASTArgumentList && node.length() == 1 && ((ASTArgumentList) node.getParent()).size() == 1) { JavaNode callParent = node.getParent().getParent(); if (callParent instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) callParent; if ("append".equals(call.getMethodName()) && (TypeTestUtil.isDeclaredInClass(StringBuilder.class, call.getMethodType()) || TypeTestUtil.isDeclaredInClass(StringBuffer.class, call.getMethodType())) ) { addViolation(data, node); } } } return data; } }
1,850
34.596154
132
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/StringInstantiationRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class StringInstantiationRule extends AbstractJavaRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTConstructorCall.class); } @Override public Object visit(ASTConstructorCall node, Object data) { ASTArgumentList args = node.getArguments(); if (args.size() <= 1 && TypeTestUtil.isExactlyA(String.class, node.getTypeNode())) { if (args.size() == 1 && TypeTestUtil.isExactlyA(byte[].class, args.get(0))) { // byte array ctor is ok return data; } addViolation(data, node); } return data; } }
1,208
32.583333
89
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/ConsecutiveAppendsShouldReuseRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.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.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class ConsecutiveAppendsShouldReuseRule extends AbstractJavaRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTExpressionStatement.class, ASTLocalVariableDeclaration.class); } @Override public Object visit(ASTExpressionStatement node, Object data) { Node nextSibling = node.asStream().followingSiblings().first(); if (nextSibling instanceof ASTExpressionStatement) { @Nullable JVariableSymbol variable = getVariableAppended(node); if (variable != null) { @Nullable JVariableSymbol nextVariable = getVariableAppended((ASTExpressionStatement) nextSibling); if (nextVariable != null && nextVariable.equals(variable)) { addViolation(data, node); } } } return data; } @Override public Object visit(ASTLocalVariableDeclaration node, Object data) { Node nextSibling = node.asStream().followingSiblings().first(); if (nextSibling instanceof ASTExpressionStatement) { @Nullable JVariableSymbol nextVariable = getVariableAppended((ASTExpressionStatement) nextSibling); if (nextVariable != null) { ASTVariableDeclaratorId varDecl = nextVariable.tryGetNode(); if (varDecl != null && node.getVarIds().any(it -> it == varDecl) && isStringBuilderAppend(varDecl.getInitializer())) { addViolation(data, node); } } } return data; } private @Nullable JVariableSymbol getVariableAppended(ASTExpressionStatement node) { ASTExpression expr = node.getExpr(); if (expr instanceof ASTMethodCall) { return getAsVarAccess(getAppendChainQualifier(expr)); } else if (expr instanceof ASTAssignmentExpression) { ASTExpression rhs = ((ASTAssignmentExpression) expr).getRightOperand(); return getAppendChainQualifier(rhs) != null ? getAssignmentLhsAsVar(expr) : null; } return null; } private @Nullable ASTExpression getAppendChainQualifier(final ASTExpression base) { ASTExpression expr = base; while (expr instanceof ASTMethodCall && isStringBuilderAppend(expr)) { expr = ((ASTMethodCall) expr).getQualifier(); } return base == expr ? null : expr; // NOPMD } private @Nullable JVariableSymbol getAssignmentLhsAsVar(@Nullable ASTExpression expr) { if (expr instanceof ASTAssignmentExpression) { return getAsVarAccess(((ASTAssignmentExpression) expr).getLeftOperand()); } return null; } private @Nullable JVariableSymbol getAsVarAccess(@Nullable ASTExpression expr) { if (expr instanceof ASTNamedReferenceExpr) { return ((ASTNamedReferenceExpr) expr).getReferencedSym(); } return null; } private boolean isStringBuilderAppend(@Nullable ASTExpression e) { if (e instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) e; return "append".equals(call.getMethodName()) && isStringBuilderAppend(call.getOverloadSelectionInfo()); } return false; } private boolean isStringBuilderAppend(OverloadSelectionResult result) { if (result.isFailed()) { return false; } JExecutableSymbol symbol = result.getMethodType().getSymbol(); return TypeTestUtil.isExactlyA(StringBuffer.class, symbol.getEnclosingClass()) || TypeTestUtil.isExactlyA(StringBuilder.class, symbol.getEnclosingClass()); } }
4,873
40.65812
115
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/UselessStringValueOfRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; 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.AbstractJavaRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class UselessStringValueOfRule extends AbstractJavaRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTMethodCall.class); } @Override public Object visit(ASTMethodCall node, Object data) { if (JavaAstUtils.isStringConcatExpr(node.getParent())) { ASTExpression valueOfArg = getValueOfArg(node); if (valueOfArg == null) { return data; //not a valueOf call } else if (TypeTestUtil.isExactlyA(String.class, valueOfArg)) { addViolation(data, node); // valueOf call on a string return data; } ASTExpression sibling = JavaAstUtils.getOtherOperandIfInInfixExpr(node); if (TypeTestUtil.isExactlyA(String.class, sibling) && !valueOfArg.getTypeMirror().isArray() // In `String.valueOf(a) + String.valueOf(b)`, // only report the second call && (getValueOfArg(sibling) == null || node.getIndexInParent() == 1)) { addViolation(data, node); } } return data; } private static @Nullable ASTExpression getValueOfArg(ASTExpression expr) { if (expr instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) expr; if (call.getArguments().size() == 1 && "valueOf".equals(call.getMethodName()) && TypeTestUtil.isDeclaredInClass(String.class, call.getMethodType())) { return call.getArguments().get(0); } } return null; } }
2,287
36.508197
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/RedundantFieldInitializerRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.Set; 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.ASTVariableAccess; 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; /** * Detects redundant field initializers, i.e. the field initializer expressions * the JVM would assign by default. * * @author lucian.ciufudean@gmail.com * @since Apr 10, 2009 */ public class RedundantFieldInitializerRule extends AbstractJavaRulechainRule { private static final Set<String> MAKE_FIELD_FINAL_CLASS_ANNOT = setOf( "lombok.Value" ); public RedundantFieldInitializerRule() { super(ASTFieldDeclaration.class); } @Override public Object visit(ASTFieldDeclaration fieldDeclaration, Object data) { if (!fieldDeclaration.hasModifiers(JModifier.FINAL) && !JavaAstUtils.hasAnyAnnotation(fieldDeclaration.getEnclosingType(), MAKE_FIELD_FINAL_CLASS_ANNOT)) { for (ASTVariableDeclaratorId varId : fieldDeclaration.getVarIds()) { ASTExpression init = varId.getInitializer(); if (init != null) { if (!isWhitelisted(init) && JavaAstUtils.isDefaultValue(varId.getTypeMirror(), init)) { addViolation(data, varId); } } } } return data; } // whitelist if there are named variables in there private static boolean isWhitelisted(ASTExpression e) { return e.descendantsOrSelf().any(it -> it instanceof ASTVariableAccess || it instanceof ASTFieldAccess); } }
2,129
33.918033
163
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/InsufficientStringBufferDeclarationRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.mutable.MutableInt; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTCharLiteral; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTLiteral; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTNumericLiteral; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; 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.JavaVisitorBase; import net.sourceforge.pmd.lang.java.ast.TypeNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * This rule finds StringBuffers which may have been pre-sized incorrectly. * * @author Allan Caplan * @author Andreas Dangel * @see <a href="https://sourceforge.net/p/pmd/discussion/188194/thread/aba9dae7/">Check StringBuffer sizes against * usage </a> */ public class InsufficientStringBufferDeclarationRule extends AbstractJavaRulechainRule { private static final int DEFAULT_BUFFER_SIZE = 16; public InsufficientStringBufferDeclarationRule() { super(ASTVariableDeclaratorId.class); } private static class State { ASTVariableDeclaratorId variable; TypeNode rootNode; int capacity; int anticipatedLength; Map<Node, Map<Node, Integer>> branches = new HashMap<>(); State(ASTVariableDeclaratorId variable, TypeNode rootNode, int capacity, int anticipatedLength) { this.variable = variable; this.rootNode = rootNode; this.capacity = capacity; this.anticipatedLength = anticipatedLength; } public void addAnticipatedLength(int length) { this.anticipatedLength += length; } public boolean isInsufficient() { processBranches(); return capacity >= 0 && anticipatedLength > capacity; } public String[] getParamsForViolation() { return new String[] { getTypeName(variable), String.valueOf(capacity), String.valueOf(anticipatedLength) }; } private String getTypeName(TypeNode node) { return node.getTypeMirror().getSymbol().getSimpleName(); } public void addBranch(Node node, int counter) { Node parent = node.ancestors(ASTIfStatement.class).last(); if (parent == null) { parent = node.ancestors(ASTSwitchStatement.class).last(); } if (parent == null) { return; } branches.putIfAbsent(parent, new HashMap<>()); Map<Node, Integer> blocks = branches.get(parent); if (!blocks.containsKey(node)) { blocks.put(node, counter); } else { blocks.put(node, blocks.get(node) + counter); } } private void processBranches() { for (Map<Node, Integer> blocks : branches.values()) { int counter = 0; for (Integer i : blocks.values()) { counter = Math.max(counter, i); } addAnticipatedLength(counter); } branches.clear(); } @Override public String toString() { return "State[capacity=" + capacity + ",anticipatedLength=" + anticipatedLength + "]"; } } @Override public Object visit(ASTVariableDeclaratorId node, Object data) { if (!TypeTestUtil.isA(StringBuilder.class, node) && !TypeTestUtil.isA(StringBuffer.class, node)) { return data; } State state = getConstructorCapacity(node, node.getInitializer()); for (ASTNamedReferenceExpr usage : node.getLocalUsages()) { if (usage.getParent() instanceof ASTMethodCall) { Node parent = usage.getParent(); while (parent instanceof ASTMethodCall) { ASTMethodCall methodCall = (ASTMethodCall) parent; processMethodCall(state, methodCall); parent = parent.getParent(); } } else if (usage.getParent() instanceof ASTAssignmentExpression) { ASTAssignmentExpression assignment = (ASTAssignmentExpression) usage.getParent(); State newState = getConstructorCapacity(node, assignment.getRightOperand()); if (newState.rootNode != null) { if (state.isInsufficient()) { addViolation(data, state.rootNode, state.getParamsForViolation()); } state = newState; } else { state.addAnticipatedLength(newState.anticipatedLength); } } } if (state.isInsufficient()) { addViolation(data, state.rootNode, state.getParamsForViolation()); } return data; } private void processMethodCall(State state, ASTMethodCall methodCall) { if ("append".equals(methodCall.getMethodName())) { int counter = 0; Set<ASTLiteral> literals = new HashSet<>(); literals.addAll(methodCall.getArguments() .descendants(ASTLiteral.class) // exclude literals, that belong to different method calls .filter(n -> n.ancestors(ASTMethodCall.class).first() == methodCall).toList()); for (ASTLiteral literal : literals) { if (literal instanceof ASTStringLiteral) { counter += ((ASTStringLiteral) literal).length(); } else if (literal instanceof ASTNumericLiteral) { if (literal.getParent() instanceof ASTCastExpression && TypeTestUtil.isA(char.class, (ASTCastExpression) literal.getParent())) { counter += 1; } else { counter += String.valueOf(((ASTNumericLiteral) literal).getConstValue()).length(); } } else if (literal instanceof ASTCharLiteral) { counter += 1; } } ASTIfStatement ifStatement = methodCall.ancestors(ASTIfStatement.class).first(); ASTSwitchStatement switchStatement = methodCall.ancestors(ASTSwitchStatement.class).first(); if (ifStatement != null) { if (ifStatement.getThenBranch().descendants().any(n -> n == methodCall)) { state.addBranch(ifStatement.getThenBranch(), counter); } else if (ifStatement.getElseBranch() != null) { state.addBranch(ifStatement.getElseBranch(), counter); } } else if (switchStatement != null) { state.addBranch(methodCall.ancestors(ASTSwitchBranch.class).first(), counter); } else { state.addAnticipatedLength(counter); } } else if ("setLength".equals(methodCall.getMethodName())) { int newLength = calculateExpression(methodCall.getArguments().get(0)); if (state.capacity != -1 && newLength > state.capacity) { state.capacity = newLength; // a bigger setLength increases capacity state.rootNode = methodCall; } // setLength fills the string builder, any new append adds to this state.anticipatedLength = newLength; } else if ("ensureCapacity".equals(methodCall.getMethodName())) { int newCapacity = calculateExpression(methodCall.getArguments().get(0)); if (newCapacity > state.capacity) { // only a bigger new capacity changes the capacity state.capacity = newCapacity; state.rootNode = methodCall; } } } private State getConstructorCapacity(ASTVariableDeclaratorId variable, ASTExpression node) { State state = new State(variable, null, -1, 0); JavaNode possibleConstructorCall = node; JavaNode child = node; while (child instanceof ASTMethodCall) { processMethodCall(state, (ASTMethodCall) child); child = child.getFirstChild(); } possibleConstructorCall = child; if (!(possibleConstructorCall instanceof ASTConstructorCall)) { return state; } ASTConstructorCall constructorCall = (ASTConstructorCall) possibleConstructorCall; if (constructorCall.getArguments().size() == 1) { ASTExpression argument = constructorCall.getArguments().get(0); if (argument instanceof ASTStringLiteral) { int stringLength = ((ASTStringLiteral) argument).length(); return new State(variable, constructorCall, DEFAULT_BUFFER_SIZE + stringLength, stringLength + state.anticipatedLength); } else { return new State(variable, constructorCall, calculateExpression(argument), state.anticipatedLength); } } return new State(variable, constructorCall, DEFAULT_BUFFER_SIZE, state.anticipatedLength); } private int calculateExpression(ASTExpression expression) { class ExpressionVisitor extends JavaVisitorBase<MutableInt, Void> { @Override public Void visit(ASTInfixExpression node, MutableInt data) { MutableInt temp = new MutableInt(-1); if (BinaryOp.ADD.equals(node.getOperator())) { data.setValue(0); node.getLeftOperand().acceptVisitor(this, temp); data.add(temp.getValue()); node.getRightOperand().acceptVisitor(this, temp); data.add(temp.getValue()); } else if (BinaryOp.MUL.equals(node.getOperator())) { node.getLeftOperand().acceptVisitor(this, temp); data.setValue(temp.getValue()); node.getRightOperand().acceptVisitor(this, temp); data.setValue(data.getValue() * temp.getValue()); } return null; } @Override public Void visit(ASTNumericLiteral node, MutableInt data) { data.setValue(node.getValueAsInt()); return null; } } MutableInt result = new MutableInt(-1); expression.acceptVisitor(new ExpressionVisitor(), result); return result.getValue(); } }
11,561
40.145907
136
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/performance/AddEmptyStringRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.performance; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral; 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.JModifier; 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; public class AddEmptyStringRule extends AbstractJavaRulechainRule { public AddEmptyStringRule() { super(ASTStringLiteral.class); } @Override public Object visit(ASTStringLiteral node, Object data) { if (!node.isEmpty()) { return null; } JavaNode parent = node.getParent(); checkExpr(data, parent); if (parent instanceof ASTVariableDeclarator) { ASTVariableDeclaratorId varId = ((ASTVariableDeclarator) parent).getVarId(); if (varId.hasModifiers(JModifier.FINAL)) { for (ASTNamedReferenceExpr usage : varId.getLocalUsages()) { checkExpr(data, usage.getParent()); } } } return null; } private void checkExpr(Object data, JavaNode parent) { if (JavaAstUtils.isInfixExprWithOperator(parent, BinaryOp.ADD) && parent.ancestors(ASTAnnotation.class).isEmpty()) { addViolation(data, parent); } } }
1,786
34.74
88
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/IdenticalCatchBranchesRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTTryStatement; 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; /** * Flags identical catch branches, which can be collapsed into a multi-catch. * * @author Clément Fournier * @since 6.4.0 */ public class IdenticalCatchBranchesRule extends AbstractJavaRulechainRule { public IdenticalCatchBranchesRule() { super(ASTTryStatement.class); } private boolean areEquivalent(ASTCatchClause st1, ASTCatchClause st2) { String e1Name = st1.getParameter().getName(); String e2Name = st2.getParameter().getName(); return JavaAstUtils.tokenEquals(st1.getBody(), st2.getBody(), name -> name.equals(e1Name) ? e2Name : name); } /** groups catch statements by equivalence class, according to the equivalence {@link #areEquivalent(ASTCatchClause, ASTCatchClause)}. */ private Set<List<ASTCatchClause>> equivalenceClasses(List<ASTCatchClause> catches) { Set<List<ASTCatchClause>> result = new HashSet<>(catches.size()); for (ASTCatchClause stmt : catches) { if (result.isEmpty()) { result.add(newEquivClass(stmt)); continue; } boolean isNewClass = true; for (List<ASTCatchClause> equivClass : result) { if (areEquivalent(stmt, equivClass.get(0))) { equivClass.add(stmt); isNewClass = false; break; } } if (isNewClass) { result.add(newEquivClass(stmt)); } } return result; } private List<ASTCatchClause> newEquivClass(ASTCatchClause stmt) { // Each equivalence class is sorted by document order List<ASTCatchClause> result = new ArrayList<>(2); result.add(stmt); return result; } // Gets the representation of the set of catch statements as a single multicatch private String getCaughtExceptionsAsString(ASTCatchClause stmt) { return PrettyPrintingUtil.prettyPrintType(stmt.getParameter().getTypeNode()); } @Override public Object visit(ASTTryStatement node, Object data) { List<ASTCatchClause> catchStatements = node.getCatchClauses().toList(); Set<List<ASTCatchClause>> equivClasses = equivalenceClasses(catchStatements); for (List<ASTCatchClause> identicalStmts : equivClasses) { if (identicalStmts.size() > 1) { String identicalBranchName = getCaughtExceptionsAsString(identicalStmts.get(0)); // By convention, lower catch blocks are collapsed into the highest one // The first node of the equivalence class is thus the block that should be transformed for (int i = 1; i < identicalStmts.size(); i++) { addViolation(data, identicalStmts.get(i), new String[]{identicalBranchName, }); } } } return data; } }
3,467
32.669903
141
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryReturnRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTCompactConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTInitializer; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTLoopStatement; 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.ASTTryStatement; 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; public class UnnecessaryReturnRule extends AbstractJavaRulechainRule { public UnnecessaryReturnRule() { super(ASTReturnStatement.class); } @Override public Object visit(ASTReturnStatement node, Object data) { if (node.getNumChildren() > 0) { return null; } NodeStream<ASTStatement> enclosingStatements = node.ancestorsOrSelf() .takeWhile(it -> !isCfgLimit(it)) .filterIs(ASTStatement.class); if (enclosingStatements.all(UnnecessaryReturnRule::isLastStatementOfParent)) { addViolation(data, node); } return null; } private boolean isCfgLimit(JavaNode it) { return it instanceof ASTMethodOrConstructorDeclaration || it instanceof ASTCompactConstructorDeclaration || it instanceof ASTInitializer || it instanceof ASTLambdaExpression; } /** * Returns true if this is the last statement of the parent node, * ie the next statement to be executed is after the parent in the * CFG. */ private static boolean isLastStatementOfParent(ASTStatement it) { // Note that local class declaration statements could be ignored // because they don't contribute anything to control flow. But this // is rare enough that this has not been implemented. A corresponding // test is in the test file. JavaNode parent = it.getParent(); if (JavaAstUtils.isLastChild(it)) { if (parent instanceof ASTSwitchArrowBranch) { return !isBranchOfSwitchExpr((ASTSwitchBranch) parent); } else if (parent instanceof ASTSwitchFallthroughBranch) { return JavaAstUtils.isLastChild(parent) && !isBranchOfSwitchExpr((ASTSwitchBranch) parent); } else { return !(parent instanceof ASTLoopStatement); // returns break the loop so are not unnecessary (though it could be replaced by break) } } // so we're not the last child... return parent instanceof ASTIfStatement // maybe we're before the else clause || parent instanceof ASTTryStatement; // maybe we're the body of a try // also maybe we're the body of a do/while, but that is a loop, so it's necessary } private static boolean isBranchOfSwitchExpr(ASTSwitchBranch branch) { return branch.getParent() instanceof ASTSwitchExpression; } }
3,678
41.77907
149
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/LinguisticNamingRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil.containsCamelCaseWord; import static net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil.startsWithCamelCaseWord; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.util.List; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTType; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator; import net.sourceforge.pmd.lang.java.ast.Annotatable; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.JavaPropertyUtil; import net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; public class LinguisticNamingRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<List<String>> IGNORED_ANNOTS = JavaPropertyUtil.ignoredAnnotationsDescriptor("java.lang.Override"); private static final PropertyDescriptor<Boolean> CHECK_BOOLEAN_METHODS = booleanProperty("checkBooleanMethod").defaultValue(true).desc("Check method names and types for inconsistent naming.").build(); private static final PropertyDescriptor<Boolean> CHECK_GETTERS = booleanProperty("checkGetters").defaultValue(true).desc("Check return type of getters.").build(); private static final PropertyDescriptor<Boolean> CHECK_SETTERS = booleanProperty("checkSetters").defaultValue(true).desc("Check return type of setters.").build(); private static final PropertyDescriptor<Boolean> CHECK_PREFIXED_TRANSFORM_METHODS = booleanProperty("checkPrefixedTransformMethods") .desc("Check return type of methods whose names start with the configured prefix (see transformMethodNames property).") .defaultValue(true).build(); private static final PropertyDescriptor<Boolean> CHECK_TRANSFORM_METHODS = booleanProperty("checkTransformMethods") .desc("Check return type of methods which contain the configured infix in their name (see transformMethodNames property).") .defaultValue(false).build(); private static final PropertyDescriptor<Boolean> CHECK_FIELDS = booleanProperty("checkFields").defaultValue(true).desc("Check field names and types for inconsistent naming.").build(); private static final PropertyDescriptor<Boolean> CHECK_VARIABLES = booleanProperty("checkVariables").defaultValue(true).desc("Check local variable names and types for inconsistent naming.").build(); private static final PropertyDescriptor<List<String>> BOOLEAN_METHOD_PREFIXES_PROPERTY = stringListProperty("booleanMethodPrefixes") .desc("The prefixes of methods that return boolean.") .defaultValues("is", "has", "can", "have", "will", "should").build(); private static final PropertyDescriptor<List<String>> TRANSFORM_METHOD_NAMES_PROPERTY = stringListProperty("transformMethodNames") .desc("The prefixes and infixes that indicate a transform method.") .defaultValues("to", "as").build(); private static final PropertyDescriptor<List<String>> BOOLEAN_FIELD_PREFIXES_PROPERTY = stringListProperty("booleanFieldPrefixes") .desc("The prefixes of fields and variables that indicate boolean.") .defaultValues("is", "has", "can", "have", "will", "should").build(); public LinguisticNamingRule() { super(ASTMethodDeclaration.class, ASTFieldDeclaration.class, ASTLocalVariableDeclaration.class); definePropertyDescriptor(IGNORED_ANNOTS); definePropertyDescriptor(CHECK_BOOLEAN_METHODS); definePropertyDescriptor(CHECK_GETTERS); definePropertyDescriptor(CHECK_SETTERS); definePropertyDescriptor(CHECK_PREFIXED_TRANSFORM_METHODS); definePropertyDescriptor(CHECK_TRANSFORM_METHODS); definePropertyDescriptor(BOOLEAN_METHOD_PREFIXES_PROPERTY); definePropertyDescriptor(TRANSFORM_METHOD_NAMES_PROPERTY); definePropertyDescriptor(CHECK_FIELDS); definePropertyDescriptor(CHECK_VARIABLES); definePropertyDescriptor(BOOLEAN_FIELD_PREFIXES_PROPERTY); } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (!hasIgnoredAnnotation(node)) { String nameOfMethod = node.getName(); if (getProperty(CHECK_BOOLEAN_METHODS)) { checkBooleanMethods(node, data, nameOfMethod); } if (getProperty(CHECK_SETTERS)) { checkSetters(node, data, nameOfMethod); } if (getProperty(CHECK_GETTERS)) { checkGetters(node, data, nameOfMethod); } if (getProperty(CHECK_PREFIXED_TRANSFORM_METHODS)) { checkPrefixedTransformMethods(node, data, nameOfMethod); } if (getProperty(CHECK_TRANSFORM_METHODS)) { checkTransformMethods(node, data, nameOfMethod); } } return data; } private boolean hasIgnoredAnnotation(Annotatable node) { return node.isAnyAnnotationPresent(getProperty(IGNORED_ANNOTS)); } private void checkPrefixedTransformMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) { List<String> prefixes = getProperty(TRANSFORM_METHOD_NAMES_PROPERTY); String[] splitMethodName = StringUtils.splitByCharacterTypeCamelCase(nameOfMethod); if (node.isVoid() && splitMethodName.length > 0 && prefixes.contains(splitMethodName[0].toLowerCase(Locale.ROOT))) { // "To" or any other configured prefix found addViolationWithMessage(data, node, "Linguistics Antipattern - The transform method ''{0}'' should not return void linguistically", new Object[] { nameOfMethod }); } } private void checkTransformMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) { for (String infix : getProperty(TRANSFORM_METHOD_NAMES_PROPERTY)) { if (node.isVoid() && containsCamelCaseWord(nameOfMethod, StringUtils.capitalize(infix))) { // "To" or any other configured infix in the middle somewhere addViolationWithMessage(data, node, "Linguistics Antipattern - The transform method ''{0}'' should not return void linguistically", new Object[] { nameOfMethod }); // the first violation is sufficient - it is still the same method we are analyzing here break; } } } private void checkGetters(ASTMethodDeclaration node, Object data, String nameOfMethod) { if (startsWithCamelCaseWord(nameOfMethod, "get") && node.isVoid()) { addViolationWithMessage(data, node, "Linguistics Antipattern - The getter ''{0}'' should not return void linguistically", new Object[] { nameOfMethod }); } } private void checkSetters(ASTMethodDeclaration node, Object data, String nameOfMethod) { if (startsWithCamelCaseWord(nameOfMethod, "set") && !node.isVoid()) { addViolationWithMessage(data, node, "Linguistics Antipattern - The setter ''{0}'' should not return any type except void linguistically", new Object[] { nameOfMethod }); } } private boolean isBooleanType(ASTType node) { return node.getTypeMirror().unbox().isPrimitive(PrimitiveTypeKind.BOOLEAN) || TypeTestUtil.isA("java.util.concurrent.atomic.AtomicBoolean", node) || TypeTestUtil.isA("java.util.function.Predicate", node); } private void checkBooleanMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) { ASTType t = node.getResultTypeNode(); if (!t.isVoid()) { for (String prefix : getProperty(BOOLEAN_METHOD_PREFIXES_PROPERTY)) { if (startsWithCamelCaseWord(nameOfMethod, prefix) && !isBooleanType(t)) { addViolationWithMessage(data, node, "Linguistics Antipattern - The method ''{0}'' indicates linguistically it returns a boolean, but it returns ''{1}''", new Object[] {nameOfMethod, PrettyPrintingUtil.prettyPrintType(t) }); } } } } private void checkField(ASTType typeNode, ASTVariableDeclarator node, Object data) { for (String prefix : getProperty(BOOLEAN_FIELD_PREFIXES_PROPERTY)) { if (startsWithCamelCaseWord(node.getName(), prefix) && !isBooleanType(typeNode)) { addViolationWithMessage(data, node, "Linguistics Antipattern - The field ''{0}'' indicates linguistically it is a boolean, but it is ''{1}''", new Object[] { node.getName(), PrettyPrintingUtil.prettyPrintType(typeNode) }); } } } private void checkVariable(ASTType typeNode, ASTVariableDeclarator node, Object data) { for (String prefix : getProperty(BOOLEAN_FIELD_PREFIXES_PROPERTY)) { if (startsWithCamelCaseWord(node.getName(), prefix) && !isBooleanType(typeNode)) { addViolationWithMessage(data, node, "Linguistics Antipattern - The variable ''{0}'' indicates linguistically it is a boolean, but it is ''{1}''", new Object[] { node.getName(), PrettyPrintingUtil.prettyPrintType(typeNode) }); } } } @Override public Object visit(ASTFieldDeclaration node, Object data) { ASTType type = node.getTypeNode(); if (type != null && getProperty(CHECK_FIELDS)) { for (ASTVariableDeclarator field : node.children(ASTVariableDeclarator.class)) { checkField(type, field, data); } } return data; } @Override public Object visit(ASTLocalVariableDeclaration node, Object data) { ASTType type = node.getTypeNode(); if (type != null && getProperty(CHECK_VARIABLES)) { for (ASTVariableDeclarator variable : node.children(ASTVariableDeclarator.class)) { checkVariable(type, variable, data); } } return data; } }
10,972
51.754808
173
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/CommentDefaultAccessModifierRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.List; import java.util.regex.Pattern; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; 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.ASTRecordDeclaration; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.ast.JavaComment; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.JavaPropertyUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Check for Methods, Fields and Nested Classes that have a default access * modifier * This rule ignores all nodes annotated with @VisibleForTesting by default. * Use the ignoredAnnotationsDescriptor property to customize the ignored rules. * * @author Damián Techeira */ public class CommentDefaultAccessModifierRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Pattern> REGEX_DESCRIPTOR = PropertyFactory.regexProperty("regex") .desc("Regular expression") .defaultValue("\\/\\*\\s*(default|package)\\s*\\*\\/") .build(); private static final PropertyDescriptor<Boolean> TOP_LEVEL_TYPES = PropertyFactory.booleanProperty("checkTopLevelTypes") .desc("Check for default access modifier in top-level classes, annotations, and enums") .defaultValue(false) .build(); private static final PropertyDescriptor<List<String>> IGNORED_ANNOTS = JavaPropertyUtil.ignoredAnnotationsDescriptor( "com.google.common.annotations.VisibleForTesting", "android.support.annotation.VisibleForTesting", "co.elastic.clients.util.VisibleForTesting", "org.junit.jupiter.api.Test", "org.junit.jupiter.api.extension.RegisterExtension", "org.junit.jupiter.api.ParameterizedTest", "org.junit.jupiter.api.RepeatedTest", "org.junit.jupiter.api.TestFactory", "org.junit.jupiter.api.TestTemplate", "org.junit.jupiter.api.BeforeEach", "org.junit.jupiter.api.BeforeAll", "org.junit.jupiter.api.AfterEach", "org.junit.jupiter.api.AfterAll", "org.testng.annotations.Test", "org.testng.annotations.AfterClass", "org.testng.annotations.AfterGroups", "org.testng.annotations.AfterMethod", "org.testng.annotations.AfterSuite", "org.testng.annotations.AfterTest", "org.testng.annotations.BeforeClass", "org.testng.annotations.BeforeGroups", "org.testng.annotations.BeforeMethod", "org.testng.annotations.BeforeSuite", "org.testng.annotations.BeforeTest" ); public CommentDefaultAccessModifierRule() { super(ASTMethodDeclaration.class, ASTAnyTypeDeclaration.class, ASTConstructorDeclaration.class, ASTFieldDeclaration.class); definePropertyDescriptor(IGNORED_ANNOTS); definePropertyDescriptor(REGEX_DESCRIPTOR); definePropertyDescriptor(TOP_LEVEL_TYPES); } @Override public Object visit(final ASTMethodDeclaration decl, final Object data) { if (shouldReportNonTopLevel(decl)) { report((RuleContext) data, decl, "method", PrettyPrintingUtil.displaySignature(decl)); } return data; } @Override public Object visit(final ASTFieldDeclaration decl, final Object data) { if (shouldReportNonTopLevel(decl)) { report((RuleContext) data, decl, "field", decl.getVarIds().firstOrThrow().getName()); } return data; } @Override public Object visit(final ASTConstructorDeclaration decl, Object data) { if (shouldReportNonTopLevel(decl)) { report((RuleContext) data, decl, "constructor", PrettyPrintingUtil.displaySignature(decl)); } return data; } @Override public Object visit(final ASTAnnotationTypeDeclaration decl, final Object data) { checkTypeDecl(decl, (RuleContext) data, "annotation"); return data; } @Override public Object visit(final ASTEnumDeclaration decl, final Object data) { checkTypeDecl(decl, (RuleContext) data, "enum"); return data; } @Override public Object visit(final ASTRecordDeclaration decl, final Object data) { checkTypeDecl(decl, (RuleContext) data, "record"); return data; } @Override public Object visit(final ASTClassOrInterfaceDeclaration decl, final Object data) { checkTypeDecl(decl, (RuleContext) data, "class"); return data; } private void checkTypeDecl(ASTAnyTypeDeclaration decl, RuleContext ctx, String typeKind) { if (decl.isNested() && shouldReportNonTopLevel(decl)) { report(ctx, decl, "nested " + typeKind, decl.getSimpleName()); } else if (!decl.isNested() && shouldReportTypeDeclaration(decl)) { report(ctx, decl, "top-level " + typeKind, decl.getSimpleName()); } } private void report(RuleContext ctx, AccessNode decl, String kind, String signature) { ctx.addViolation(decl, kind, signature); } private boolean shouldReportNonTopLevel(final AccessNode decl) { final ASTAnyTypeDeclaration enclosing = decl.getEnclosingType(); return isMissingComment(decl) && isNotIgnored(decl) && !(decl instanceof ASTFieldDeclaration && enclosing.isAnnotationPresent("lombok.Value")); } private boolean isMissingComment(AccessNode decl) { // check if the class/method/field has a default access // modifier return decl.getVisibility() == Visibility.V_PACKAGE // if is a default access modifier check if there is a comment // in this line && !hasOkComment(decl); } private boolean isNotIgnored(AccessNode decl) { return getProperty(IGNORED_ANNOTS).stream().noneMatch(decl::isAnnotationPresent); } private boolean hasOkComment(AccessNode node) { Pattern regex = getProperty(REGEX_DESCRIPTOR); return JavaComment.getLeadingComments(node) .anyMatch(it -> regex.matcher(it.getText()).matches()); } private boolean shouldReportTypeDeclaration(ASTAnyTypeDeclaration decl) { // don't report on interfaces return !(decl.isRegularInterface() && !decl.isAnnotation()) && isMissingComment(decl) && isNotIgnored(decl) // either nested or top level and we should check it && (decl.isNested() || getProperty(TOP_LEVEL_TYPES)); } }
7,521
39.880435
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryCastRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.ADD; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.DIV; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.GE; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.GT; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.LE; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.LT; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.MOD; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.MUL; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.SHIFT_OPS; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.SUB; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isInfixExprWithOperator; import java.util.EnumSet; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTMethodReference; import net.sourceforge.pmd.lang.java.ast.BinaryOp; 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.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeConversion; import net.sourceforge.pmd.lang.java.types.TypeOps; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.lang.java.types.ast.ExprContext; import net.sourceforge.pmd.lang.java.types.ast.ExprContext.ExprContextKind; /** * Detects casts where the operand is already a subtype of the context * type, or may be converted to it implicitly. */ public class UnnecessaryCastRule extends AbstractJavaRulechainRule { private static final Set<BinaryOp> BINARY_PROMOTED_OPS = EnumSet.of(LE, GE, GT, LT, ADD, SUB, MUL, DIV, MOD); public UnnecessaryCastRule() { super(ASTCastExpression.class); } @Override public Object visit(ASTCastExpression castExpr, Object data) { ASTExpression operand = castExpr.getOperand(); // eg in // Object o = (Integer) 1; @Nullable ExprContext context = castExpr.getConversionContext(); // Object JTypeMirror coercionType = castExpr.getCastType().getTypeMirror(); // Integer JTypeMirror operandType = operand.getTypeMirror(); // int if (TypeOps.isUnresolvedOrNull(operandType) || TypeOps.isUnresolvedOrNull(coercionType)) { return null; } // Note that we assume that coercionType is convertible to // contextType because the code must compile if (operand instanceof ASTLambdaExpression || operand instanceof ASTMethodReference) { // Then the cast provides a target type for the expression (always). // We need to check the enclosing context, as if it's invocation we give up for now if (context.isMissing() || context.hasKind(ExprContextKind.INVOCATION)) { // Then the cast may be used to determine the overload. // We need to treat the casted lambda as a whole unit. // todo see below return null; } // Since the code is assumed to compile we'll just assume that coercionType // is a functional interface. if (coercionType.equals(context.getTargetType())) { // then we also know that the context is functional reportCast(castExpr, data); } // otherwise the cast is narrowing, and removing it would // change the runtime class of the produced lambda. // Eg `SuperItf obj = (SubItf) ()-> {};` // If we remove the cast, even if it might compile, // the object will not implement SubItf anymore. } else if (isCastUnnecessary(castExpr, context, coercionType, operandType)) { reportCast(castExpr, data); } return null; } private boolean isCastUnnecessary(ASTCastExpression castExpr, @NonNull ExprContext context, JTypeMirror coercionType, JTypeMirror operandType) { if (operandType.equals(coercionType)) { // with the exception of the lambda thing above, casts to // the same type are always unnecessary return true; } else if (context.isMissing()) { // then we have fewer violation conditions return !operandType.isBottom() // casts on a null literal are necessary && operandType.isSubtypeOf(coercionType); } return !isCastDeterminingContext(castExpr, context, coercionType, operandType) && castIsUnnecessaryToMatchContext(context, coercionType, operandType); } private void reportCast(ASTCastExpression castExpr, Object data) { addViolation(data, castExpr, PrettyPrintingUtil.prettyPrintType(castExpr.getCastType())); } private static boolean castIsUnnecessaryToMatchContext(ExprContext context, JTypeMirror coercionType, JTypeMirror operandType) { if (context.hasKind(ExprContextKind.INVOCATION)) { // todo unsupported for now, the cast may be disambiguating overloads return false; } JTypeMirror contextType = context.getTargetType(); if (contextType == null) { return false; // should not occur in valid code } else if (!TypeConversion.isConvertibleUsingBoxing(operandType, coercionType)) { // narrowing cast return false; } else if (!context.acceptsType(operandType)) { // then removing the cast would produce uncompilable code return false; } boolean isBoxingFollowingCast = contextType.isPrimitive() != coercionType.isPrimitive(); // means boxing behavior is equivalent return !isBoxingFollowingCast || operandType.unbox().isSubtypeOf(contextType.unbox()); } /** * Returns whether the context type actually depends on the cast. * This means our analysis as written above won't work, and usually * that the cast is necessary, because there's some primitive conversions * happening, or some other corner case. */ private static boolean isCastDeterminingContext(ASTCastExpression castExpr, ExprContext context, @NonNull JTypeMirror coercionType, JTypeMirror operandType) { if (castExpr.getParent() instanceof ASTConditionalExpression && castExpr.getIndexInParent() != 0) { // a branch of a ternary return true; } else if (context.hasKind(ExprContextKind.STRING) && isInfixExprWithOperator(castExpr.getParent(), ADD)) { // inside string concatenation return !TypeTestUtil.isA(String.class, JavaAstUtils.getOtherOperandIfInInfixExpr(castExpr)) && !TypeTestUtil.isA(String.class, operandType); } else if (context.hasKind(ExprContextKind.NUMERIC) && castExpr.getParent() instanceof ASTInfixExpression) { // numeric expr ASTInfixExpression parent = (ASTInfixExpression) castExpr.getParent(); if (isInfixExprWithOperator(parent, SHIFT_OPS)) { // if so, then the cast is determining the width of expr // the right operand is always int return castExpr == parent.getLeftOperand() && !TypeOps.isStrictSubtype(operandType.unbox(), operandType.getTypeSystem().INT); } else if (isInfixExprWithOperator(parent, BINARY_PROMOTED_OPS)) { ASTExpression otherOperand = JavaAstUtils.getOtherOperandIfInInfixExpr(castExpr); JTypeMirror otherType = otherOperand.getTypeMirror(); // Ie, the type that is taken by the binary promotion // is the type of the cast, not the type of the operand. // Eg in // int i; ((double) i) * i // the only reason the mult expr has type double is because of the cast return TypeOps.isStrictSubtype(otherType, coercionType) // but not for integers strictly smaller than int && !TypeOps.isStrictSubtype(otherType.unbox(), otherType.getTypeSystem().INT); } } return false; } }
8,977
46.005236
162
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/PrematureDeclarationRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static java.util.Collections.emptySet; import static net.sourceforge.pmd.lang.ast.NodeStream.asInstanceOf; import java.util.Set; import java.util.stream.Collectors; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTForInit; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTResource; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; 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.JavaRuleUtil; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.InvocationMatcher.CompoundInvocationMatcher; /** * Checks for variables in methods that are defined before they are really * needed. A reference is deemed to be premature if it is created ahead of a * block of code that doesn't use it that also has the ability to return or * throw an exception. * * @author Brian Remedios */ public class PrematureDeclarationRule extends AbstractJavaRulechainRule { private static final CompoundInvocationMatcher TIME_METHODS = InvocationMatcher.parseAll( "java.lang.System#nanoTime()", "java.lang.System#currentTimeMillis()" ); public PrematureDeclarationRule() { super(ASTLocalVariableDeclaration.class); } @Override public Object visit(ASTLocalVariableDeclaration node, Object data) { if (node.getParent() instanceof ASTForInit || node.getParent() instanceof ASTResource) { // those don't count return null; } for (ASTVariableDeclaratorId id : node) { ASTExpression initializer = id.getInitializer(); if (JavaAstUtils.isNeverUsed(id) // avoid the duplicate with unused variables || cannotBeMoved(initializer) || JavaRuleUtil.hasSideEffect(initializer, emptySet())) { continue; } Set<JVariableSymbol> refsInInitializer = getReferencedVars(initializer); // If there's no initializer, or the initializer doesn't depend on anything (eg, a literal), // then we don't care about side-effects boolean hasStatefulInitializer = !refsInInitializer.isEmpty() || JavaRuleUtil.hasSideEffect(initializer, emptySet()); for (ASTStatement stmt : statementsAfter(node)) { if (hasReferencesIn(stmt, id) || hasStatefulInitializer && JavaRuleUtil.hasSideEffect(stmt, refsInInitializer)) { break; } if (hasExit(stmt)) { addViolation(data, node, id.getName()); break; } } } return null; } /** * Returns the set of local variables referenced inside the expression. */ private static Set<JVariableSymbol> getReferencedVars(ASTExpression term) { return term == null ? emptySet() : term.descendantsOrSelf() .filterIs(ASTNamedReferenceExpr.class) .filter(it -> it.getReferencedSym() != null) .collect(Collectors.mapping(ASTNamedReferenceExpr::getReferencedSym, Collectors.toSet())); } /** * Time methods cannot be moved ever, even when there are no side-effects. * The side effect they depend on is the program being executed. Are they * the only methods like that? */ private boolean cannotBeMoved(ASTExpression initializer) { return TIME_METHODS.anyMatch(initializer); } /** * Returns whether the block contains a return call or throws an exception. * Exclude blocks that have these things as part of an inner class. */ private static boolean hasExit(ASTStatement block) { return block.descendants() .map(asInstanceOf(ASTThrowStatement.class, ASTReturnStatement.class)) .nonEmpty(); } /** * Returns whether the variable is mentioned within the statement or not. */ private static boolean hasReferencesIn(ASTStatement stmt, ASTVariableDeclaratorId var) { return stmt.descendants(ASTVariableAccess.class) .crossFindBoundaries() .filterMatching(ASTNamedReferenceExpr::getReferencedSym, var.getSymbol()) .nonEmpty(); } /** Returns all the statements following the given local var declaration. */ private static NodeStream<ASTStatement> statementsAfter(ASTLocalVariableDeclaration node) { return node.asStream().followingSiblings().filterIs(ASTStatement.class); } }
5,472
39.843284
129
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/AbstractNamingConventionRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyBuilder.RegexPropertyBuilder; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.StringUtil.CaseConvention; /** * Base class for naming conventions rule. Not public API, but * used to uniformize eg property names between our rules. * * <p>Protected methods may leak API because concrete classes * are not final so they're package private instead * * @author Clément Fournier * @since 6.5.0 */ abstract class AbstractNamingConventionRule<T extends JavaNode> extends AbstractJavaRulechainRule { static final String CAMEL_CASE = "[a-z][a-zA-Z0-9]*"; static final String PASCAL_CASE = "[A-Z][a-zA-Z0-9]*"; @SafeVarargs protected AbstractNamingConventionRule(Class<? extends JavaNode> first, Class<? extends JavaNode>... visits) { super(first, visits); } /** The argument is interpreted as the display name, and is converted to camel case to get the property name. */ RegexPropertyBuilder defaultProp(String displayName) { return defaultProp(CaseConvention.SPACE_SEPARATED.convertTo(CaseConvention.CAMEL_CASE, displayName), displayName); } /** Returns a pre-filled builder with the given name and display name (for the description). */ RegexPropertyBuilder defaultProp(String name, String displayName) { return PropertyFactory.regexProperty(name + "Pattern") .desc("Regex which applies to " + displayName.trim() + " names") .defaultValue(defaultConvention()); } /** Default regex string for this kind of entities. */ abstract String defaultConvention(); /** Generic "kind" of node, eg "static method" or "utility class". */ abstract String kindDisplayName(T node, PropertyDescriptor<Pattern> descriptor); /** Extracts the name that should be pattern matched. */ abstract String nameExtractor(T node); void checkMatches(T node, PropertyDescriptor<Pattern> regex, Object data) { String name = nameExtractor(node); if (!getProperty(regex).matcher(name).matches()) { addViolation(data, node, new Object[]{ kindDisplayName(node, regex), name, getProperty(regex).toString(), }); } } }
2,689
36.361111
122
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/FormalParameterNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Enforces a naming convention for lambda and method parameters. * * @author Clément Fournier * @since 6.6.0 */ public final class FormalParameterNamingConventionsRule extends AbstractNamingConventionRule<ASTVariableDeclaratorId> { // These are not exhaustive, but are chosen to be the most useful, for a start private final PropertyDescriptor<Pattern> formalParamRegex = defaultProp("methodParameter", "formal parameter").build(); private final PropertyDescriptor<Pattern> finalFormalParamRegex = defaultProp("finalMethodParameter", "final formal parameter").build(); private final PropertyDescriptor<Pattern> lambdaParamRegex = defaultProp("lambdaParameter", "inferred-type lambda parameter").build(); private final PropertyDescriptor<Pattern> explicitLambdaParamRegex = defaultProp("explicitLambdaParameter", "explicitly-typed lambda parameter").build(); public FormalParameterNamingConventionsRule() { super(ASTVariableDeclaratorId.class); definePropertyDescriptor(formalParamRegex); definePropertyDescriptor(finalFormalParamRegex); definePropertyDescriptor(lambdaParamRegex); definePropertyDescriptor(explicitLambdaParamRegex); } @Override public Object visit(ASTVariableDeclaratorId node, Object data) { if (node.isLambdaParameter()) { checkMatches(node, node.isTypeInferred() ? lambdaParamRegex : explicitLambdaParamRegex, data); } else if (node.isFormalParameter()) { checkMatches(node, node.isFinal() ? finalFormalParamRegex : formalParamRegex, data); } return data; } @Override String defaultConvention() { return CAMEL_CASE; } @Override String nameExtractor(ASTVariableDeclaratorId node) { return node.getName(); } @Override String kindDisplayName(ASTVariableDeclaratorId node, PropertyDescriptor<Pattern> descriptor) { if (node.isLambdaParameter()) { return node.isTypeInferred() ? "lambda parameter" : "explicitly-typed lambda parameter"; } else if (node.isFormalParameter()) { // necessarily a method parameter here return node.isFinal() ? "final method parameter" : "method parameter"; } throw new UnsupportedOperationException("This rule doesn't handle this case"); } }
2,657
34.918919
157
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/MethodNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil; import net.sourceforge.pmd.properties.PropertyBuilder.RegexPropertyBuilder; import net.sourceforge.pmd.properties.PropertyDescriptor; public class MethodNamingConventionsRule extends AbstractNamingConventionRule<ASTMethodDeclaration> { private final Map<String, String> descriptorToDisplayName = new HashMap<>(); private final PropertyDescriptor<Pattern> instanceRegex = defaultProp("", "instance").build(); private final PropertyDescriptor<Pattern> staticRegex = defaultProp("static").build(); private final PropertyDescriptor<Pattern> nativeRegex = defaultProp("native").build(); private final PropertyDescriptor<Pattern> junit3Regex = defaultProp("JUnit 3 test").defaultValue("test[A-Z0-9][a-zA-Z0-9]*").build(); private final PropertyDescriptor<Pattern> junit4Regex = defaultProp("JUnit 4 test").build(); private final PropertyDescriptor<Pattern> junit5Regex = defaultProp("JUnit 5 test").build(); public MethodNamingConventionsRule() { super(ASTMethodDeclaration.class); definePropertyDescriptor(instanceRegex); definePropertyDescriptor(staticRegex); definePropertyDescriptor(nativeRegex); definePropertyDescriptor(junit3Regex); definePropertyDescriptor(junit4Regex); definePropertyDescriptor(junit5Regex); } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (node.isOverridden()) { return data; } if (node.hasModifiers(JModifier.NATIVE)) { checkMatches(node, nativeRegex, data); } else if (node.isStatic()) { checkMatches(node, staticRegex, data); } else if (TestFrameworksUtil.isJUnit5Method(node)) { checkMatches(node, junit5Regex, data); } else if (TestFrameworksUtil.isJUnit4Method(node)) { checkMatches(node, junit4Regex, data); } else if (TestFrameworksUtil.isJUnit3Method(node)) { checkMatches(node, junit3Regex, data); } else { checkMatches(node, instanceRegex, data); } return data; } @Override String defaultConvention() { return CAMEL_CASE; } @Override String nameExtractor(ASTMethodDeclaration node) { return node.getName(); } @Override RegexPropertyBuilder defaultProp(String name, String displayName) { String display = (displayName + " method").trim(); RegexPropertyBuilder prop = super.defaultProp(name.isEmpty() ? "method" : name, display); descriptorToDisplayName.put(prop.getName(), display); return prop; } @Override String kindDisplayName(ASTMethodDeclaration node, PropertyDescriptor<Pattern> descriptor) { return descriptorToDisplayName.get(descriptor.name()); } }
3,221
34.021739
137
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/LocalVariableNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Enforces a naming convention for local variables and other locally scoped variables. * * @author Clément Fournier * @since 6.6.0 */ public final class LocalVariableNamingConventionsRule extends AbstractNamingConventionRule<ASTVariableDeclaratorId> { // These are not exhaustive, but are chosen to be the most useful, for a start private final PropertyDescriptor<Pattern> localVarRegex = defaultProp("localVar", "non-final local variable").build(); private final PropertyDescriptor<Pattern> finalVarRegex = defaultProp("finalVar", "final local variable").build(); private final PropertyDescriptor<Pattern> exceptionBlockParameterRegex = defaultProp("catchParameter", "exception block parameter").build(); public LocalVariableNamingConventionsRule() { super(ASTVariableDeclaratorId.class); definePropertyDescriptor(localVarRegex); definePropertyDescriptor(finalVarRegex); definePropertyDescriptor(exceptionBlockParameterRegex); addRuleChainVisit(ASTVariableDeclaratorId.class); } @Override public Object visit(ASTVariableDeclaratorId node, Object data) { if (node.isExceptionBlockParameter()) { checkMatches(node, exceptionBlockParameterRegex, data); } else if (node.isLocalVariable()) { checkMatches(node, node.isFinal() ? finalVarRegex : localVarRegex, data); } return data; } @Override String defaultConvention() { return CAMEL_CASE; } @Override String nameExtractor(ASTVariableDeclaratorId node) { return node.getName(); } @Override String kindDisplayName(ASTVariableDeclaratorId node, PropertyDescriptor<Pattern> descriptor) { if (node.isExceptionBlockParameter()) { return "exception block parameter"; } else if (node.isLocalVariable()) { return node.isFinal() ? "final local variable" : "local variable"; } throw new UnsupportedOperationException("This rule doesn't handle this case"); } }
2,368
29.766234
144
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/FieldNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility.V_PUBLIC; import static net.sourceforge.pmd.lang.java.ast.JModifier.FINAL; import static net.sourceforge.pmd.lang.java.ast.JModifier.STATIC; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Configurable naming conventions for field declarations. * * @author Clément Fournier * @since 6.7.0 */ public class FieldNamingConventionsRule extends AbstractNamingConventionRule<ASTVariableDeclaratorId> { // TODO we need a more powerful scheme to match some fields, e.g. include modifiers/type // We could define a new property, but specifying property values as a single string doesn't scale private static final PropertyDescriptor<List<String>> EXCLUDED_NAMES = PropertyFactory.stringListProperty("exclusions") .desc("Names of fields to whitelist.") .defaultValues("serialVersionUID", "serialPersistentFields") .build(); private static final Set<String> MAKE_FIELD_STATIC_CLASS_ANNOT = setOf( "lombok.experimental.UtilityClass" ); private final PropertyDescriptor<Pattern> publicConstantFieldRegex = defaultProp("public constant").defaultValue("[A-Z][A-Z_0-9]*").build(); private final PropertyDescriptor<Pattern> constantFieldRegex = defaultProp("constant").desc("Regex which applies to non-public static final field names").defaultValue("[A-Z][A-Z_0-9]*").build(); private final PropertyDescriptor<Pattern> enumConstantRegex = defaultProp("enum constant").defaultValue("[A-Z][A-Z_0-9]*").build(); private final PropertyDescriptor<Pattern> finalFieldRegex = defaultProp("final field").build(); private final PropertyDescriptor<Pattern> staticFieldRegex = defaultProp("static field").build(); private final PropertyDescriptor<Pattern> defaultFieldRegex = defaultProp("defaultField", "field").build(); public FieldNamingConventionsRule() { super(ASTFieldDeclaration.class, ASTEnumConstant.class); definePropertyDescriptor(publicConstantFieldRegex); definePropertyDescriptor(constantFieldRegex); definePropertyDescriptor(enumConstantRegex); definePropertyDescriptor(finalFieldRegex); definePropertyDescriptor(staticFieldRegex); definePropertyDescriptor(defaultFieldRegex); definePropertyDescriptor(EXCLUDED_NAMES); } @Override public Object visit(ASTFieldDeclaration node, Object data) { for (ASTVariableDeclaratorId id : node) { if (getProperty(EXCLUDED_NAMES).contains(id.getVariableName())) { continue; } ASTAnyTypeDeclaration enclosingType = node.getEnclosingType(); boolean isFinal = node.hasModifiers(FINAL); boolean isStatic = node.hasModifiers(STATIC) || JavaAstUtils.hasAnyAnnotation(enclosingType, MAKE_FIELD_STATIC_CLASS_ANNOT); if (isFinal && isStatic) { checkMatches(id, node.getVisibility() == V_PUBLIC ? publicConstantFieldRegex : constantFieldRegex, data); } else if (isFinal) { checkMatches(id, finalFieldRegex, data); } else if (isStatic) { checkMatches(id, staticFieldRegex, data); } else { checkMatches(id, defaultFieldRegex, data); } } return data; } @Override public Object visit(ASTEnumConstant node, Object data) { // This inlines checkMatches because there's no variable declarator id if (!getProperty(enumConstantRegex).matcher(node.getImage()).matches()) { addViolation(data, node, new Object[]{ "enum constant", node.getImage(), getProperty(enumConstantRegex).toString(), }); } return data; } @Override String defaultConvention() { return CAMEL_CASE; } @Override String nameExtractor(ASTVariableDeclaratorId node) { return node.getName(); } @Override String kindDisplayName(ASTVariableDeclaratorId node, PropertyDescriptor<Pattern> descriptor) { boolean isFinal = node.hasModifiers(FINAL); boolean isStatic = node.hasModifiers(STATIC); if (isFinal && isStatic) { return node.getVisibility() == V_PUBLIC ? "public constant" : "constant"; } else if (isFinal) { return "final field"; } else if (isStatic) { return "static field"; } else { return "field"; } } }
5,281
39.015152
198
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryBoxingRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.Set; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTList; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.InvocationNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; import net.sourceforge.pmd.lang.java.types.TypePrettyPrint; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.lang.java.types.ast.ExprContext; /** * */ public class UnnecessaryBoxingRule extends AbstractJavaRulechainRule { private static final Set<String> INTERESTING_NAMES = setOf( "valueOf", "booleanValue", "charValue", "byteValue", "shortValue", "intValue", "longValue", "floatValue", "doubleValue" ); public UnnecessaryBoxingRule() { super(ASTMethodCall.class, ASTConstructorCall.class); } @Override public Object visit(ASTConstructorCall node, Object data) { if (node.getTypeMirror().isBoxedPrimitive()) { ASTExpression arg = ASTList.singleOrNull(node.getArguments()); if (arg == null) { return null; } JTypeMirror argT = arg.getTypeMirror(); if (argT.isPrimitive()) { checkBox((RuleContext) data, "boxing", node, arg, node.getMethodType().getFormalParameters().get(0)); } } return null; } @Override public Object visit(ASTMethodCall node, Object data) { if (INTERESTING_NAMES.contains(node.getMethodName())) { OverloadSelectionResult overload = node.getOverloadSelectionInfo(); if (overload.isFailed()) { return null; } JMethodSig m = overload.getMethodType(); boolean isValueOf = "valueOf".equals(node.getMethodName()); ASTExpression qualifier = node.getQualifier(); if (isValueOf && isWrapperValueOf(m)) { checkBox((RuleContext) data, "boxing", node, node.getArguments().get(0), m.getFormalParameters().get(0)); } else if (isValueOf && isStringValueOf(m) && qualifier != null) { checkUnboxing((RuleContext) data, node, qualifier.getTypeMirror()); } else if (!isValueOf && isUnboxingCall(m) && qualifier != null) { checkBox((RuleContext) data, "unboxing", node, qualifier, qualifier.getTypeMirror()); } } return null; } private boolean isUnboxingCall(JMethodSig m) { return !m.isStatic() && m.getDeclaringType().isBoxedPrimitive() && m.getArity() == 0; } private boolean isWrapperValueOf(JMethodSig m) { return m.isStatic() && m.getArity() == 1 && m.getDeclaringType().isBoxedPrimitive() && m.getFormalParameters().get(0).isPrimitive(); } private boolean isStringValueOf(JMethodSig m) { return m.isStatic() && (m.getArity() == 1 || m.getArity() == 2) && m.getDeclaringType().isBoxedPrimitive() && TypeTestUtil.isA(String.class, m.getFormalParameters().get(0)); } private void checkBox( RuleContext rctx, String opKind, ASTExpression conversionExpr, ASTExpression convertedExpr, JTypeMirror conversionInput ) { // the conversion looks like // CTX _ = conversion(sourceExpr) // we have the following data flow: // sourceExpr -> convInput -> convOutput -> ctx // 1 2 3 // where 1 and 3 are implicit conversions which we assume are // valid because the code should compile. // we want to report a violation if this is equivalent to // sourceExpr -> ctx // which basically means testing that convInput -> convOutput // may be performed implicitly. // We cannot just test compatibility of the source to the ctx, // because of situations like // int i = integer.byteValue() // where the conversion actually truncates the input value. JTypeMirror sourceType = convertedExpr.getTypeMirror(); JTypeMirror conversionOutput = conversionExpr.getTypeMirror(); ExprContext ctx = conversionExpr.getConversionContext(); JTypeMirror ctxType = ctx.getTargetType(); if (ctxType == null && conversionExpr instanceof InvocationNode) { ctxType = conversionOutput; } if (ctxType != null) { if (isImplicitlyConvertible(conversionInput, conversionOutput)) { boolean simpleConv = isReferenceSubtype(sourceType, conversionInput); final String reason; if (simpleConv && conversionInput.unbox().equals(conversionOutput)) { reason = "explicit unboxing"; } else if (simpleConv && conversionInput.box().equals(conversionOutput)) { reason = "explicit boxing"; } else if (sourceType.equals(conversionOutput)) { reason = "boxing of boxed value"; } else { if (sourceType.equals(ctxType)) { reason = opKind; } else { reason = "explicit conversion from " + TypePrettyPrint.prettyPrintWithSimpleNames(sourceType) + " to " + TypePrettyPrint.prettyPrintWithSimpleNames(ctxType); } } addViolation(rctx, conversionExpr, reason); } } } private void checkUnboxing( RuleContext rctx, ASTMethodCall methodCall, JTypeMirror conversionOutput ) { // methodCall is e.g. Integer.valueOf("42") // this checks, whether the resulting type "Integer" is e.g. assigned to an "int" // which triggers implicit unboxing. ExprContext ctx = methodCall.getConversionContext(); JTypeMirror ctxType = ctx.getTargetType(); if (ctxType != null) { if (isImplicitlyConvertible(conversionOutput, ctxType)) { if (conversionOutput.unbox().equals(ctxType)) { addViolation(rctx, methodCall, "implicit unboxing. Use " + conversionOutput.getSymbol().getSimpleName() + ".parse" + StringUtils.capitalize(ctxType.getSymbol().getSimpleName()) + "(...) instead"); } } } } private boolean isImplicitlyConvertible(JTypeMirror i, JTypeMirror o) { return i.box().isSubtypeOf(o.box()) || i.unbox().isSubtypeOf(o.unbox()); } /** * Whether {@code S <: T}, but ignoring primitive widening. * {@code isReferenceSubtype(int, double) == false} even though * {@code int.isSubtypeOf(double)}. */ private static boolean isReferenceSubtype(JTypeMirror s, JTypeMirror t) { return s.isPrimitive() ? t.equals(s) : s.isSubtypeOf(t); } }
7,690
36.8867
181
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UseDiamondOperatorRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.StringUtils; 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.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTTypeArguments; import net.sourceforge.pmd.lang.java.ast.InternalApiBridge; import net.sourceforge.pmd.lang.java.ast.InvocationNode; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeOps; import net.sourceforge.pmd.lang.java.types.TypingContext; import net.sourceforge.pmd.lang.java.types.ast.ExprContext; import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror; import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.CtorInvocationMirror; import net.sourceforge.pmd.lang.java.types.internal.infer.ExprMirror.InvocationMirror; import net.sourceforge.pmd.lang.java.types.internal.infer.Infer; import net.sourceforge.pmd.lang.java.types.internal.infer.MethodCallSite; import net.sourceforge.pmd.lang.java.types.internal.infer.ast.JavaExprMirrors; /** * Checks usages of explicity type arguments in a constructor call that * may be replaced by a diamond ({@code <>}). In order to determine this, * we mock a type resolution call site, which is equivalent to the expression * as if it had a diamond instead of explicit type arguments. We then perform * overload resolution for this fake call site. If overload resolution fails, * resolves to another overload, or if the inferred type is not compatible * with the expected context type, then the type arguments are unnecessary, * and removing them will not break the program. * * <p>Note that type inference in Java 8+ works differently from Java 7. * In Java 7, type arguments may be necessary in more places. The specifics * are however implemented within the type resolution code, and this rule does * not need to know about it. */ public class UseDiamondOperatorRule extends AbstractJavaRulechainRule { private static final String REPLACE_TYPE_ARGS_MESSAGE = "Explicit type arguments can be replaced by a diamond: `{0}`"; private static final String RAW_TYPE_MESSAGE = "Raw type use may be avoided by using a diamond: `{0}`"; /** * Maximum length of the argument list (including parentheses) for * it to be included in the violation message instead of an ellipsis {@code (...)}. */ private static final int MAX_ARGS_LENGTH = 25; public UseDiamondOperatorRule() { super(ASTConstructorCall.class); } @Override public Object visit(ASTConstructorCall ctorCall, Object data) { ASTClassOrInterfaceType newTypeNode = ctorCall.getTypeNode(); JTypeMirror newType = newTypeNode.getTypeMirror(); ASTTypeArguments targs = newTypeNode.getTypeArguments(); if (targs != null && targs.isDiamond() // if unresolved we can't know whether the class is generic or not || TypeOps.isUnresolved(newType)) { return null; } if (!newType.isGeneric() // targs may be null, in which case this would be a raw type || ctorCall.isAnonymousClass() && !supportsDiamondOnAnonymousClass(ctorCall)) { return null; } if (inferenceSucceedsWithoutTypeArgs(ctorCall)) { // report it JavaNode reportNode = targs == null ? newTypeNode : targs; String message = targs == null ? RAW_TYPE_MESSAGE : REPLACE_TYPE_ARGS_MESSAGE; String replaceWith = produceSuggestedExprImage(ctorCall); addViolationWithMessage(data, reportNode, message, new String[] { replaceWith }); } return null; } private static boolean supportsDiamondOnAnonymousClass(ASTConstructorCall ctorCall) { return ctorCall.getLanguageVersion().compareToVersion("9") >= 0; } /** Redo inference as described in the javadoc of this class. */ private static boolean inferenceSucceedsWithoutTypeArgs(ASTConstructorCall call) { ExprContext context = call.getConversionContext(); if (context.isMissing()) { return false; } Infer infer = InternalApiBridge.getInferenceEntryPoint(call); // this may not mutate the AST JavaExprMirrors factory = JavaExprMirrors.forObservation(infer); InvocationNode invocContext = InternalApiBridge.getTopLevelExprContext(call).getInvocNodeIfInvocContext(); ExprContext topmostContext; InvocationMirror mirror; if (invocContext == null) { CtorInvocationMirror defaultMirror = (CtorInvocationMirror) factory.getTopLevelInvocationMirror(call); mirror = new SpyInvocMirror(defaultMirror); topmostContext = call.getConversionContext(); } else { mirror = factory.getInvocationMirror(invocContext, (e, parent, self) -> { ExprMirror defaultImpl = factory.defaultMirrorMaker().createMirrorForSubexpression(e, parent, self); if (e == call) { return new SpyInvocMirror((CtorInvocationMirror) defaultImpl); } else { return defaultImpl; } }); if (invocContext instanceof ASTExpression) { topmostContext = ((ASTExpression) invocContext).getConversionContext(); } else { topmostContext = ExprContext.getMissingInstance(); } } JTypeMirror targetType = topmostContext.getPolyTargetType(false); MethodCallSite fakeCallSite = infer.newCallSite(mirror, targetType); infer.inferInvocationRecursively(fakeCallSite); return mirror.isEquivalentToUnderlyingAst() && topmostContext.acceptsType(mirror.getInferredType()); } private static String produceSuggestedExprImage(ASTConstructorCall ctor) { StringBuilder sb = new StringBuilder(30); sb.append("new "); produceSameTypeWithDiamond(ctor.getTypeNode(), sb, true); ASTArgumentList arguments = ctor.getArguments(); String argsString; if (arguments.size() == 0) { argsString = "()"; } else { CharSequence text = arguments.getText(); if (text.length() <= MAX_ARGS_LENGTH && !StringUtils.contains(text, '\n')) { argsString = text.toString(); } else { argsString = "(...)"; } } return sb.append(argsString).toString(); } private static StringBuilder produceSameTypeWithDiamond(ASTClassOrInterfaceType type, StringBuilder sb, boolean topLevel) { if (type.isFullyQualified()) { JTypeDeclSymbol sym = type.getTypeMirror().getSymbol(); Objects.requireNonNull(sym); sb.append(sym.getPackageName()).append('.'); } else { ASTClassOrInterfaceType qualifier = type.getQualifier(); if (qualifier != null) { produceSameTypeWithDiamond(qualifier, sb, false).append('.'); } } sb.append(type.getSimpleName()); return topLevel ? sb.append("<>") : sb; } /** Proxy that pretends it has diamond type args. */ private static final class SpyInvocMirror implements CtorInvocationMirror { private final CtorInvocationMirror base; SpyInvocMirror(CtorInvocationMirror base) { this.base = base; } // overridden methods @Override public @NonNull JTypeMirror getNewType() { // see doc of CtorInvocationMirror#getNewType return ((JClassType) base.getNewType()).getGenericTypeDeclaration(); } @Override public boolean isDiamond() { return true; // pretend it is } // delegated methods @Override public List<JTypeMirror> getExplicitTypeArguments() { return base.getExplicitTypeArguments(); } @Override public JavaNode getExplicitTargLoc(int i) { return base.getExplicitTargLoc(i); } @Override public void setInferredType(JTypeMirror mirror) { base.setInferredType(mirror); } @Override public JTypeMirror getInferredType() { return base.getInferredType(); } @Override public void setCtDecl(MethodCtDecl methodType) { base.setCtDecl(methodType); } @Override public @Nullable MethodCtDecl getCtDecl() { return base.getCtDecl(); } @Override public JavaNode getLocation() { return base.getLocation(); } @Override public @NonNull JClassType getEnclosingType() { return base.getEnclosingType(); } @Override public boolean isAnonymous() { return base.isAnonymous(); } @Override public Iterable<JMethodSig> getAccessibleCandidates(JTypeMirror newType) { return base.getAccessibleCandidates(newType); } @Override public @Nullable JTypeMirror getReceiverType() { return base.getReceiverType(); } @Override public String getName() { return base.getName(); } @Override public List<ExprMirror> getArgumentExpressions() { return base.getArgumentExpressions(); } @Override public int getArgumentCount() { return base.getArgumentCount(); } @Override public String toString() { return base.toString(); } @Override public TypingContext getTypingContext() { return base.getTypingContext(); } @Override public boolean isEquivalentToUnderlyingAst() { return base.isEquivalentToUnderlyingAst(); } } }
10,669
36.1777
127
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryModifierRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.lang.java.ast.JModifier.ABSTRACT; import static net.sourceforge.pmd.lang.java.ast.JModifier.FINAL; import static net.sourceforge.pmd.lang.java.ast.JModifier.PRIVATE; import static net.sourceforge.pmd.lang.java.ast.JModifier.PUBLIC; import static net.sourceforge.pmd.lang.java.ast.JModifier.STATIC; import java.util.EnumSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; 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.ASTRecordDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTResource; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class UnnecessaryModifierRule extends AbstractJavaRulechainRule { public UnnecessaryModifierRule() { super(ASTAnyTypeDeclaration.class, ASTMethodDeclaration.class, ASTResource.class, ASTFieldDeclaration.class, ASTConstructorDeclaration.class); addRuleChainVisit(ASTRecordDeclaration.class); } private void reportUnnecessaryModifiers(Object data, JavaNode node, JModifier unnecessaryModifier, String explanation) { reportUnnecessaryModifiers(data, node, EnumSet.of(unnecessaryModifier), explanation); } private void reportUnnecessaryModifiers(Object data, JavaNode node, Set<JModifier> unnecessaryModifiers, String explanation) { if (unnecessaryModifiers.isEmpty()) { return; } super.addViolation(data, node, new String[]{ formatUnnecessaryModifiers(unnecessaryModifiers), PrettyPrintingUtil.getPrintableNodeKind(node), PrettyPrintingUtil.getNodeName(node), explanation.isEmpty() ? "" : ": " + explanation, }); } private String formatUnnecessaryModifiers(Set<JModifier> set) { // prints in the standard modifier order (sorted by enum constant ordinal), // regardless of the actual order in which we checked return (set.size() > 1 ? "s" : "") + " '" + StringUtils.join(set, " ") + "'"; } @Override public Object visit(ASTEnumDeclaration node, Object data) { if (node.hasExplicitModifiers(PUBLIC)) { checkDeclarationInInterfaceType(data, node, EnumSet.of(PUBLIC)); } if (node.hasExplicitModifiers(STATIC)) { // a static enum reportUnnecessaryModifiers(data, node, STATIC, "nested enums are implicitly static"); } return data; } @Override public Object visit(ASTAnnotationTypeDeclaration node, Object data) { if (node.hasExplicitModifiers(ABSTRACT)) { // may have several violations, with different explanations reportUnnecessaryModifiers(data, node, ABSTRACT, "annotations types are implicitly abstract"); } if (!node.isNested()) { return data; } checkDeclarationInInterfaceType(data, node, EnumSet.of(PUBLIC)); if (node.hasExplicitModifiers(STATIC)) { // a static annotation reportUnnecessaryModifiers(data, node, STATIC, "nested annotation types are implicitly static"); } return data; } // also considers annotations, as should ASTAnyTypeDeclaration do private boolean isParentInterfaceType(AccessNode node) { ASTAnyTypeDeclaration enclosing = node.getEnclosingType(); return enclosing != null && enclosing.isInterface(); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isInterface() && node.hasExplicitModifiers(ABSTRACT)) { // an abstract interface reportUnnecessaryModifiers(data, node, ABSTRACT, "interface types are implicitly abstract"); } if (!node.isNested()) { return data; } checkDeclarationInInterfaceType(data, node, EnumSet.of(PUBLIC, STATIC)); if (node.hasExplicitModifiers(STATIC) && node.isInterface() && !isParentInterfaceType(node)) { // a static interface reportUnnecessaryModifiers(data, node, STATIC, "member interfaces are implicitly static"); } return data; } @Override public Object visit(final ASTMethodDeclaration node, Object data) { checkDeclarationInInterfaceType(data, node, EnumSet.of(PUBLIC, ABSTRACT)); if (node.hasExplicitModifiers(FINAL)) { // If the method is annotated by @SafeVarargs then it's ok if (!isSafeVarargs(node)) { if (node.hasModifiers(PRIVATE)) { reportUnnecessaryModifiers(data, node, FINAL, "private methods cannot be overridden"); } else { final ASTAnyTypeDeclaration n = node.getEnclosingType(); // A final method of an anonymous class / enum constant. Neither can be extended / overridden if (n.isAnonymous()) { reportUnnecessaryModifiers(data, node, FINAL, "an anonymous class cannot be extended"); } else if (n.isFinal()) { // notice: enum types are implicitly final if no enum constant declares a body reportUnnecessaryModifiers(data, node, FINAL, "the method is already in a final class"); } } } } return data; } @Override public Object visit(final ASTResource node, final Object data) { if (!node.isConciseResource() && node.asLocalVariableDeclaration().hasExplicitModifiers(FINAL)) { reportUnnecessaryModifiers(data, node, FINAL, "resource specifications are implicitly final"); } return data; } @Override public Object visit(ASTFieldDeclaration node, Object data) { checkDeclarationInInterfaceType(data, node, EnumSet.of(PUBLIC, STATIC, FINAL)); return data; } @Override public Object visit(ASTConstructorDeclaration node, Object data) { if (node.getEnclosingType().isEnum() && node.hasExplicitModifiers(PRIVATE)) { reportUnnecessaryModifiers(data, node, PRIVATE, "enum constructors are implicitly private"); } return data; } @Override public Object visit(ASTRecordDeclaration node, Object data) { if (node.hasExplicitModifiers(STATIC)) { reportUnnecessaryModifiers(data, node, STATIC, "records are implicitly static"); } if (node.hasExplicitModifiers(FINAL)) { reportUnnecessaryModifiers(data, node, FINAL, "records are implicitly final"); } return data; } private boolean isSafeVarargs(final ASTMethodDeclaration node) { return node.isAnnotationPresent(SafeVarargs.class.getName()); } private void checkDeclarationInInterfaceType(Object data, AccessNode member, Set<JModifier> unnecessary) { // third ancestor could be an AllocationExpression // if this is a method in an anonymous inner class ASTAnyTypeDeclaration parent = member.getEnclosingType(); if (isParentInterfaceType(member)) { unnecessary.removeIf(mod -> !member.hasExplicitModifiers(mod)); String explanation = "the " + PrettyPrintingUtil.getPrintableNodeKind(member) + " is declared in an " + PrettyPrintingUtil.getPrintableNodeKind(parent) + " type"; reportUnnecessaryModifiers(data, member, unnecessary, explanation); } } }
8,454
37.085586
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/ConfusingTernaryRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.BinaryOp; import net.sourceforge.pmd.lang.java.ast.UnaryOp; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * <code>if (x != y) { diff(); } else { same(); }</code> and<br> * <code>(!x ? diff() : same());</code> * * <p>XPath can handle the easy cases, e.g.:</p> * * <pre> * //IfStatement[ * Statement[2] * and Expression[ * EqualityExpression[@Image="!="] or * UnaryExpressionNotPlusMinus[@Image="!"]]] * </pre> * * <p>But "&amp;&amp;" and "||" are difficult, since we need a match for <i>all</i> * children instead of just one. This can be done by using a double-negative, * e.g.:</p> * * <pre> * not(*[not(<i>matchme</i>)]) * </pre> * * <p>Still, XPath is unable to handle arbitrarily nested cases, since it lacks * recursion, e.g.:</p> * * <pre> * if (((x != !y)) || !(x)) { * diff(); * } else { * same(); * } * </pre> */ public class ConfusingTernaryRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> IGNORE_ELSE_IF = booleanProperty("ignoreElseIf") .desc("Ignore conditions with an else-if case").defaultValue(false).build(); public ConfusingTernaryRule() { super(ASTIfStatement.class, ASTConditionalExpression.class); definePropertyDescriptor(IGNORE_ELSE_IF); } @Override public Object visit(ASTIfStatement node, Object data) { // look for "if (match) ..; else .." if (node.getNumChildren() == 3 && isMatch(node.getCondition())) { if (!getProperty(IGNORE_ELSE_IF) || !(node.getElseBranch() instanceof ASTIfStatement) && !(node.getParent() instanceof ASTIfStatement)) { addViolation(data, node); } } return data; } @Override public Object visit(ASTConditionalExpression node, Object data) { // look for "match ? .. : .." if (isMatch(node.getCondition())) { addViolation(data, node); } return data; } // recursive! private static boolean isMatch(ASTExpression node) { return isUnaryNot(node) || isNotEquals(node) || isConditionalWithAllMatches(node); } private static boolean isUnaryNot(ASTExpression node) { // look for "!x" return node instanceof ASTUnaryExpression && ((ASTUnaryExpression) node).getOperator().equals(UnaryOp.NEGATION); } private static boolean isNotEquals(ASTExpression node) { if (!(node instanceof ASTInfixExpression)) { return false; } ASTInfixExpression infix = (ASTInfixExpression) node; // look for "x != y" return infix.getOperator().equals(BinaryOp.NE) && !(infix.getLeftOperand() instanceof ASTNullLiteral) && !(infix.getRightOperand() instanceof ASTNullLiteral); } private static boolean isConditionalWithAllMatches(ASTExpression node) { // look for "match && match" or "match || match" if (node instanceof ASTInfixExpression) { ASTInfixExpression infix = (ASTInfixExpression) node; return (infix.getOperator() == BinaryOp.CONDITIONAL_AND || infix.getOperator() == BinaryOp.CONDITIONAL_OR) && isMatch(infix.getLeftOperand()) && isMatch(infix.getRightOperand()); } return false; } }
4,089
33.083333
118
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryLocalBeforeReturnRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; 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.symbols.JVariableSymbol; import net.sourceforge.pmd.properties.PropertyDescriptor; public class UnnecessaryLocalBeforeReturnRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> STATEMENT_ORDER_MATTERS = booleanProperty("statementOrderMatters").defaultValue(true).desc("If set to false this rule no longer requires the variable declaration and return statement to be on consecutive lines. Any variable that is used solely in a return statement will be reported.").build(); public UnnecessaryLocalBeforeReturnRule() { super(ASTReturnStatement.class); definePropertyDescriptor(STATEMENT_ORDER_MATTERS); } @Override public Object visit(ASTReturnStatement returnStmt, Object data) { if (!(returnStmt.getExpr() instanceof ASTVariableAccess)) { return null; } ASTVariableAccess varExpr = (ASTVariableAccess) returnStmt.getExpr(); JVariableSymbol sym = varExpr.getReferencedSym(); if (sym == null) { return null; } ASTVariableDeclaratorId varDecl = sym.tryGetNode(); if (varDecl == null || !varDecl.isLocalVariable() || varDecl.getDeclaredAnnotations().nonEmpty()) { return null; } if (varDecl.getLocalUsages().size() != 1) { return null; } // then this is the only usage if (!getProperty(STATEMENT_ORDER_MATTERS) || varDecl.ancestors(ASTLocalVariableDeclaration.class).firstOrThrow().getNextSibling() == returnStmt) { addViolation(data, varDecl, varDecl.getName()); } return null; } }
2,241
39.763636
347
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/OnlyOneReturnRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; public class OnlyOneReturnRule extends AbstractJavaRulechainRule { public OnlyOneReturnRule() { super(ASTMethodDeclaration.class); } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (node.getBody() == null) { return null; } NodeStream<ASTReturnStatement> returnsExceptLast = node.getBody().descendants(ASTReturnStatement.class).dropLast(1); for (ASTReturnStatement returnStmt : returnsExceptLast) { addViolation(data, returnStmt); } return null; } }
978
28.666667
79
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/FieldDeclarationsShouldBeAtStartOfClassRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEmptyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumConstant; 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.ASTInitializer; 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; /** * Detects fields that are declared after methods, constructors, etc. It was a * XPath rule, but the Java version is much faster. */ public class FieldDeclarationsShouldBeAtStartOfClassRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> IGNORE_ANONYMOUS_CLASS_DECLARATIONS = booleanProperty("ignoreAnonymousClassDeclarations") .defaultValue(true) .desc("Ignore field declarations, that are initialized with an anonymous class creation expression").build(); private static final PropertyDescriptor<Boolean> IGNORE_ENUM_DECLARATIONS = booleanProperty("ignoreEnumDeclarations") .defaultValue(true) .desc("Ignore enum declarations that precede fields").build(); private static final PropertyDescriptor<Boolean> IGNORE_INTERFACE_DECLARATIONS = booleanProperty("ignoreInterfaceDeclarations") .defaultValue(false) .desc("Ignore interface declarations that precede fields").build(); public FieldDeclarationsShouldBeAtStartOfClassRule() { super(ASTAnyTypeDeclaration.class); definePropertyDescriptor(IGNORE_ANONYMOUS_CLASS_DECLARATIONS); definePropertyDescriptor(IGNORE_INTERFACE_DECLARATIONS); definePropertyDescriptor(IGNORE_ENUM_DECLARATIONS); } @Override public Object visitJavaNode(JavaNode node, Object data) { assert node instanceof ASTAnyTypeDeclaration; return visit((ASTAnyTypeDeclaration) node, data); } public Object visit(ASTAnyTypeDeclaration node, Object data) { boolean inStartOfClass = true; for (ASTBodyDeclaration declaration : node.getDeclarations()) { if (!isAllowedAtStartOfClass(declaration)) { inStartOfClass = false; } if (!inStartOfClass && declaration instanceof ASTFieldDeclaration) { ASTFieldDeclaration field = (ASTFieldDeclaration) declaration; if (!isInitializerOk(field)) { addViolation(data, declaration); } } } return null; } private boolean isAllowedAtStartOfClass(ASTBodyDeclaration declaration) { return declaration instanceof ASTFieldDeclaration || declaration instanceof ASTInitializer || declaration instanceof ASTEnumConstant || declaration instanceof ASTEmptyDeclaration || declaration instanceof ASTEnumDeclaration && getProperty(IGNORE_ENUM_DECLARATIONS) || isInterface(declaration) && getProperty(IGNORE_INTERFACE_DECLARATIONS); } private boolean isInterface(ASTBodyDeclaration declaration) { return declaration instanceof ASTAnyTypeDeclaration && ((ASTAnyTypeDeclaration) declaration).isRegularInterface(); } private boolean isInitializerOk(ASTFieldDeclaration fieldDeclaration) { if (getProperty(IGNORE_ANONYMOUS_CLASS_DECLARATIONS) && fieldDeclaration.getVarIds().count() == 1) { ASTExpression initializer = fieldDeclaration.getVarIds().firstOrThrow().getInitializer(); return JavaAstUtils.isAnonymousClassCreation(initializer); } return false; } }
4,198
43.2
121
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryImportRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; import net.sourceforge.pmd.lang.java.ast.JavaComment; import net.sourceforge.pmd.lang.java.ast.JavadocComment; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.symbols.JAccessibleElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JExecutableSymbol; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.symbols.table.ScopeInfo; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainIterator; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.JVariableSig; import net.sourceforge.pmd.lang.java.types.OverloadSelectionResult; import net.sourceforge.pmd.lang.java.types.TypeSystem; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.util.CollectionUtil; /** * Detects unnecessary imports. * * <p>For PMD 7 I had hoped this rule could be rewritten to use the * symbol table implementation directly instead of reimplementing a * symbol table (with less care). This would be good for performance * and correctness. Modifying the symbol table chain to track which * import is used is hard though, mostly because the API to expose * is unclear (we wouldn't want symbol tables to expose a mutable API). */ public class UnnecessaryImportRule extends AbstractJavaRule { private static final String UNUSED_IMPORT_MESSAGE = "Unused import ''{0}''"; private static final String UNUSED_STATIC_IMPORT_MESSAGE = "Unused static import ''{0}''"; private static final String DUPLICATE_IMPORT_MESSAGE = "Duplicate import ''{0}''"; private static final String IMPORT_FROM_SAME_PACKAGE_MESSAGE = "Unnecessary import from the current package ''{0}''"; private static final String IMPORT_FROM_JAVA_LANG_MESSAGE = "Unnecessary import from the java.lang package ''{0}''"; private final Set<ImportWrapper> allSingleNameImports = new HashSet<>(); private final Set<ImportWrapper> allImportsOnDemand = new HashSet<>(); private final Set<ImportWrapper> unnecessaryJavaLangImports = new HashSet<>(); private final Set<ImportWrapper> unnecessaryImportsFromSamePackage = new HashSet<>(); /* * Patterns to match the following constructs: * * @see package.class#member(param, param) label * {@linkplain package.class#member(param, param) label} * {@link package.class#member(param, param) label} * {@link package.class#field} * {@value package.class#field} * * @throws package.class label * @exception package.class label */ /* package.class#member(param, param) */ private static final String TYPE_PART_GROUP = "((?:\\p{Alpha}\\w*\\.)*(?:\\p{Alpha}\\w*))?(?:#\\w*(?:\\(([.\\w\\s,\\[\\]]*)\\))?)?"; private static final Pattern SEE_PATTERN = Pattern.compile("@see\\s+" + TYPE_PART_GROUP); private static final Pattern LINK_PATTERNS = Pattern.compile("\\{@link(?:plain)?\\s+" + TYPE_PART_GROUP + "[\\s\\}]"); private static final Pattern VALUE_PATTERN = Pattern.compile("\\{@value\\s+(\\p{Alpha}\\w*)[\\s#\\}]"); private static final Pattern THROWS_PATTERN = Pattern.compile("@throws\\s+(\\p{Alpha}\\w*)"); private static final Pattern EXCEPTION_PATTERN = Pattern.compile("@exception\\s+(\\p{Alpha}\\w*)"); /* // @link substring="a" target="package.class#member(param, param)" */ private static final Pattern LINK_IN_SNIPPET = Pattern .compile("//\\s*@link\\s+(?:.*?)?target=[\"']?" + TYPE_PART_GROUP + "[\"']?"); private static final Pattern[] PATTERNS = { SEE_PATTERN, LINK_PATTERNS, VALUE_PATTERN, THROWS_PATTERN, EXCEPTION_PATTERN, LINK_IN_SNIPPET }; @Override public Object visit(ASTCompilationUnit node, Object data) { this.allSingleNameImports.clear(); this.allImportsOnDemand.clear(); this.unnecessaryJavaLangImports.clear(); this.unnecessaryImportsFromSamePackage.clear(); String packageName = node.getPackageName(); for (ASTImportDeclaration importDecl : node.children(ASTImportDeclaration.class)) { visitImport(importDecl, data, packageName); } for (ImportWrapper wrapper : allSingleNameImports) { if ("java.lang".equals(wrapper.node.getPackageName())) { if (!isJavaLangImportNecessary(node, wrapper)) { // the import is not shadowing something unnecessaryJavaLangImports.add(wrapper); } } } super.visit(node, data); visitComments(node); doReporting(data); return data; } private void doReporting(Object data) { for (ImportWrapper wrapper : allSingleNameImports) { String message = wrapper.isStatic() ? UNUSED_STATIC_IMPORT_MESSAGE : UNUSED_IMPORT_MESSAGE; reportWithMessage(wrapper.node, data, message); } for (ImportWrapper wrapper : allImportsOnDemand) { String message = wrapper.isStatic() ? UNUSED_STATIC_IMPORT_MESSAGE : UNUSED_IMPORT_MESSAGE; reportWithMessage(wrapper.node, data, message); } // remove unused ones, they have already been reported unnecessaryJavaLangImports.removeAll(allSingleNameImports); unnecessaryJavaLangImports.removeAll(allImportsOnDemand); unnecessaryImportsFromSamePackage.removeAll(allSingleNameImports); unnecessaryImportsFromSamePackage.removeAll(allImportsOnDemand); for (ImportWrapper wrapper : unnecessaryJavaLangImports) { reportWithMessage(wrapper.node, data, IMPORT_FROM_JAVA_LANG_MESSAGE); } for (ImportWrapper wrapper : unnecessaryImportsFromSamePackage) { reportWithMessage(wrapper.node, data, IMPORT_FROM_SAME_PACKAGE_MESSAGE); } } private boolean isJavaLangImportNecessary(ASTCompilationUnit node, ImportWrapper wrapper) { ShadowChainIterator<JTypeMirror, ScopeInfo> iter = node.getSymbolTable().types().iterateResults(wrapper.node.getImportedSimpleName()); if (iter.hasNext()) { iter.next(); if (iter.getScopeTag() == ScopeInfo.SINGLE_IMPORT) { if (iter.hasNext()) { iter.next(); // the import is shadowing something else return iter.getScopeTag() != ScopeInfo.JAVA_LANG; } } } return false; } private void visitComments(ASTCompilationUnit node) { // todo improve that when we have a javadoc parser for (JavaComment comment : node.getComments()) { if (!(comment instanceof JavadocComment)) { continue; } for (Pattern p : PATTERNS) { Matcher m = p.matcher(comment.getImage()); while (m.find()) { String fullname = m.group(1); if (fullname != null) { // may be null for "@see #" and "@link #" removeReferenceSingleImport(fullname); } if (m.groupCount() > 1) { fullname = m.group(2); if (fullname != null) { for (String param : fullname.split("\\s*,\\s*")) { removeReferenceSingleImport(param); } } } if (allSingleNameImports.isEmpty()) { return; } } } } } private void visitImport(ASTImportDeclaration node, Object data, String thisPackageName) { if (thisPackageName.equals(node.getPackageName())) { unnecessaryImportsFromSamePackage.add(new ImportWrapper(node)); } Set<ImportWrapper> container = node.isImportOnDemand() ? allImportsOnDemand : allSingleNameImports; if (!container.add(new ImportWrapper(node))) { // duplicate reportWithMessage(node, data, DUPLICATE_IMPORT_MESSAGE); } } private void reportWithMessage(ASTImportDeclaration node, Object data, String message) { addViolationWithMessage(data, node, message, new String[] { PrettyPrintingUtil.prettyImport(node) }); } @Override public Object visit(ASTClassOrInterfaceType node, Object data) { if (node.getQualifier() == null && !node.isFullyQualified() && node.getTypeMirror().isClassOrInterface()) { JClassSymbol symbol = ((JClassType) node.getTypeMirror()).getSymbol(); ShadowChainIterator<JTypeMirror, ScopeInfo> scopeIter = node.getSymbolTable().types().iterateResults(node.getSimpleName()); checkScopeChain(false, symbol, scopeIter, ts -> true, false); } return super.visit(node, data); } @Override public Object visit(ASTMethodCall node, Object data) { if (node.getQualifier() == null) { OverloadSelectionResult overload = node.getOverloadSelectionInfo(); if (overload.isFailed()) { return null; // todo we're erring towards FPs } ShadowChainIterator<JMethodSig, ScopeInfo> scopeIter = node.getSymbolTable().methods().iterateResults(node.getMethodName()); JExecutableSymbol symbol = overload.getMethodType().getSymbol(); checkScopeChain(true, symbol, scopeIter, methods -> CollectionUtil.any(methods, m -> m.getSymbol().equals(symbol)), true); } return super.visit(node, data); } @Override public Object visit(ASTVariableAccess node, Object data) { JVariableSymbol sym = node.getReferencedSym(); if (sym != null && sym.isField() && ((JFieldSymbol) sym).isStatic()) { if (node.getParent() instanceof ASTSwitchLabel && node.ancestors(ASTSwitchLike.class).take(1).any(ASTSwitchLike::isEnumSwitch)) { // special scoping rules, see JSymbolTable#variables doc return null; } ShadowChainIterator<JVariableSig, ScopeInfo> scopeIter = node.getSymbolTable().variables().iterateResults(node.getName()); checkScopeChain(false, (JFieldSymbol) sym, scopeIter, ts -> true, true); } return null; } private <T> void checkScopeChain(boolean recursive, JAccessibleElementSymbol symbol, ShadowChainIterator<T, ScopeInfo> scopeIter, Predicate<List<T>> containsTarget, boolean onlyStatic) { while (scopeIter.hasNext()) { scopeIter.next(); // must be the first result // todo make sure new Outer().new Inner() does not mark Inner as used if (containsTarget.test(scopeIter.getResults())) { // We found the declaration bringing the symbol in scope // If it's an import, then it's used. However, maybe it's from java.lang. if (scopeIter.getScopeTag() == ScopeInfo.SINGLE_IMPORT) { allSingleNameImports.removeIf( it -> (it.isStatic() || !onlyStatic) && symbol.getSimpleName().equals(it.node.getImportedSimpleName()) ); } else if (scopeIter.getScopeTag() == ScopeInfo.IMPORT_ON_DEMAND) { allImportsOnDemand.removeIf(it -> { if (!it.isStatic() && onlyStatic) { return false; } // This is the class that contains the symbol // we're looking for. // We have to test whether this symbol is contained // by the imported type or package. JClassSymbol symbolOwner = symbol.getEnclosingClass(); if (symbolOwner == null) { // package import on demand return it.node.getImportedName().equals(symbol.getPackageName()); } else { if (it.node.getImportedName().equals(symbolOwner.getCanonicalName())) { // importing the container directly return it.isStatic() == symbol.isStatic(); } // maybe we're importing a subclass of the container. TypeSystem ts = symbolOwner.getTypeSystem(); JClassSymbol importedContainer = ts.getClassSymbol(it.node.getImportedName()); return importedContainer == null // insufficient classpath, err towards FNs || TypeTestUtil.isA(ts.rawType(symbolOwner), ts.rawType(importedContainer)); } }); } return; } if (!recursive) { break; } } // unknown reference } /** We found a reference to the type given by the name. */ private void removeReferenceSingleImport(String referenceName) { String expectedImport = StringUtils.substringBefore(referenceName, "."); allSingleNameImports.removeIf(it -> expectedImport.equals(it.node.getImportedSimpleName())); } /** Override the equal behaviour of ASTImportDeclaration to put it into a set. */ private static final class ImportWrapper { private final ASTImportDeclaration node; private ImportWrapper(ASTImportDeclaration node) { this.node = node; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (getClass() != o.getClass()) { return false; } ImportWrapper that = (ImportWrapper) o; return node.getImportedName().equals(that.node.getImportedName()) && node.isImportOnDemand() == that.node.isImportOnDemand() && this.isStatic() == that.isStatic(); } @Override public int hashCode() { return node.getImportedName().hashCode() * 31 + Boolean.hashCode(node.isStatic()) + 37 * Boolean.hashCode(node.isImportOnDemand()); } private boolean isStatic() { return this.node.isStatic(); } } }
15,998
42.008065
144
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/EmptyControlStatementRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTDoStatement; import net.sourceforge.pmd.lang.java.ast.ASTEmptyStatement; 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.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTInitializer; import net.sourceforge.pmd.lang.java.ast.ASTResource; import net.sourceforge.pmd.lang.java.ast.ASTResourceList; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.ast.ASTSynchronizedStatement; 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.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; public class EmptyControlStatementRule extends AbstractJavaRulechainRule { public EmptyControlStatementRule() { super(ASTFinallyClause.class, ASTSynchronizedStatement.class, ASTTryStatement.class, ASTDoStatement.class, ASTBlock.class, ASTForStatement.class, ASTForeachStatement.class, ASTWhileStatement.class, ASTIfStatement.class, ASTSwitchStatement.class, ASTInitializer.class); } @Override public Object visit(ASTFinallyClause node, Object data) { if (isEmpty(node.getBody())) { asCtx(data).addViolationWithMessage(node, "Empty finally clause"); } return null; } @Override public Object visit(ASTSynchronizedStatement node, Object data) { if (isEmpty(node.getBody())) { asCtx(data).addViolationWithMessage(node, "Empty synchronized statement"); } return null; } @Override public Object visit(ASTSwitchStatement node, Object data) { if (node.getNumChildren() == 1) { asCtx(data).addViolationWithMessage(node, "Empty switch statement"); } return null; } @Override public Object visit(ASTBlock node, Object data) { if (isEmpty(node) && node.getParent() instanceof ASTBlock) { asCtx(data).addViolationWithMessage(node, "Empty block"); } return null; } @Override public Object visit(ASTIfStatement node, Object data) { if (isEmpty(node.getThenBranch())) { asCtx(data).addViolationWithMessage(node, "Empty if statement"); } if (node.hasElse() && isEmpty(node.getElseBranch())) { asCtx(data).addViolationWithMessage(node.getElseBranch(), "Empty else statement"); } return null; } @Override public Object visit(ASTWhileStatement node, Object data) { if (isEmpty(node.getBody())) { asCtx(data).addViolationWithMessage(node, "Empty while statement"); } return null; } @Override public Object visit(ASTForStatement node, Object data) { if (isEmpty(node.getBody())) { asCtx(data).addViolationWithMessage(node, "Empty for statement"); } return null; } @Override public Object visit(ASTForeachStatement node, Object data) { if (JavaRuleUtil.isExplicitUnusedVarName(node.getVarId().getName())) { // allow `for (ignored : iterable) {}` return null; } if (isEmpty(node.getBody())) { asCtx(data).addViolationWithMessage(node, "Empty foreach statement"); } return null; } @Override public Object visit(ASTDoStatement node, Object data) { if (isEmpty(node.getBody())) { asCtx(data).addViolationWithMessage(node, "Empty do..while statement"); } return null; } @Override public Object visit(ASTInitializer node, Object data) { if (isEmpty(node.getBody())) { asCtx(data).addViolationWithMessage(node, "Empty initializer statement"); } return null; } @Override public Object visit(ASTTryStatement node, Object data) { if (isEmpty(node.getBody())) { // all resources must be explicitly ignored boolean allResourcesIgnored = true; boolean hasResource = false; ASTResourceList resources = node.getResources(); if (resources != null) { for (ASTResource resource : resources) { hasResource = true; String name = resource.getStableName(); if (!JavaRuleUtil.isExplicitUnusedVarName(name)) { allResourcesIgnored = false; break; } } } if (hasResource && !allResourcesIgnored) { asCtx(data).addViolationWithMessage(node, "Empty try body - you could rename the resource to ''ignored''"); } else if (!hasResource) { asCtx(data).addViolationWithMessage(node, "Empty try body"); } } return null; } private boolean isEmpty(JavaNode node) { return node instanceof ASTBlock && node.getNumChildren() == 0 || node instanceof ASTEmptyStatement; } }
5,531
35.394737
123
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/ClassNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.java.ast.ASTAnnotationTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTRecordDeclaration; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil; import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Configurable naming conventions for type declarations. */ public class ClassNamingConventionsRule extends AbstractNamingConventionRule<ASTAnyTypeDeclaration> { private final PropertyDescriptor<Pattern> classRegex = defaultProp("class", "concrete class").build(); private final PropertyDescriptor<Pattern> abstractClassRegex = defaultProp("abstract class").build(); private final PropertyDescriptor<Pattern> interfaceRegex = defaultProp("interface").build(); private final PropertyDescriptor<Pattern> enumerationRegex = defaultProp("enum").build(); private final PropertyDescriptor<Pattern> annotationRegex = defaultProp("annotation").build(); private final PropertyDescriptor<Pattern> utilityClassRegex = defaultProp("utility class").build(); private final PropertyDescriptor<Pattern> testClassRegex = defaultProp("test class") .desc("Regex which applies to test class names. Since PMD 6.52.0.") .defaultValue("^Test.*$|^[A-Z][a-zA-Z0-9]*Test(s|Case)?$").build(); public ClassNamingConventionsRule() { super(ASTClassOrInterfaceDeclaration.class, ASTEnumDeclaration.class, ASTAnnotationTypeDeclaration.class, ASTRecordDeclaration.class); definePropertyDescriptor(classRegex); definePropertyDescriptor(abstractClassRegex); definePropertyDescriptor(interfaceRegex); definePropertyDescriptor(enumerationRegex); definePropertyDescriptor(annotationRegex); definePropertyDescriptor(utilityClassRegex); definePropertyDescriptor(testClassRegex); } private boolean isTestClass(ASTClassOrInterfaceDeclaration node) { return !node.isNested() && TestFrameworksUtil.isTestClass(node); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isAbstract()) { checkMatches(node, abstractClassRegex, data); } else if (isTestClass(node)) { checkMatches(node, testClassRegex, data); } else if (JavaRuleUtil.isUtilityClass(node)) { checkMatches(node, utilityClassRegex, data); } else if (node.isInterface()) { checkMatches(node, interfaceRegex, data); } else { checkMatches(node, classRegex, data); } return data; } @Override public Object visit(ASTEnumDeclaration node, Object data) { checkMatches(node, enumerationRegex, data); return data; } @Override public Object visit(ASTRecordDeclaration node, Object data) { checkMatches(node, classRegex, data); // property? return data; } @Override public Object visit(ASTAnnotationTypeDeclaration node, Object data) { checkMatches(node, annotationRegex, data); return data; } @Override String defaultConvention() { return PASCAL_CASE; } @Override String nameExtractor(ASTAnyTypeDeclaration node) { return node.getSimpleName(); } @Override String kindDisplayName(ASTAnyTypeDeclaration node, PropertyDescriptor<Pattern> descriptor) { return JavaRuleUtil.isUtilityClass(node) ? "utility class" : PrettyPrintingUtil.getPrintableNodeKind(node); } }
4,059
36.247706
115
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/LocalVariableCouldBeFinalRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; public class LocalVariableCouldBeFinalRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> IGNORE_FOR_EACH = booleanProperty("ignoreForEachDecl").defaultValue(false).desc("Ignore non-final loop variables in a for-each statement.").build(); public LocalVariableCouldBeFinalRule() { super(ASTLocalVariableDeclaration.class); definePropertyDescriptor(IGNORE_FOR_EACH); addRuleChainVisit(ASTLocalVariableDeclaration.class); } @Override public Object visit(ASTLocalVariableDeclaration node, Object data) { if (node.isFinal()) { // also for implicit finals, like resources return data; } if (getProperty(IGNORE_FOR_EACH) && node.getParent() instanceof ASTForeachStatement) { return data; } MethodArgumentCouldBeFinalRule.checkForFinal((RuleContext) data, this, node.getVarIds()); return data; } }
1,483
37.051282
138
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UselessParenthesesRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule.Necessity.ALWAYS; import static net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule.Necessity.BALANCING; import static net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule.Necessity.CLARIFYING; import static net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule.Necessity.NEVER; import static net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule.Necessity.definitely; import static net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule.Necessity.necessaryIf; import net.sourceforge.pmd.lang.java.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTConditionalExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.BinaryOp; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.AssertionUtil; public final class UselessParenthesesRule extends AbstractJavaRulechainRule { // todo rename to UnnecessaryParentheses private static final PropertyDescriptor<Boolean> IGNORE_CLARIFYING = PropertyFactory.booleanProperty("ignoreClarifying") .defaultValue(true) .desc("Ignore parentheses that separate expressions of difference precedence," + " like in `(a % 2 == 0) ? x : -x`") .build(); private static final PropertyDescriptor<Boolean> IGNORE_BALANCING = PropertyFactory.booleanProperty("ignoreBalancing") .defaultValue(true) .desc("Ignore unnecessary parentheses that appear balanced around an equality " + "operator, because the other operand requires parentheses." + "For example, in `(a == null) == (b == null)`, only the second pair " + "of parentheses is necessary, but the expression is clearer that way.") .build(); public UselessParenthesesRule() { super(ASTExpression.class); definePropertyDescriptor(IGNORE_CLARIFYING); definePropertyDescriptor(IGNORE_BALANCING); } private boolean reportClarifying() { return !getProperty(IGNORE_CLARIFYING); } private boolean reportBalancing() { return !getProperty(IGNORE_BALANCING); } @Override public Object visitJavaNode(JavaNode node, Object data) { if (node instanceof ASTExpression) { checkExpr((ASTExpression) node, data); } else { throw new IllegalArgumentException("Expected an expression, got " + node); } return null; } private void checkExpr(ASTExpression e, Object data) { if (!e.isParenthesized()) { return; } Necessity necessity = needsParentheses(e, e.getParent()); if (necessity == NEVER || reportClarifying() && necessity == CLARIFYING || reportBalancing() && necessity == BALANCING) { addViolation(data, e); } } static Necessity needsParentheses(ASTExpression inner, JavaNode outer) { // Note: as of jdk 15, PatternExpression cannot be parenthesized // TypeExpression may never be parenthesized either assert inner.isParenthesized() : inner + " is not parenthesized"; if (inner.getParenthesisDepth() > 1 || !(outer instanceof ASTExpression)) { // ((a + b)) unnecessary // new int[(2)] unnecessary // return (1 + 2); return NEVER; } if (inner instanceof ASTPrimaryExpression || inner instanceof ASTSwitchExpression) { return NEVER; } if (outer instanceof ASTLambdaExpression) { // () -> (a + b) unnecessary // () -> (() -> b) unnecessary // () -> (a ? b : c); unnecessary unless the parent of the lambda is itself a ternary if (inner instanceof ASTLambdaExpression) { return NEVER; } return definitely(inner instanceof ASTConditionalExpression && outer.getParent() instanceof ASTConditionalExpression); } if (inner instanceof ASTAssignmentExpression) { // a * (b = c) necessary // a ? (b = c) : d necessary // a = (b = c) associative // (a = b) = c (impossible) return outer instanceof ASTAssignmentExpression ? NEVER : ALWAYS; } if (inner instanceof ASTConditionalExpression) { // a ? (b ? c : d) : e necessary // a ? b : (c ? d : e) associative // (a ? b : c) ? d : e necessary if (outer instanceof ASTConditionalExpression) { return inner.getIndexInParent() == 2 ? NEVER // last child : ALWAYS; } else { return necessaryIf(!(outer instanceof ASTAssignmentExpression)); } } if (inner instanceof ASTLambdaExpression) { // a ? (() -> b) + c : d invalid, but necessary // a ? (() -> b) : d clarifying return outer instanceof ASTConditionalExpression ? CLARIFYING : definitely(!(outer instanceof ASTAssignmentExpression)); } if (inner instanceof ASTInfixExpression) { if (outer instanceof ASTInfixExpression) { BinaryOp inop = ((ASTInfixExpression) inner).getOperator(); BinaryOp outop = ((ASTInfixExpression) outer).getOperator(); int comp = outop.comparePrecedence(inop); // (a * b) + c unnecessary // a * (b + c) necessary // a + (b + c) unnecessary // (a + b) + c unnecessary // (a - b) + c clarifying if (comp > 0) { return ALWAYS; // outer has greater precedence } else if (comp < 0) { return CLARIFYING; // outer has lower precedence, but the operators are different } // the rest deals with ties in precedence if (inner.getIndexInParent() == 1) { // parentheses are on the right // eg a - (b + c) if (associatesRightWith(outop, inop, (ASTInfixExpression) inner, (ASTInfixExpression) outer)) { // a & (b & c) // a | (b | c) // a ^ (b ^ c) // a && (b && c) // a || (b || c) return NEVER; } else { return ALWAYS; } } else { // parentheses are on the left // eg (a + b) + c if (outop.hasSamePrecedenceAs(BinaryOp.EQ) // EQ or NE && ((ASTInfixExpression) outer).getRightOperand().isParenthesized()) { // (a == null) == (b == null) return BALANCING; } else if (outop == BinaryOp.ADD && inop.hasSamePrecedenceAs(BinaryOp.ADD) && inner.getTypeMirror().isNumeric() && !((ASTInfixExpression) outer).getTypeMirror().isNumeric()) { return CLARIFYING; } return NEVER; } } else { // outer !is ASTInfixExpression if (outer instanceof ASTConditionalExpression && inner.getIndexInParent() == 0) { // (a == b) ? .. : .. return CLARIFYING; } return necessaryIf(isUnary(outer) || outer instanceof ASTPrimaryExpression); } } if (isUnary(inner)) { return isUnary(outer) ? NEVER : necessaryIf(outer instanceof ASTPrimaryExpression); } throw AssertionUtil.shouldNotReachHere("Unhandled case inside " + outer); } private static boolean isUnary(JavaNode expr) { return expr instanceof ASTUnaryExpression || expr instanceof ASTCastExpression; } // Returns true if it is safe to remove parentheses in the expression `A outop (B inop C)` // outop and inop have the same precedence class private static boolean associatesRightWith(BinaryOp outop, BinaryOp inop, ASTInfixExpression inner, ASTInfixExpression outer) { /* Notes about associativity: - Integer multiplication/addition is associative when the operands are all of the same type. - Floating-point multiplication/addition is not associative. - The boolean equality operators are associative, but input type != output type in general - Bitwise and logical operators are associative - The conditional-OR/AND operator is fully associative with respect to both side effects and result value. */ switch (inop) { case AND: case OR: case XOR: case CONDITIONAL_AND: case CONDITIONAL_OR: return true; case MUL: // a * (b * c) -- yes // a * (b / c) -- no, could change semantics // a * (b % c) -- no // a / (b * c) -- no // a / (b / c) -- no // a / (b % c) -- no // a % (b * c) -- no // a % (b / c) -- no // a % (b % c) -- no return inop == outop; // == MUL case SUB: case ADD: // a + (b + c) -- yes, unless outop is concatenation and inop is addition, or operands are floats // a + (b - c) -- yes // a - (b + c) -- no // a - (b - c) -- no return outop == BinaryOp.ADD && outer.getTypeMirror().isPrimitive() == inner.getTypeMirror().isPrimitive() && !inner.getTypeMirror().isFloatingPoint(); default: return false; } } enum Necessity { ALWAYS, NEVER, CLARIFYING, BALANCING; static Necessity definitely(boolean b) { return b ? ALWAYS : NEVER; } static Necessity necessaryIf(boolean b) { return b ? ALWAYS : CLARIFYING; } } }
11,436
39.413428
131
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/MethodArgumentCouldBeFinalRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.NodeStream; 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.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.rule.AbstractRule; public class MethodArgumentCouldBeFinalRule extends AbstractJavaRulechainRule { public MethodArgumentCouldBeFinalRule() { super(ASTMethodOrConstructorDeclaration.class); } @Override public Object visit(ASTMethodDeclaration meth, Object data) { if (meth.getBody() == null) { return data; } lookForViolation(meth, data); return data; } @Override public Object visit(ASTConstructorDeclaration constructor, Object data) { lookForViolation(constructor, data); return data; } private void lookForViolation(ASTMethodOrConstructorDeclaration node, Object data) { checkForFinal((RuleContext) data, this, node.getFormalParameters().toStream().map(ASTFormalParameter::getVarId)); } static void checkForFinal(RuleContext ruleContext, AbstractRule rule, NodeStream<ASTVariableDeclaratorId> variables) { outer: for (ASTVariableDeclaratorId var : variables) { if (var.isFinal()) { continue; } boolean used = false; for (ASTNamedReferenceExpr usage : var.getLocalUsages()) { used = true; if (usage.getAccessType() == AccessType.WRITE) { continue outer; } } if (used) { rule.addViolation(ruleContext, var, var.getName()); } } } }
2,291
34.8125
122
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryFullyQualifiedNameRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import java.util.List; import java.util.function.BiPredicate; import java.util.function.Function; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.lang.java.ast.ASTFieldAccess; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTTypeExpression; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.symbols.JAccessibleElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.symbols.table.JSymbolTable; import net.sourceforge.pmd.lang.java.symbols.table.ScopeInfo; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChain; import net.sourceforge.pmd.lang.java.symbols.table.coreimpl.ShadowChainIterator; import net.sourceforge.pmd.lang.java.types.JMethodSig; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.util.AssertionUtil; public class UnnecessaryFullyQualifiedNameRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> REPORT_METHODS = booleanProperty("reportStaticMethods") .desc("Report unnecessary static method qualifiers like in `Collections.emptyList()`, if the method is imported or inherited.") .defaultValue(true) .build(); private static final PropertyDescriptor<Boolean> REPORT_FIELDS = booleanProperty("reportStaticFields") .desc("Report unnecessary static field qualifiers like in `Math.PI`, if the field is imported or inherited.") .defaultValue(true) .build(); public UnnecessaryFullyQualifiedNameRule() { super(ASTClassOrInterfaceType.class); definePropertyDescriptor(REPORT_METHODS); definePropertyDescriptor(REPORT_FIELDS); } @Override public Object visit(final ASTClassOrInterfaceType deepest, Object data) { if (deepest.getQualifier() != null) { // the child will be visited instead return data; } ASTClassOrInterfaceType next = deepest; ScopeInfo bestReason = null; if (next.isFullyQualified()) { bestReason = typeMeansSame(next); } // try to find the longest prefix that can be removed while (bestReason != null && segmentIsIrrelevant(next) && next.getParent() instanceof ASTClassOrInterfaceType) { ASTClassOrInterfaceType nextParent = (ASTClassOrInterfaceType) next.getParent(); ScopeInfo newBestReason = typeMeansSame(nextParent); if (newBestReason == null) { break; } else { bestReason = newBestReason; next = nextParent; } } // maybe a method call/field can still take precedence if (next.getParent() instanceof ASTTypeExpression) { JavaNode opa = next.getParent().getParent(); if (getProperty(REPORT_METHODS) && opa instanceof ASTMethodCall) { ASTMethodCall methodCall = (ASTMethodCall) opa; if (methodCall.getExplicitTypeArguments() == null && methodProbablyMeansSame(methodCall)) { // we don't actually know where the method came from String simpleName = formatMemberName(next, methodCall.getMethodType().getSymbol()); String unnecessary = produceQualifier(deepest, next, true); addViolation(data, next, new Object[] {unnecessary, simpleName, ""}); return null; } } else if (getProperty(REPORT_FIELDS) && opa instanceof ASTFieldAccess) { ASTFieldAccess fieldAccess = (ASTFieldAccess) opa; ScopeInfo reasonForFieldInScope = fieldMeansSame(fieldAccess); if (reasonForFieldInScope != null) { String simpleName = formatMemberName(next, fieldAccess.getReferencedSym()); String reasonToString = unnecessaryReasonWrapper(reasonForFieldInScope); String unnecessary = produceQualifier(deepest, next, true); addViolation(data, next, new Object[] {unnecessary, simpleName, reasonToString}); return null; } } } if (bestReason != null) { String simpleName = next.getSimpleName(); String reasonToString = unnecessaryReasonWrapper(bestReason); String unnecessary = produceQualifier(deepest, next, false); addViolation(data, next, new Object[] {unnecessary, simpleName, reasonToString}); } return null; } private String produceQualifier(ASTClassOrInterfaceType startIncluded, ASTClassOrInterfaceType stopExcluded, boolean includeLast) { StringBuilder sb = new StringBuilder(); if (startIncluded.isFullyQualified()) { sb.append(startIncluded.getTypeMirror().getSymbol().getPackageName()); } ASTClassOrInterfaceType nextSimpleName = startIncluded; while (nextSimpleName != stopExcluded) { // NOPMD we want identity comparison sb.append('.').append(nextSimpleName.getSimpleName()); nextSimpleName = (ASTClassOrInterfaceType) nextSimpleName.getParent(); } if (includeLast) { if (sb.length() == 0) { return nextSimpleName.getSimpleName(); } sb.append('.').append(nextSimpleName.getSimpleName()); } return sb.toString(); } private boolean segmentIsIrrelevant(ASTClassOrInterfaceType type) { return type.getTypeArguments() == null && type.getDeclaredAnnotations().isEmpty(); } /** * Checks that the type name can be referred to by simple name in the * given scope, which means, that the qualification can be dropped. * If the symbol table for types yields the same symbol when referred * to by simple name, then this is true. * * @return The reason why the type is in scope. Null if it's not in scope. */ private static @Nullable ScopeInfo typeMeansSame(@NonNull ASTClassOrInterfaceType typeNode) { JTypeDeclSymbol sym = typeNode.getTypeMirror().getSymbol(); if (sym == null || sym.isUnresolved()) { return null; } JSymbolTable symTable = typeNode.getSymbolTable(); if (symTable.variables().resolveFirst(sym.getSimpleName()) != null) { return null; //name is obscured: https://docs.oracle.com/javase/specs/jls/se15/html/jls-6.html#jls-6.4.2 } return fieldOrTypeMeansSame( sym, typeNode.getSymbolTable(), JSymbolTable::types, (s, t) -> s.equals(t.getSymbol()) ); } private static boolean methodProbablyMeansSame(ASTMethodCall call) { // todo at least filter by potential applicability // (ideally, do a complete inference run) // this may have false negatives List<JMethodSig> accessibleMethods = call.getSymbolTable().methods().resolve(call.getMethodName()); if (accessibleMethods.isEmpty() || call.getOverloadSelectionInfo().isFailed()) { return false; } JClassSymbol methodOwner = call.getMethodType().getSymbol().getEnclosingClass(); for (JMethodSig m : accessibleMethods) { if (!m.getSymbol().getEnclosingClass().equals(methodOwner)) { return false; } } return true; } private static ScopeInfo fieldMeansSame(ASTFieldAccess field) { JFieldSymbol sym = field.getReferencedSym(); if (sym == null || sym.isUnresolved()) { return null; } return fieldOrTypeMeansSame( sym, field.getSymbolTable(), JSymbolTable::variables, (s, t) -> s.equals(t.getSymbol()) ); } private static <S extends JElementSymbol, T> ScopeInfo fieldOrTypeMeansSame(@NonNull S originalSym, JSymbolTable symTable, Function<JSymbolTable, ShadowChain<T, ScopeInfo>> shadowChainGetter, BiPredicate<S, T> areEqual) { ShadowChainIterator<T, ScopeInfo> iter = shadowChainGetter.apply(symTable).iterateResults(originalSym.getSimpleName()); if (iter.hasNext()) { iter.next(); List<T> results = iter.getResults(); if (results.size() == 1) { // otherwise ambiguous if (areEqual.test(originalSym, results.get(0))) { return iter.getScopeTag(); } } // not unnecessary return null; } // unknown symbol return null; } private static String formatMemberName(ASTClassOrInterfaceType qualifier, JAccessibleElementSymbol call) { JClassSymbol methodOwner = call.getEnclosingClass(); if (methodOwner != null && !methodOwner.equals(qualifier.getTypeMirror().getSymbol())) { return methodOwner.getSimpleName() + "::" + call.getSimpleName(); } return call.getSimpleName(); } private static String unnecessaryReasonWrapper(ScopeInfo scopeInfo) { return " because it is " + unnecessaryReason(scopeInfo); } private static String unnecessaryReason(ScopeInfo scopeInfo) { switch (scopeInfo) { case JAVA_LANG: return "declared in java.lang"; case SAME_PACKAGE: case SAME_FILE: return "declared in the same package"; case SINGLE_IMPORT: case IMPORT_ON_DEMAND: return "imported in this file"; case INHERITED: return "inherited by an enclosing type"; case ENCLOSING_TYPE_MEMBER: case ENCLOSING_TYPE: return "declared in an enclosing type"; default: throw AssertionUtil.shouldNotReachHere("unknown constant" + scopeInfo); } } }
10,873
41.476563
148
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/AtLeastOneConstructorRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.Arrays; import java.util.Collection; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.rule.AbstractIgnoredAnnotationRule; import net.sourceforge.pmd.lang.java.rule.design.UseUtilityClassRule; /** * This rule detects non-static classes with no constructors; * requiring even the default constructor to be explicit. * It ignores classes with solely static methods, * use {@link UseUtilityClassRule} to flag those. */ public class AtLeastOneConstructorRule extends AbstractIgnoredAnnotationRule { public AtLeastOneConstructorRule() { addRuleChainVisit(ASTClassOrInterfaceDeclaration.class); } @Override protected Collection<String> defaultSuppressionAnnotations() { return Arrays.asList("lombok.Data", "lombok.Value", "lombok.Builder", "lombok.NoArgsConstructor", "lombok.RequiredArgsConstructor", "lombok.AllArgsConstructor"); } @Override public Object visit(final ASTClassOrInterfaceDeclaration node, final Object data) { // Ignore interfaces / static classes / classes that have a constructor / classes ignored through annotations if (!node.isRegularClass() || node.isStatic() || node.getDeclarations().any(it -> it instanceof ASTConstructorDeclaration) || hasIgnoredAnnotation(node)) { return data; } NodeStream<AccessNode> members = node.getDeclarations() .filterIs(AccessNode.class) .filterNot(it -> it instanceof ASTAnyTypeDeclaration); if (members.isEmpty() || members.any(it -> !it.isStatic())) { // Do we have any non-static members? addViolation(data, node); } return data; } }
2,299
36.704918
117
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/codestyle/UnnecessaryConstructorRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.codestyle; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; 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.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.rule.AbstractIgnoredAnnotationRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; /** * This rule detects when a constructor is not necessary; * i.e., when there is only one constructor, it’s public, has an empty body, * and takes no arguments. */ public class UnnecessaryConstructorRule extends AbstractIgnoredAnnotationRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTEnumDeclaration.class, ASTClassOrInterfaceDeclaration.class); } @Override protected Collection<String> defaultSuppressionAnnotations() { return Arrays.asList("javax.inject.Inject", "com.google.inject.Inject", "org.springframework.beans.factory.annotation.Autowired"); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isRegularClass()) { checkClassOrEnum(node, data); } return data; } @Override public Object visit(ASTEnumDeclaration node, Object data) { checkClassOrEnum(node, data); return data; } private void checkClassOrEnum(ASTAnyTypeDeclaration node, Object data) { List<ASTConstructorDeclaration> ctors = node.getDeclarations(ASTConstructorDeclaration.class).take(2).toList(); if (ctors.size() == 1 && isExplicitDefaultConstructor(node, ctors.get(0))) { addViolation(data, ctors.get(0)); } } private boolean isExplicitDefaultConstructor(ASTAnyTypeDeclaration declarator, ASTConstructorDeclaration ctor) { return ctor.getArity() == 0 && !hasIgnoredAnnotation(ctor) && hasDefaultCtorVisibility(declarator, ctor) && isEmptyBlock(ctor.getBody()) && ctor.getThrowsList() == null; } private boolean isEmptyBlock(ASTBlock body) { if (body.size() == 0) { return true; } else if (body.size() == 1) { ASTStatement stmt = body.get(0); if (stmt instanceof ASTExplicitConstructorInvocation) { ASTExplicitConstructorInvocation superCall = (ASTExplicitConstructorInvocation) stmt; return superCall.isSuper() && superCall.getArgumentCount() == 0; } } return false; } private boolean hasDefaultCtorVisibility(ASTAnyTypeDeclaration node, ASTConstructorDeclaration cons) { if (node instanceof ASTClassOrInterfaceDeclaration) { return node.getVisibility() == cons.getVisibility(); } else if (node instanceof ASTEnumDeclaration) { return cons.getVisibility() == Visibility.V_PRIVATE; } return false; } }
3,568
36.177083
119
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveMethodLengthRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.rule.internal.AbstractJavaCounterCheckRule; /** * This rule detects when a method exceeds a certain threshold. i.e. if a method * has more than x lines of code. * * @deprecated Use {@link NcssCountRule} instead. */ @Deprecated public class ExcessiveMethodLengthRule extends AbstractJavaCounterCheckRule.AbstractLineLengthCheckRule<ASTMethodOrConstructorDeclaration> { public ExcessiveMethodLengthRule() { super(ASTMethodOrConstructorDeclaration.class); } @Override protected int defaultReportLevel() { return 100; } }
815
28.142857
140
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/InvalidJavaBeanRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTPackageDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTType; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.Annotatable; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.JArrayType; import net.sourceforge.pmd.lang.java.types.JPrimitiveType; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.StringUtil; public class InvalidJavaBeanRule extends AbstractJavaRulechainRule { private static final String LOMBOK_PACKAGE = "lombok"; private static final String LOMBOK_DATA = "Data"; private static final String LOMBOK_GETTER = "Getter"; private static final String LOMBOK_SETTER = "Setter"; private static final PropertyDescriptor<Boolean> ENSURE_SERIALIZATION = PropertyFactory.booleanProperty("ensureSerialization") .desc("Require that beans implement java.io.Serializable.") .defaultValue(false) .build(); private static final PropertyDescriptor<List<String>> PACKAGES_DESCRIPTOR = stringListProperty("packages") .desc("Consider classes in only these package to be beans. Set to an empty value to check all classes.") .defaultValues("org.example.beans") .delim(',') .build(); private Map<String, PropertyInfo> properties; public InvalidJavaBeanRule() { super(ASTClassOrInterfaceDeclaration.class); definePropertyDescriptor(ENSURE_SERIALIZATION); definePropertyDescriptor(PACKAGES_DESCRIPTOR); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { String packageName = ""; ASTPackageDeclaration packageDeclaration = node.getRoot().getPackageDeclaration(); if (packageDeclaration != null) { packageName = packageDeclaration.getName(); } List<String> packages = getProperty(PACKAGES_DESCRIPTOR); if (!packages.isEmpty() && !packages.contains(packageName)) { // skip analysis outside the configured packages return null; } String beanName = node.getSimpleName(); if (getProperty(ENSURE_SERIALIZATION) && !TypeTestUtil.isA(Serializable.class, node)) { asCtx(data).addViolationWithMessage(node, "The bean ''{0}'' does not implement java.io.Serializable.", beanName); } if (!hasNoArgConstructor(node)) { asCtx(data).addViolationWithMessage(node, "The bean ''{0}'' is missing a no-arg constructor.", beanName); } if (hasLombokDataAnnotation(node)) { // skip further analysis return null; } properties = new HashMap<>(); collectFields(node); collectMethods(node); for (PropertyInfo propertyInfo : properties.values()) { if (!hasLombokGetterAnnotation(node) && !hasLombokSetterAnnotation(node) && propertyInfo.hasMissingGetter() && propertyInfo.hasMissingSetter()) { asCtx(data).addViolationWithMessage(propertyInfo.getDeclaratorId(), "The bean ''{0}'' is missing a getter and a setter for property ''{1}''.", beanName, propertyInfo.getName()); } else if (!hasLombokGetterAnnotation(node) && propertyInfo.hasMissingGetter()) { asCtx(data).addViolationWithMessage(propertyInfo.getDeclaratorId(), "The bean ''{0}'' is missing a getter for property ''{1}''.", beanName, propertyInfo.getName()); } else if (!hasLombokSetterAnnotation(node) && propertyInfo.hasMissingSetter()) { asCtx(data).addViolationWithMessage(propertyInfo.getDeclaratorId(), "The bean ''{0}'' is missing a setter for property ''{1}''.", beanName, propertyInfo.getName()); } if (propertyInfo.hasWrongGetterType()) { asCtx(data).addViolationWithMessage(propertyInfo.getGetter(), "The bean ''{0}'' should return a ''{1}'' in getter of property ''{2}''.", beanName, propertyInfo.getTypeName(), propertyInfo.getName()); } if (propertyInfo.hasWrongBooleanGetterName()) { asCtx(data).addViolationWithMessage(propertyInfo.getGetter(), "The bean ''{0}'' should use the method name ''is{1}'' for the getter of property ''{2}''.", beanName, propertyInfo.getName(), propertyInfo.getName()); } if (propertyInfo.hasWrongTypeGetterAndSetter()) { asCtx(data).addViolationWithMessage(propertyInfo.getGetter(), "The bean ''{0}'' has a property ''{1}'' with getter and setter that don''t have the same type.", beanName, propertyInfo.getName()); } if (propertyInfo.hasWrongIndexedGetterType()) { asCtx(data).addViolationWithMessage(propertyInfo.indexedGetter, "The bean ''{0}'' has a property ''{1}'' with an indexed getter using the wrong type.", beanName, propertyInfo.getName()); } if (propertyInfo.hasWrongIndexedSetterType()) { asCtx(data).addViolationWithMessage(propertyInfo.indexedSetter, "The bean ''{0}'' has a property ''{1}'' with an indexed setter using the wrong type.", beanName, propertyInfo.getName()); } } return null; } private void collectFields(ASTClassOrInterfaceDeclaration node) { for (ASTFieldDeclaration fieldDeclaration : node.getDeclarations(ASTFieldDeclaration.class).toList()) { for (ASTVariableDeclaratorId variableDeclaratorId : fieldDeclaration) { String propertyName = StringUtils.capitalize(variableDeclaratorId.getName()); if (!fieldDeclaration.hasModifiers(JModifier.STATIC) && !fieldDeclaration.hasModifiers(JModifier.TRANSIENT)) { PropertyInfo field = getOrCreatePropertyInfo(propertyName); field.setDeclaratorId(variableDeclaratorId); field.setReadonly(fieldDeclaration.hasModifiers(JModifier.FINAL)); } } } } private PropertyInfo getOrCreatePropertyInfo(String propertyName) { PropertyInfo propertyInfo = properties.get(propertyName); if (propertyInfo == null) { propertyInfo = new PropertyInfo(propertyName); properties.put(propertyName, propertyInfo); } return propertyInfo; } private void collectMethods(ASTClassOrInterfaceDeclaration node) { for (ASTMethodDeclaration methodDeclaration : node.getDeclarations(ASTMethodDeclaration.class).toList()) { String methodName = methodDeclaration.getName(); int parameterCount = methodDeclaration.getArity(); String propertyName = StringUtil.withoutPrefixes(methodName, "get", "set", "is"); if (methodName.startsWith("get") || methodName.startsWith("is")) { if (parameterCount == 0) { PropertyInfo propertyInfo = getOrCreatePropertyInfo(propertyName); propertyInfo.setGetter(methodDeclaration); } else if (parameterCount == 1 && getFirstParameterType(methodDeclaration).isPrimitive(JPrimitiveType.PrimitiveTypeKind.INT)) { PropertyInfo propertyInfo = getOrCreatePropertyInfo(propertyName); propertyInfo.setIndexedGetter(methodDeclaration); } } else if (methodName.startsWith("set")) { if (parameterCount == 1) { PropertyInfo propertyInfo = getOrCreatePropertyInfo(propertyName); propertyInfo.setSetter(methodDeclaration); } else if (parameterCount == 2 && getFirstParameterType(methodDeclaration).isPrimitive(JPrimitiveType.PrimitiveTypeKind.INT)) { PropertyInfo propertyInfo = getOrCreatePropertyInfo(propertyName); propertyInfo.setIndexedSetter(methodDeclaration); } } } } private static JTypeMirror getFirstParameterType(ASTMethodDeclaration declaration) { return getParameterType(declaration, 0); } private static JTypeMirror getParameterType(ASTMethodDeclaration declaration, int i) { if (declaration.getArity() >= i + 1) { ASTFormalParameter firstParameter = declaration.getFormalParameters().children(ASTFormalParameter.class).get(i); return firstParameter.getTypeMirror(); } return null; } private static JTypeMirror getResultType(ASTMethodDeclaration declaration) { ASTType resultType = declaration.getResultTypeNode(); return resultType.getTypeMirror(); } private boolean hasNoArgConstructor(ASTClassOrInterfaceDeclaration node) { int constructorCount = 0; for (ASTConstructorDeclaration ctor : node.getDeclarations(ASTConstructorDeclaration.class)) { if (ctor.getArity() == 0) { return true; } constructorCount++; } // default constructor is ok return constructorCount == 0; } private static boolean hasLombokImport(Annotatable node) { return node.getRoot().descendants(ASTImportDeclaration.class) .filter(ASTImportDeclaration::isImportOnDemand) .filterNot(ASTImportDeclaration::isStatic) .any(i -> LOMBOK_PACKAGE.equals(i.getImportedName())); } private static boolean hasLombokDataAnnotation(Annotatable node) { return node.isAnnotationPresent(LOMBOK_PACKAGE + "." + LOMBOK_DATA) || hasLombokImport(node) && node.isAnnotationPresent(LOMBOK_DATA); } private static boolean hasLombokGetterAnnotation(Annotatable node) { return node.isAnnotationPresent(LOMBOK_PACKAGE + "." + LOMBOK_GETTER) || hasLombokImport(node) && node.isAnnotationPresent(LOMBOK_GETTER); } private static boolean hasLombokSetterAnnotation(Annotatable node) { return node.isAnnotationPresent(LOMBOK_PACKAGE + "." + LOMBOK_SETTER) || hasLombokImport(node) && node.isAnnotationPresent(LOMBOK_SETTER); } private static class PropertyInfo { private final String name; private ASTVariableDeclaratorId declaratorId; private boolean readonly; private ASTMethodDeclaration getter; private ASTMethodDeclaration indexedGetter; private ASTMethodDeclaration setter; private ASTMethodDeclaration indexedSetter; PropertyInfo(String name) { this.name = name; } public String getName() { return name; } public ASTVariableDeclaratorId getDeclaratorId() { return declaratorId; } public void setDeclaratorId(ASTVariableDeclaratorId declaratorId) { this.declaratorId = declaratorId; } public boolean isReadonly() { return readonly; } public void setReadonly(boolean readonly) { this.readonly = readonly; } public ASTMethodDeclaration getGetter() { return getter; } public void setGetter(ASTMethodDeclaration getter) { this.getter = getter; } public ASTMethodDeclaration getIndexedGetter() { return indexedGetter; } public void setIndexedGetter(ASTMethodDeclaration indexedGetter) { this.indexedGetter = indexedGetter; } public ASTMethodDeclaration getSetter() { return setter; } public void setSetter(ASTMethodDeclaration setter) { this.setter = setter; } public ASTMethodDeclaration getIndexedSetter() { return indexedSetter; } public void setIndexedSetter(ASTMethodDeclaration indexedSetter) { this.indexedSetter = indexedSetter; } private boolean hasMissingGetter() { return declaratorId != null && getter == null && !hasFieldLombokGetter(); } private boolean hasMissingSetter() { return declaratorId != null && !readonly && setter == null && !hasFieldLombokSetter(); } private String getTypeName() { JTypeMirror type = null; if (declaratorId != null) { type = declaratorId.getTypeMirror(); } else if (getter != null) { type = getResultType(getter); } else if (setter != null) { type = getFirstParameterType(setter); } if (type != null) { return type.toString(); } return "<unknown type>"; } private boolean hasWrongGetterType() { return declaratorId != null && getter != null && !getter.getResultTypeNode().isVoid() && !declaratorId.getTypeMirror().equals(getResultType(getter)); } private boolean hasWrongBooleanGetterName() { if (getter != null && (TypeTestUtil.isA(Boolean.class, declaratorId) || TypeTestUtil.isA(Boolean.TYPE, declaratorId))) { return !getter.getName().startsWith("is"); } return false; } private boolean hasWrongTypeGetterAndSetter() { if (declaratorId != null || getter == null || setter == null) { return false; } JTypeMirror parameterType = getFirstParameterType(setter); return getter.getResultTypeNode().isVoid() || !getResultType(getter).equals(parameterType); } private boolean hasWrongIndexedGetterType() { if (getter == null || indexedGetter == null) { return false; } JTypeMirror propertyType = getResultType(getter); if (propertyType != null && propertyType.isArray()) { propertyType = ((JArrayType) propertyType).getComponentType(); } JTypeMirror getterType = getResultType(indexedGetter); return !propertyType.equals(getterType); } private boolean hasWrongIndexedSetterType() { if (setter == null || indexedSetter == null) { return false; } JTypeMirror propertyType = getFirstParameterType(setter); if (propertyType != null && propertyType.isArray()) { propertyType = ((JArrayType) propertyType).getComponentType(); } JTypeMirror setterType = getParameterType(indexedSetter, 1); return !propertyType.equals(setterType); } private boolean hasFieldLombokGetter() { ASTFieldDeclaration fieldDeclaration = declaratorId != null ? declaratorId.ancestors(ASTFieldDeclaration.class).first() : null; return fieldDeclaration != null && hasLombokGetterAnnotation(fieldDeclaration); } private boolean hasFieldLombokSetter() { ASTFieldDeclaration fieldDeclaration = declaratorId != null ? declaratorId.ancestors(ASTFieldDeclaration.class).first() : null; return fieldDeclaration != null && hasLombokSetterAnnotation(fieldDeclaration); } } }
16,775
42.348837
143
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/CognitiveComplexityRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.COGNITIVE_COMPLEXITY; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Cognitive complexity rule. * * @author Denis Borovikov * @see JavaMetrics#COGNITIVE_COMPLEXITY */ public class CognitiveComplexityRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Integer> REPORT_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("reportLevel").desc("Cognitive Complexity reporting threshold") .require(positive()).defaultValue(15).build(); public CognitiveComplexityRule() { super(ASTMethodOrConstructorDeclaration.class); definePropertyDescriptor(REPORT_LEVEL_DESCRIPTOR); } private int getReportLevel() { return getProperty(REPORT_LEVEL_DESCRIPTOR); } @Override public final Object visit(ASTMethodDeclaration node, Object data) { return visitMethod(node, data); } @Override public final Object visit(ASTConstructorDeclaration node, Object data) { return visitMethod(node, data); } private Object visitMethod(ASTMethodOrConstructorDeclaration node, Object data) { if (!COGNITIVE_COMPLEXITY.supports(node)) { return data; } int cognitive = MetricsUtil.computeMetric(COGNITIVE_COMPLEXITY, node); final int reportLevel = getReportLevel(); if (cognitive >= reportLevel) { addViolation(data, node, new String[] { node instanceof ASTMethodDeclaration ? "method" : "constructor", PrettyPrintingUtil.displaySignature(node), String.valueOf(cognitive), String.valueOf(reportLevel) }); } return data; } }
2,604
37.308824
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/SimplifyConditionalRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.CONDITIONAL_AND; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.CONDITIONAL_OR; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.INSTANCEOF; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.NE; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.getOtherOperandIfInInfixExpr; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isBooleanNegation; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isInfixExprWithOperator; import static net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil.isNullCheck; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.StablePathMatcher; public class SimplifyConditionalRule extends AbstractJavaRulechainRule { public SimplifyConditionalRule() { super(ASTInfixExpression.class); } @Override public Object visit(ASTInfixExpression node, Object data) { if (node.getOperator() == INSTANCEOF) { StablePathMatcher instanceOfSubject = StablePathMatcher.matching(node.getLeftOperand()); if (instanceOfSubject == null) { return null; } ASTExpression nullCheckExpr; boolean negated; if (isInfixExprWithOperator(node.getParent(), CONDITIONAL_AND)) { // a != null && a instanceof T negated = false; nullCheckExpr = getOtherOperandIfInInfixExpr(node); } else if (isBooleanNegation(node.getParent()) && isInfixExprWithOperator(node.getParent().getParent(), CONDITIONAL_OR)) { // a == null || a instanceof T negated = true; nullCheckExpr = getOtherOperandIfInInfixExpr(node.getParent()); } else { return null; } if (!isNullCheck(nullCheckExpr, instanceOfSubject)) { return null; } if (negated != isInfixExprWithOperator(nullCheckExpr, NE)) { addViolation(data, nullCheckExpr); } } return null; } }
2,481
37.78125
100
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/SimplifyBooleanReturnsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.CONDITIONAL_AND; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.CONDITIONAL_OR; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.EQ; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.GE; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.GT; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.LE; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.LT; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.NE; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.opsWithGreaterPrecedence; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.areComplements; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isBooleanLiteral; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isInfixExprWithOperator; import java.util.EnumSet; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTCastExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.BinaryOp; 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.types.JPrimitiveType.PrimitiveTypeKind; public class SimplifyBooleanReturnsRule extends AbstractJavaRulechainRule { private static final Set<BinaryOp> NEGATABLE_OPS = EnumSet.of(EQ, NE, GT, LT, GE, LE); public SimplifyBooleanReturnsRule() { super(ASTReturnStatement.class); } @Override public Object visit(ASTReturnStatement node, Object data) { ASTExpression expr = node.getExpr(); if (expr == null || !expr.getTypeMirror().isPrimitive(PrimitiveTypeKind.BOOLEAN) || !isThenBranchOfSomeIf(node)) { return null; } checkIf(node.ancestors(ASTIfStatement.class).firstOrThrow(), asCtx(data), expr); return null; } // Only explore the then branch. If we explore the else, then we'll report twice. // In the case if .. else, both branches need to be symmetric anyway. private boolean isThenBranchOfSomeIf(ASTReturnStatement node) { if (node.getParent() instanceof ASTIfStatement) { return node.getIndexInParent() == 1; } return node.getParent() instanceof ASTBlock && ((ASTBlock) node.getParent()).size() == 1 && node.getParent().getParent() instanceof ASTIfStatement && node.getParent().getIndexInParent() == 1; } private void checkIf(ASTIfStatement node, RuleContext data, ASTExpression thenExpr) { // that's the case: if..then..return; return; ASTExpression elseExpr = getElseExpr(node); if (elseExpr == null) { return; } if (isBooleanLiteral(thenExpr) || isBooleanLiteral(elseExpr)) { String fix = needsToBeReportedWhenOneBranchIsBoolean(node.getCondition(), thenExpr, elseExpr); if (fix != null) { data.addViolation(node, fix); } } else if (areComplements(thenExpr, elseExpr)) { // if (foo) return !a; // else return a; data.addViolation(node, "return {condition};"); } } /** * Whether refactoring an if-then-else to use shortcut operators * would require adding parentheses to respect operator precedence. * <pre>{@code * if (cond) true else expr -> cond || expr * if (cond) false else expr -> !cond && expr * if (cond) expr else true -> !cond || expr * if (cond) expr else false -> cond && expr * }</pre> * Note that both the `expr` and the `condition` may require parentheses * (if the cond has to be negated). */ private String needsToBeReportedWhenOneBranchIsBoolean(ASTExpression condition, ASTExpression thenExpr, ASTExpression elseExpr) { // at least one of these is true boolean thenFalse = isBooleanLiteral(thenExpr, false); boolean thenTrue = isBooleanLiteral(thenExpr, true); boolean elseTrue = isBooleanLiteral(elseExpr, true); boolean elseFalse = isBooleanLiteral(elseExpr, false); assert thenFalse || elseFalse || thenTrue || elseTrue : "expected boolean branch"; if (isBooleanLiteral(thenExpr) && isBooleanLiteral(elseExpr)) { // both are boolean if (thenTrue && elseFalse) { return "return {condition};"; } else if (thenFalse && elseTrue) { return "return !{condition};"; } else if (thenTrue) { // both are true return "return true;"; } else { // both are false return "return false;"; } } boolean conditionNegated = thenFalse || elseTrue; if (conditionNegated && needsNewParensWhenNegating(condition)) { return null; } BinaryOp op = thenFalse || elseFalse ? CONDITIONAL_AND : CONDITIONAL_OR; // the branch that is not a literal, if both are literals, prefers elseExpr ASTExpression branch = thenFalse || thenTrue ? elseExpr : thenExpr; if (doesNotNeedNewParensUnderInfix(condition, op) && doesNotNeedNewParensUnderInfix(branch, op)) { if (thenTrue) { return "return {condition} || {elseBranch};"; } else if (thenFalse) { return "return !{condition} || {elseBranch};"; } else if (elseTrue) { return "return !{condition} && {thenBranch};"; } else { return "return {condition} && {thenBranch};"; } } return null; } private static boolean needsNewParensWhenNegating(ASTExpression e) { if (e instanceof ASTPrimaryExpression || e instanceof ASTCastExpression // parenthesized expressions are primary || e.isParenthesized() // == -> != || isInfixExprWithOperator(e, NEGATABLE_OPS) // !! -> || JavaAstUtils.isBooleanNegation(e)) { return false; } else if (isInfixExprWithOperator(e, CONDITIONAL_OR) || isInfixExprWithOperator(e, CONDITIONAL_AND)) { // negating these ops can be replaced with complement op // and the negation pushed down branches using De Morgan's laws ASTInfixExpression infix = (ASTInfixExpression) e; return needsNewParensWhenNegating(infix.getLeftOperand()) || needsNewParensWhenNegating(infix.getRightOperand()); } return true; } private static boolean doesNotNeedNewParensUnderInfix(ASTExpression e, BinaryOp op) { // those nodes have greater precedence than infix return e instanceof ASTPrimaryExpression || e instanceof ASTCastExpression || e instanceof ASTUnaryExpression || e.isParenthesized() || isInfixExprWithOperator(e, opsWithGreaterPrecedence(op)); } private @Nullable ASTExpression getReturnExpr(JavaNode node) { if (node instanceof ASTReturnStatement) { return ((ASTReturnStatement) node).getExpr(); } else if (node instanceof ASTBlock && ((ASTBlock) node).size() == 1) { return getReturnExpr(((ASTBlock) node).get(0)); } return null; } private @Nullable ASTExpression getElseExpr(ASTIfStatement node) { return node.hasElse() ? getReturnExpr(node.getElseBranch()) : getReturnExpr(node.getNextSibling()); // may be followed immediately by return } }
8,509
41.979798
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/UseUtilityClassRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.Set; import net.sourceforge.pmd.lang.java.ast.ASTAnnotation; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; 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.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMemberValuePair; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; 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.types.TypeTestUtil; public class UseUtilityClassRule extends AbstractJavaRulechainRule { private static final Set<String> IGNORED_CLASS_ANNOT = setOf( "lombok.experimental.UtilityClass", "org.junit.runner.RunWith" // for suites and such ); public UseUtilityClassRule() { super(ASTClassOrInterfaceDeclaration.class); } @Override public Object visit(ASTClassOrInterfaceDeclaration klass, Object data) { if (JavaAstUtils.hasAnyAnnotation(klass, IGNORED_CLASS_ANNOT) || TypeTestUtil.isA("junit.framework.TestSuite", klass) // suite method is ok || klass.isInterface() || klass.isAbstract() || klass.getSuperClassTypeNode() != null || klass.getSuperInterfaceTypeNodes().nonEmpty() ) { return data; } boolean hasAnyMethods = false; boolean hasNonPrivateCtor = false; boolean hasAnyCtor = false; for (ASTBodyDeclaration declaration : klass.getDeclarations()) { if (declaration instanceof ASTFieldDeclaration && !((ASTFieldDeclaration) declaration).isStatic()) { return null; } if (declaration instanceof ASTConstructorDeclaration) { hasAnyCtor = true; if (((ASTConstructorDeclaration) declaration).getVisibility() != Visibility.V_PRIVATE) { hasNonPrivateCtor = true; } } if (declaration instanceof ASTMethodDeclaration) { if (((ASTMethodDeclaration) declaration).getVisibility() != Visibility.V_PRIVATE) { hasAnyMethods = true; } if (!((ASTMethodDeclaration) declaration).isStatic()) { return null; } } } // account for default ctor hasNonPrivateCtor |= !hasAnyCtor && klass.getVisibility() != Visibility.V_PRIVATE && !hasLombokPrivateCtor(klass); String message; if (hasAnyMethods && hasNonPrivateCtor) { message = "This utility class has a non-private constructor"; addViolationWithMessage(data, klass, message); } return null; } private boolean hasLombokPrivateCtor(ASTClassOrInterfaceDeclaration parent) { // check if there's a lombok no arg private constructor, if so skip the rest of the rules return parent.getDeclaredAnnotations() .filter(t -> TypeTestUtil.isA("lombok.NoArgsConstructor", t)) .flatMap(ASTAnnotation::getMembers) // to set the access level of a constructor in lombok, you set the access property on the annotation .filterMatching(ASTMemberValuePair::getName, "access") // This is from the AccessLevel enum in Lombok // if the constructor is found and the accesslevel is private no need to check anything else .any(it -> isAccessToVarWithName(it.getValue(), "PRIVATE")); } private static boolean isAccessToVarWithName(JavaNode node, String name) { return node instanceof ASTNamedReferenceExpr && ((ASTNamedReferenceExpr) node).getName().equals(name); } }
4,384
40.367925
121
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/SingularFieldRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.ast.JModifier.FINAL; import static net.sourceforge.pmd.lang.java.ast.JModifier.STATIC; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; 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.lang.java.rule.internal.DataflowPass.ReachingDefinitionSet; import net.sourceforge.pmd.lang.java.rule.internal.JavaPropertyUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * A singular field is a field that may be converted to a local variable. * This means, that in every method the field is used, there is no path * that uses the value that the field has before the method is called. * In other words, the field is overwritten before any read. * * @author Eric Olander * @author Wouter Zelle * @author Clément Fournier * @since Created on April 17, 2005, 9:49 PM */ public class SingularFieldRule extends AbstractJavaRulechainRule { private static final Set<String> INVALIDATING_CLASS_ANNOT = setOf( "lombok.Builder", "lombok.EqualsAndHashCode", "lombok.Getter", "lombok.Setter", "lombok.Data", "lombok.Value" ); private static final PropertyDescriptor<List<String>> IGNORED_FIELD_ANNOTATIONS = JavaPropertyUtil.ignoredAnnotationsDescriptor( "lombok.Setter", "lombok.Getter", "java.lang.Deprecated", "lombok.experimental.Delegate", "javafx.fxml.FXML" ); public SingularFieldRule() { super(ASTAnyTypeDeclaration.class); definePropertyDescriptor(IGNORED_FIELD_ANNOTATIONS); } @Override public Object visitJavaNode(JavaNode node, Object data) { ASTAnyTypeDeclaration enclosingType = (ASTAnyTypeDeclaration) node; if (JavaAstUtils.hasAnyAnnotation(enclosingType, INVALIDATING_CLASS_ANNOT)) { return null; } DataflowResult dataflow = null; for (ASTFieldDeclaration fieldDecl : enclosingType.getDeclarations(ASTFieldDeclaration.class)) { if (!mayBeSingular(fieldDecl) || JavaAstUtils.hasAnyAnnotation(fieldDecl, getProperty(IGNORED_FIELD_ANNOTATIONS))) { continue; } for (ASTVariableDeclaratorId varId : fieldDecl.getVarIds()) { if (dataflow == null) { //compute lazily dataflow = DataflowPass.getDataflowResult(node.getRoot()); } if (isSingularField(enclosingType, varId, dataflow)) { addViolation(data, varId, varId.getName()); } } } return null; } public static boolean mayBeSingular(AccessNode varId) { return varId.getEffectiveVisibility().isAtMost(Visibility.V_PRIVATE) && !varId.getModifiers().hasAny(STATIC, FINAL); } private boolean isSingularField(ASTAnyTypeDeclaration fieldOwner, ASTVariableDeclaratorId varId, DataflowResult dataflow) { if (JavaAstUtils.isNeverUsed(varId)) { return false; // don't report unused field } //Check usages for validity & group them by scope //They're valid if they don't escape the scope of their method, eg by being in a nested class or lambda Map<ASTBodyDeclaration, List<ASTNamedReferenceExpr>> usagesByScope = new HashMap<>(); for (ASTNamedReferenceExpr usage : varId.getLocalUsages()) { if (usage.getEnclosingType() != fieldOwner || !JavaAstUtils.isThisFieldAccess(usage)) { return false; // give up } ASTBodyDeclaration enclosing = getEnclosingBodyDecl(fieldOwner, usage); if (hasEnclosingLambda(enclosing, usage)) { return false; } usagesByScope.computeIfAbsent(enclosing, k -> new ArrayList<>()).add(usage); } // the field is singular if it is used as a local var in every method. for (ASTBodyDeclaration method : usagesByScope.keySet()) { if (method != null && !usagesDontObserveValueBeforeMethodCall(usagesByScope.get(method), dataflow)) { return false; } } return true; } private @Nullable ASTBodyDeclaration getEnclosingBodyDecl(JavaNode stop, ASTNamedReferenceExpr usage) { return usage.ancestors() .takeWhile(it -> it != stop) .first(ASTBodyDeclaration.class); } private boolean hasEnclosingLambda(JavaNode stop, ASTNamedReferenceExpr usage) { return usage.ancestors() .takeWhile(it -> it != stop) .any(it -> it instanceof ASTLambdaExpression); } private boolean usagesDontObserveValueBeforeMethodCall(List<ASTNamedReferenceExpr> usages, DataflowResult dataflow) { for (ASTNamedReferenceExpr usage : usages) { ReachingDefinitionSet reaching = dataflow.getReachingDefinitions(usage); if (reaching.containsInitialFieldValue()) { return false; } } return true; } }
6,245
39.558442
127
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/SignatureDeclareThrowsExceptionRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTThrowsList; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.rule.internal.TestFrameworksUtil; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * A method/constructor shouldn't explicitly throw java.lang.Exception, since it * is unclear which exceptions that can be thrown from the methods. It might be * difficult to document and understand such vague interfaces. Use either a class * derived from RuntimeException or a checked exception. * * <p>This rule uses PMD's type resolution facilities, and can detect * if the class implements or extends TestCase class * * @author <a href="mailto:trondandersen@c2i.net">Trond Andersen</a> * @version 1.0 * @since 1.2 */ public class SignatureDeclareThrowsExceptionRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Boolean> IGNORE_JUNIT_COMPLETELY_DESCRIPTOR = booleanProperty("IgnoreJUnitCompletely").defaultValue(false) .desc("Allow all methods in a JUnit3 TestCase to throw Exceptions").build(); public SignatureDeclareThrowsExceptionRule() { super(ASTThrowsList.class); definePropertyDescriptor(IGNORE_JUNIT_COMPLETELY_DESCRIPTOR); } @Override public Object visit(ASTThrowsList throwsList, Object o) { if (!isIgnored(throwsList.getOwner()) && throwsList.toStream().any(it -> TypeTestUtil.isExactlyA(Exception.class, it))) { addViolation(o, throwsList); } return null; } private boolean isIgnored(ASTMethodOrConstructorDeclaration owner) { if (getProperty(IGNORE_JUNIT_COMPLETELY_DESCRIPTOR) && TestFrameworksUtil.isJUnit3Class(owner.getEnclosingType())) { return true; } else if (owner instanceof ASTMethodDeclaration) { ASTMethodDeclaration m = (ASTMethodDeclaration) owner; return TestFrameworksUtil.isTestMethod(m) || TestFrameworksUtil.isTestConfigurationMethod(m) // Ignore overridden methods, the issue should be marked on the method definition || m.isOverridden(); } return false; } }
2,699
39.909091
124
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/AvoidThrowingNullPointerExceptionRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableAccess; 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.symbols.JLocalVariableSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * Finds <code>throw</code> statements containing <code>NullPointerException</code> * instances as thrown values * * @author <a href="mailto:michaeller.2012@gmail.com">Mykhailo Palahuta</a> */ public class AvoidThrowingNullPointerExceptionRule extends AbstractJavaRulechainRule { public AvoidThrowingNullPointerExceptionRule() { super(ASTThrowStatement.class); } @Override public Object visit(ASTThrowStatement throwStmt, Object data) { ASTExpression thrown = throwStmt.getExpr(); if (TypeTestUtil.isA(NullPointerException.class, thrown)) { addViolation(data, throwStmt); } else if (thrown instanceof ASTVariableAccess) { JVariableSymbol sym = ((ASTVariableAccess) thrown).getReferencedSym(); if (sym instanceof JLocalVariableSymbol && hasNpeValue((ASTVariableAccess) thrown)) { addViolation(data, throwStmt); } } return null; } private boolean hasNpeValue(ASTVariableAccess thrown) { DataflowResult dataflow = DataflowPass.getDataflowResult(thrown.getRoot()); ReachingDefinitionSet reaching = dataflow.getReachingDefinitions(thrown); if (reaching.isNotFullyKnown()) { // we lean towards false negatives... maybe we should be able // to report this with a lower priority return false; } for (AssignmentEntry it : reaching.getReaching()) { if (!TypeTestUtil.isExactlyA(NullPointerException.class, it.getRhsType())) { return false; } } return true; } }
2,521
39.677419
97
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/CouplingBetweenObjectsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.HashSet; import java.util.Set; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTType; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.java.symbols.JAccessibleElementSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * CouplingBetweenObjects attempts to capture all unique Class attributes, local * variables, and return types to determine how many objects a class is coupled * to. This is only a gauge and isn't a hard and fast rule. The threshold value * is configurable and should be determined accordingly * * @author aglover * @since Feb 20, 2003 */ public class CouplingBetweenObjectsRule extends AbstractJavaRule { private static final PropertyDescriptor<Integer> THRESHOLD_DESCRIPTOR = PropertyFactory.intProperty("threshold") .desc("Unique type reporting threshold") .require(positive()).defaultValue(20).build(); private int couplingCount; private boolean inInterface; private final Set<JTypeMirror> typesFoundSoFar = new HashSet<>(); public CouplingBetweenObjectsRule() { definePropertyDescriptor(THRESHOLD_DESCRIPTOR); } @Override public Object visit(ASTCompilationUnit cu, Object data) { super.visit(cu, data); if (couplingCount > getProperty(THRESHOLD_DESCRIPTOR)) { addViolation(data, cu, "A value of " + couplingCount + " may denote a high amount of coupling within the class"); } couplingCount = 0; typesFoundSoFar.clear(); return null; } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { boolean prev = inInterface; inInterface = node.isInterface(); super.visit(node, data); inInterface = prev; return null; } @Override public Object visit(ASTMethodDeclaration node, Object data) { ASTType type = node.getResultTypeNode(); checkVariableType(type); return super.visit(node, data); } @Override public Object visit(ASTLocalVariableDeclaration node, Object data) { ASTType type = node.getTypeNode(); checkVariableType(type); return super.visit(node, data); } @Override public Object visit(ASTFormalParameter node, Object data) { ASTType type = node.getTypeNode(); checkVariableType(type); return super.visit(node, data); } @Override public Object visit(ASTFieldDeclaration node, Object data) { ASTType type = node.getTypeNode(); checkVariableType(type); return super.visit(node, data); } /** * performs a check on the variable and updates the counter. Counter is * instance for a class and is reset upon new class scan. * * @param typeNode The variable type. */ private void checkVariableType(ASTType typeNode) { if (inInterface || typeNode == null) { return; } // if the field is of any type other than the class type // increment the count JTypeMirror t = typeNode.getTypeMirror(); if (!this.ignoreType(typeNode, t) && this.typesFoundSoFar.add(t)) { couplingCount++; } } /** * Filters variable type - we don't want primitives, wrappers, strings, etc. * This needs more work. I'd like to filter out super types and perhaps * interfaces * * @param t The variable type. * * @return boolean true if variableType is not what we care about */ private boolean ignoreType(ASTType typeNode, JTypeMirror t) { if (typeNode.getEnclosingType().getSymbol().equals(t.getSymbol())) { return true; } JTypeDeclSymbol symbol = t.getSymbol(); return symbol == null || JAccessibleElementSymbol.PRIMITIVE_PACKAGE.equals(symbol.getPackageName()) || t.isPrimitive() || t.isBoxedPrimitive(); } }
4,841
33.340426
115
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/NPathComplexityRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.math.BigInteger; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Simple n-path complexity rule. * * @author Clément Fournier * @author Jason Bennett */ public class NPathComplexityRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Integer> REPORT_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("reportLevel").desc("N-Path Complexity reporting threshold") .require(positive()).defaultValue(200).build(); public NPathComplexityRule() { super(ASTMethodOrConstructorDeclaration.class); definePropertyDescriptor(REPORT_LEVEL_DESCRIPTOR); } @Override public Object visitJavaNode(JavaNode node, Object data) { return visitMethod((ASTMethodOrConstructorDeclaration) node, (RuleContext) data); } private Object visitMethod(ASTMethodOrConstructorDeclaration node, RuleContext data) { int reportLevel = getProperty(REPORT_LEVEL_DESCRIPTOR); if (!JavaMetrics.NPATH.supports(node)) { return data; } BigInteger npath = MetricsUtil.computeMetric(JavaMetrics.NPATH, node); if (npath.compareTo(BigInteger.valueOf(reportLevel)) >= 0) { addViolation(data, node, new String[] {node instanceof ASTMethodDeclaration ? "method" : "constructor", PrettyPrintingUtil.displaySignature(node), String.valueOf(npath), String.valueOf(reportLevel)}); } return data; } }
2,396
36.453125
115
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/CyclomaticComplexityRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.CycloOption; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.metrics.MetricOptions; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Cyclomatic complexity rule using metrics. * * @author Clément Fournier, based on work by Alan Hohn and Donald A. Leckie * @version 6.0.0 */ public class CyclomaticComplexityRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Integer> CLASS_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("classReportLevel") .desc("Total class complexity reporting threshold") .require(positive()).defaultValue(80).build(); private static final PropertyDescriptor<Integer> METHOD_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("methodReportLevel") .desc("Cyclomatic complexity reporting threshold") .require(positive()).defaultValue(10).build(); private static final Map<String, CycloOption> OPTION_MAP; static { OPTION_MAP = new HashMap<>(); OPTION_MAP.put(CycloOption.IGNORE_BOOLEAN_PATHS.valueName(), CycloOption.IGNORE_BOOLEAN_PATHS); OPTION_MAP.put(CycloOption.CONSIDER_ASSERT.valueName(), CycloOption.CONSIDER_ASSERT); } private static final PropertyDescriptor<List<CycloOption>> CYCLO_OPTIONS_DESCRIPTOR = PropertyFactory.enumListProperty("cycloOptions", OPTION_MAP) .desc("Choose options for the computation of Cyclo") .emptyDefaultValue() .build(); public CyclomaticComplexityRule() { super(ASTMethodOrConstructorDeclaration.class, ASTAnyTypeDeclaration.class); definePropertyDescriptor(CLASS_LEVEL_DESCRIPTOR); definePropertyDescriptor(METHOD_LEVEL_DESCRIPTOR); definePropertyDescriptor(CYCLO_OPTIONS_DESCRIPTOR); } @Override public Object visitJavaNode(JavaNode node, Object param) { if (node instanceof ASTAnyTypeDeclaration) { visitTypeDecl((ASTAnyTypeDeclaration) node, param); } return null; } public Object visitTypeDecl(ASTAnyTypeDeclaration node, Object data) { MetricOptions cycloOptions = MetricOptions.ofOptions(getProperty(CYCLO_OPTIONS_DESCRIPTOR)); if (JavaMetrics.WEIGHED_METHOD_COUNT.supports(node)) { int classWmc = MetricsUtil.computeMetric(JavaMetrics.WEIGHED_METHOD_COUNT, node, cycloOptions); if (classWmc >= getProperty(CLASS_LEVEL_DESCRIPTOR)) { int classHighest = (int) MetricsUtil.computeStatistics(JavaMetrics.CYCLO, node.getOperations(), cycloOptions).getMax(); String[] messageParams = {PrettyPrintingUtil.getPrintableNodeKind(node), node.getSimpleName(), " total", classWmc + " (highest " + classHighest + ")", }; addViolation(data, node, messageParams); } } return data; } @Override public final Object visit(ASTMethodDeclaration node, Object data) { visitMethodLike(node, data); return data; } @Override public final Object visit(ASTConstructorDeclaration node, Object data) { visitMethodLike(node, data); return data; } private void visitMethodLike(ASTMethodOrConstructorDeclaration node, Object data) { MetricOptions cycloOptions = MetricOptions.ofOptions(getProperty(CYCLO_OPTIONS_DESCRIPTOR)); if (JavaMetrics.CYCLO.supports(node)) { int cyclo = MetricsUtil.computeMetric(JavaMetrics.CYCLO, node, cycloOptions); if (cyclo >= getProperty(METHOD_LEVEL_DESCRIPTOR)) { String opname = PrettyPrintingUtil.displaySignature(node); String kindname = node instanceof ASTConstructorDeclaration ? "constructor" : "method"; addViolation(data, node, new String[] {kindname, opname, "", "" + cyclo, }); } } } }
5,240
38.406015
135
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveImportsRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.rule.internal.AbstractJavaCounterCheckRule; /** * ExcessiveImports attempts to count all unique imports a class contains. This * rule will count a "import com.something.*;" as a single import. This is a * unique situation and I'd like to create an audit type rule that captures * those. * * @author aglover * @since Feb 21, 2003 */ public class ExcessiveImportsRule extends AbstractJavaCounterCheckRule<ASTCompilationUnit> { public ExcessiveImportsRule() { super(ASTCompilationUnit.class); } @Override protected int defaultReportLevel() { return 30; } @Override protected boolean isViolation(ASTCompilationUnit node, int reportLevel) { return node.children(ASTImportDeclaration.class).count() >= reportLevel; } }
1,082
29.083333
92
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ClassWithOnlyPrivateConstructorsShouldBeFinalRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility.V_PRIVATE; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.JModifier; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; public class ClassWithOnlyPrivateConstructorsShouldBeFinalRule extends AbstractJavaRulechainRule { public ClassWithOnlyPrivateConstructorsShouldBeFinalRule() { super(ASTClassOrInterfaceDeclaration.class); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (node.isRegularClass() && !node.hasModifiers(JModifier.FINAL) && !node.isAnnotationPresent("lombok.Value") && !hasPublicLombokConstructors(node) && hasOnlyPrivateCtors(node) && hasNoSubclasses(node)) { asCtx(data).addViolation(node); } return null; } private boolean hasPublicLombokConstructors(ASTClassOrInterfaceDeclaration node) { return node.getDeclaredAnnotations() .filter(it -> TypeTestUtil.isA("lombok.NoArgsConstructor", it) || TypeTestUtil.isA("lombok.RequiredArgsConstructor", it) || TypeTestUtil.isA("lombok.AllArgsConstructor", it)) .any(it -> it.getFlatValue("access").filterIs(ASTNamedReferenceExpr.class).none(ref -> "PRIVATE".equals(ref.getName()))); } private boolean hasNoSubclasses(ASTClassOrInterfaceDeclaration klass) { return klass.getRoot() .descendants(ASTAnyTypeDeclaration.class) .crossFindBoundaries() .none(it -> doesExtend(it, klass)); } private boolean doesExtend(ASTAnyTypeDeclaration sub, ASTClassOrInterfaceDeclaration superClass) { return sub != superClass && TypeTestUtil.isA(superClass.getTypeMirror().getErasure(), sub); } private boolean hasOnlyPrivateCtors(ASTClassOrInterfaceDeclaration node) { return node.getDeclarations(ASTConstructorDeclaration.class).all(it -> it.getVisibility() == V_PRIVATE) && (node.getVisibility() == V_PRIVATE // then the default ctor is private || node.getDeclarations(ASTConstructorDeclaration.class).nonEmpty()); } }
2,731
43.064516
140
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveClassLengthRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.rule.internal.AbstractJavaCounterCheckRule; /** * This rule detects when a class exceeds a certain threshold. i.e. if a class * has more than 1000 lines of code. * * @deprecated Use {@link NcssCountRule} instead. */ @Deprecated public class ExcessiveClassLengthRule extends AbstractJavaCounterCheckRule.AbstractLineLengthCheckRule<ASTAnyTypeDeclaration> { public ExcessiveClassLengthRule() { super(ASTAnyTypeDeclaration.class); } @Override protected int defaultReportLevel() { return 1000; } }
778
27.851852
127
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/UselessOverridingMethodRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.ast.JModifier.FINAL; import static net.sourceforge.pmd.lang.java.ast.JModifier.NATIVE; import static net.sourceforge.pmd.lang.java.ast.JModifier.SYNCHRONIZED; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import java.lang.reflect.Modifier; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTExpressionStatement; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTList; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTSuperExpression; import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils; 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.OverloadSelectionResult; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; public class UselessOverridingMethodRule extends AbstractJavaRulechainRule { // TODO extend AbstractIgnoredAnnotationRule node // TODO ignore if there is javadoc private static final PropertyDescriptor<Boolean> IGNORE_ANNOTATIONS_DESCRIPTOR = booleanProperty("ignoreAnnotations") .defaultValue(false) .desc("Ignore methods that have annotations (except @Override)") .build(); public UselessOverridingMethodRule() { super(ASTMethodDeclaration.class); definePropertyDescriptor(IGNORE_ANNOTATIONS_DESCRIPTOR); } @Override public Object visit(ASTMethodDeclaration node, Object data) { if (!node.isOverridden() || node.getBody() == null // Can skip methods which are final or have new behavior (synchronized, native) || node.getModifiers().hasAny(FINAL, NATIVE, SYNCHRONIZED) // We can also skip the 'clone' method as they are generally // 'useless' but as it is considered a 'good practice' to // implement them anyway ( see bug 1522517) || JavaAstUtils.isCloneMethod(node)) { return null; } // skip annotated methods if (!getProperty(IGNORE_ANNOTATIONS_DESCRIPTOR) && node.getDeclaredAnnotations().any(it -> !TypeTestUtil.isA(Override.class, it))) { return null; } ASTStatement statement = ASTList.singleOrNull(node.getBody()); // Only process functions with one statement if (statement == null) { return null; } if ((statement instanceof ASTExpressionStatement || statement instanceof ASTReturnStatement) && statement.getNumChildren() == 1 && statement.getChild(0) instanceof ASTMethodCall) { // merely calling super.foo() or returning super.foo() ASTMethodCall methodCall = (ASTMethodCall) statement.getChild(0); if (methodCall.getQualifier() instanceof ASTSuperExpression && methodCall.getArguments().size() == node.getArity() // might be disambiguating: Interface.super.foo() && JavaAstUtils.isUnqualifiedSuper(methodCall.getQualifier())) { OverloadSelectionResult overload = methodCall.getOverloadSelectionInfo(); if (!overload.isFailed() // note: don't compare symbols, as the equals method for method symbols is broken for now && overload.getMethodType().equals(node.getOverriddenMethod()) && sameModifiers(node.getOverriddenMethod().getSymbol(), node.getSymbol()) && argumentsAreUnchanged(node, methodCall)) { addViolation(data, node); } } } return null; } private boolean argumentsAreUnchanged(ASTMethodDeclaration node, ASTMethodCall methodCall) { ASTArgumentList arg = methodCall.getArguments(); int i = 0; for (ASTFormalParameter formal : node.getFormalParameters()) { if (!JavaAstUtils.isReferenceToVar((ASTExpression) arg.getChild(i), formal.getVarId().getSymbol())) { return false; } i++; } return true; } private boolean sameModifiers(JExecutableSymbol superMethod, JMethodSymbol subMethod) { int visibilityMask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (visibilityMask & subMethod.getModifiers()) == (visibilityMask & superMethod.getModifiers()) // making visible in another package && !isProtectedElevatingVisibility(superMethod, subMethod); } private boolean isProtectedElevatingVisibility(JExecutableSymbol superMethod, JMethodSymbol subMethod) { return Modifier.isProtected(subMethod.getModifiers()) && !subMethod.getPackageName().equals(superMethod.getPackageName()); } }
5,478
43.909836
113
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ExceptionAsFlowControlRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import net.sourceforge.pmd.lang.java.ast.ASTBodyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTCatchClause; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTTryStatement; 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.types.JTypeMirror; /** * Catches the use of exception statements as a flow control device. * * @author Will Sargent */ public class ExceptionAsFlowControlRule extends AbstractJavaRulechainRule { // TODO tests: // - catch a supertype of the exception (unless this is unwanted) // - throw statements with not just a new SomethingExpression, eg a method call returning an exception public ExceptionAsFlowControlRule() { super(ASTThrowStatement.class); } @Override public Object visit(ASTThrowStatement node, Object data) { JTypeMirror thrownType = node.getExpr().getTypeMirror(); JavaNode parent = node.getParent(); while (!(parent instanceof ASTBodyDeclaration)) { if (parent instanceof ASTCatchClause) { // if the exception is thrown in a catch block, then we // have to ignore the try stmt (jump past it). parent = parent.getParent().getParent(); continue; } if (parent instanceof ASTTryStatement) { // maybe the exception is being caught here. for (ASTCatchClause catchClause : ((ASTTryStatement) parent).getCatchClauses()) { if (catchClause.getParameter().getAllExceptionTypes().any(it -> thrownType.isSubtypeOf(it.getTypeMirror()))) { if (!JavaAstUtils.isJustRethrowException(catchClause)) { asCtx(data).addViolation(catchClause, node.getReportLocation().getStartLine()); return null; } else { break; } } } } parent = parent.getParent(); } return null; } }
2,418
39.316667
130
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/LawOfDemeterRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.ast.BinaryOp.INSTANCEOF; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isArrayLengthFieldAccess; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isCallOnThisInstance; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isInfixExprWithOperator; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isRefToFieldOfThisClass; import static net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils.isThisOrSuper; import static net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil.isGetterCall; import static net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil.isNullChecked; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.stream.Stream; 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.ASTArrayAccess; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; 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.ASTForeachStatement; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; 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.QualifiableExpression; 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.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.symbols.JClassSymbol; import net.sourceforge.pmd.lang.java.symbols.JFieldSymbol; import net.sourceforge.pmd.lang.java.symbols.JTypeDeclSymbol; import net.sourceforge.pmd.lang.java.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.JClassType; import net.sourceforge.pmd.lang.java.types.JTypeMirror; import net.sourceforge.pmd.lang.java.types.TypeOps; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * This rule can detect possible violations of the Law of Demeter. The Law of * Demeter is a simple rule, that says "only talk to friends". It helps to * reduce coupling between classes or objects. * <p> * See: * <ul> * <li>Andrew Hunt, David Thomas, and Ward Cunningham. The Pragmatic Programmer. * From Journeyman to Master. Addison-Wesley Longman, Amsterdam, October * 1999.</li> * <li>K.J. Lieberherr and I.M. Holland. Assuring good style for object-oriented * programs. Software, IEEE, 6(5):38–48, 1989.</li> * </ul> * * @author Clément Fournier * @since 5.0 * */ public class LawOfDemeterRule extends AbstractJavaRule { private static final PropertyDescriptor<Integer> TRUST_RADIUS = PropertyFactory.intProperty("trustRadius") .desc("Maximum degree of trusted data. The default of 1 is the most restrictive.") .require(positive()) .defaultValue(1) .build(); private static final String FIELD_ACCESS_ON_FOREIGN_VALUE = "Access to field `{0}` on foreign value `{1}` (degree {2})"; private static final String METHOD_CALL_ON_FOREIGN_VALUE = "Call to `{0}` on foreign value `{1}` (degree {2})"; public LawOfDemeterRule() { definePropertyDescriptor(TRUST_RADIUS); } /** * This cache is there to prevent recursion in case of cycles. It * also avoids recomputing the degree of too many nodes, as the degree * of a call chain depends on the degree of the qualifier. {@link #visit(ASTMethodCall, Object)} * is called on every part of the chain, so without memoization we * would run in O(n2). */ private final Map<ASTExpression, Integer> degreeCache = new LinkedHashMap<>(); @Override public void apply(Node target, RuleContext ctx) { degreeCache.clear(); // reimplement our own traversal instead of using the rulechain, // so that we have a stable traversal order. ((ASTCompilationUnit) target) .descendants().crossFindBoundaries() .forEach(it -> { if (it instanceof ASTMethodCall) { this.visit((ASTMethodCall) it, ctx); } else if (it instanceof ASTFieldAccess) { this.visit((ASTFieldAccess) it, ctx); } }); degreeCache.clear(); // avoid memory leak } /** * Only report the first occurrences of a breach of trust. Those are * the ones that need to be fixed. */ private boolean isReportedDegree(int degree) { return degree == getProperty(TRUST_RADIUS) + 1; } @Override public Object visit(ASTFieldAccess node, Object data) { if (shouldReport(node)) { addViolationWithMessage( data, node, FIELD_ACCESS_ON_FOREIGN_VALUE, new Object[] { node.getName(), PrettyPrintingUtil.prettyPrint(node.getQualifier()), foreignDegree(node.getQualifier()), }); } return null; } @Override public Object visit(ASTMethodCall node, Object data) { if (shouldReport(node)) { addViolationWithMessage( data, node, METHOD_CALL_ON_FOREIGN_VALUE, new Object[] { node.getMethodName(), PrettyPrintingUtil.prettyPrint(node.getQualifier()), foreignDegree(node.getQualifier()), }); } return null; } private boolean shouldReport(QualifiableExpression expr) { ASTExpression qualifier = expr.getQualifier(); if (qualifier == null) { return false; } int degree = foreignDegree(expr); if (isReportedDegree(degree) && isUsedAsGetter(expr)) { if (expr.getParent() instanceof ASTVariableDeclarator) { // NOPMD #3786 // Stored in local var, don't report if some usages escape. // In that case, usage sites with non-escaping usage will be reported. return isAllowedStore(((ASTVariableDeclarator) expr.getParent()).getVarId()); } else { return true; } } // Reported degree may be higher if LHS is a local var with the reported degree. // If some usages of that local escape, the local hasn't been reported. Those usages // that don't escape need to be reported. if (qualifier instanceof ASTVariableAccess && isReportedDegree(foreignDegree(qualifier))) { JVariableSymbol sym = ((ASTVariableAccess) qualifier).getReferencedSym(); return sym != null && !isAllowedStore(sym.tryGetNode()); } return false; } private boolean isAllowedStore(ASTVariableDeclaratorId varId) { return varId != null && varId.getLocalUsages().stream().noneMatch(this::escapesMethod); } private int foreignDegree(@Nullable ASTExpression expr) { if (expr == null) { return 0; } Integer cachedValue = degreeCache.get(expr); if (cachedValue == null) { degreeCache.put(expr, -1); // recursion guard int computed = foreignDegreeImpl(expr); degreeCache.put(expr, computed); // System.out.println("Degree " + computed + ": " + expr); return computed; } else if (cachedValue == -1) { return cachedValue; // recursion } else { return cachedValue; } } private int foreignDegreeImpl(ASTExpression expr) { if (expr instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) expr; return methodCallDegree(call); } else if (expr instanceof ASTFieldAccess) { ASTFieldAccess access = (ASTFieldAccess) expr; return fieldAccessDegree(access); } else if (expr instanceof ASTVariableAccess) { ASTVariableAccess access = (ASTVariableAccess) expr; return variableDegree(access); } else if (expr instanceof ASTArrayAccess) { return foreignDegree(((ASTArrayAccess) expr).getQualifier()); } else if (expr instanceof ASTConstructorCall) { return ACCESSIBLE; } else if (expr instanceof ASTTypeExpression || isThisOrSuper(expr)) { return TRUSTED; } return ACCESSIBLE; } private int methodCallDegree(ASTMethodCall call) { if (call.getOverloadSelectionInfo().isFailed() // be conservative || call.getMethodType().isStatic() // static methods are taken to be construction methods. || isCallOnThisInstance(call) || call.getQualifier() == null // either static or call on this. Prevents NPE when unresolved || isFactoryMethod(call) || isBuilderPattern(call.getQualifier()) || isPureData(call)) { return ACCESSIBLE; } else if (isPureDataContainer(call.getMethodType().getDeclaringType()) || isPureDataContainer(call.getTypeMirror()) || !isGetterCall(call) || isTransformationMethod(call)) { return asForeignAsQualifier(call); } return moreForeignThanQualifier(call); } private boolean isTransformationMethod(ASTMethodCall expr) { if (expr.getQualifier() == null) { return false; } JTypeMirror qualType = expr.getQualifier().getTypeMirror(); JTypeMirror returnType = expr.getTypeMirror(); // note: there is a possible optimization that only tests // if types are related when their names are similar, look into history. return TypeOps.areRelated(qualType, returnType); } private boolean isPureData(ASTExpression expr) { return TypeTestUtil.isA(String.class, expr) || TypeTestUtil.isA(StringBuilder.class, expr) || TypeTestUtil.isA(StringBuffer.class, expr) || expr.getTypeMirror().isPrimitive() || expr.getTypeMirror().isBoxedPrimitive() || isNullChecked(expr) || isInfixExprWithOperator(expr.getParent(), INSTANCEOF); } private boolean isPureDataContainer(JTypeMirror type) { JTypeDeclSymbol symbol = type.getSymbol(); if (symbol instanceof JClassSymbol) { // NOPMD return "java.util".equals(symbol.getPackageName()) // collection, map, iterator, properties, etc || TypeTestUtil.isA(Stream.class, type) || TypeTestUtil.isA(Class.class, type) || TypeTestUtil.isA(org.w3c.dom.NodeList.class, type) || TypeTestUtil.isA(org.w3c.dom.NamedNodeMap.class, type) || type.isArray(); } return false; } private boolean escapesMethod(ASTExpression expr) { return expr.getParent() instanceof ASTArgumentList || expr.getParent() instanceof ASTReturnStatement || expr.getParent() instanceof ASTThrowStatement; } private boolean isUsedAsGetter(ASTExpression expr) { return !escapesMethod(expr) && !(expr.getParent() instanceof ASTExpressionStatement); } private int variableDegree(ASTVariableAccess expr) { DataflowResult dataflow = DataflowPass.getDataflowResult(expr.getRoot()); ReachingDefinitionSet reaching = dataflow.getReachingDefinitions(expr); if (reaching.isNotFullyKnown()) { // a field symbol, normally return expr.getReferencedSym() instanceof JFieldSymbol ? fieldAccessDegree(expr) : TRUSTED; // unresolved, or failure in data flow pass } // note this max could be changed to min to get a more conservative // strategy, trading recall for precision. maybe make that configurable return reaching.getReaching().stream() .mapToInt(this::foreignDegree).max().orElse(TRUSTED); } private int fieldAccessDegree(ASTNamedReferenceExpr expr) { if (isRefToFieldOfThisClass(expr) || isPureData(expr)) { return ACCESSIBLE; } else if (isArrayLengthFieldAccess(expr)) { return asForeignAsQualifier((ASTFieldAccess) expr); } else if (expr instanceof ASTFieldAccess) { return moreForeignThanQualifier((ASTFieldAccess) expr); } else { return ACCESSIBLE; } } private int foreignDegree(AssignmentEntry def) { if (def.isForeachVar()) { ASTForeachStatement foreach = def.getVarId().ancestors(ASTForeachStatement.class).firstOrThrow(); // same degree as the list return foreignDegree(foreach.getIterableExpr()); } // formal parameters are not foreign otherwise we couldn't call any methods on them if (def.getVarId().isFormalParameter()) { return 1; } return foreignDegree(def.getRhsAsExpression()); } private boolean isBuilderPattern(ASTExpression expr) { return typeEndsWith(expr, "Builder"); } private boolean isFactoryMethod(ASTMethodCall expr) { ASTExpression qualifier = expr.getQualifier(); if (qualifier != null) { // NOPMD SimplifyBooleanReturns https://github.com/pmd/pmd/issues/3786 return typeEndsWith(qualifier, "Factory") || nameEndsWith(qualifier, "Factory") || nameIs(qualifier, "factory"); } return false; } private boolean nameEndsWith(ASTExpression expr, String suffix) { return expr instanceof ASTNamedReferenceExpr && ((ASTNamedReferenceExpr) expr).getName().endsWith(suffix); } private boolean nameIs(ASTExpression expr, String name) { return expr instanceof ASTNamedReferenceExpr && ((ASTNamedReferenceExpr) expr).getName().equals(name); } private boolean typeEndsWith(ASTExpression expr, String suffix) { return expr != null && expr.getTypeMirror() instanceof JClassType && expr.getTypeMirror().getSymbol().getSimpleName().endsWith(suffix); } /** * Degree 0. * <ul> * <li>`this` * </ul> * You can use the object however you like. */ private static final int TRUSTED = 0; /** * Degree 1. * <ul> * <li>Fields of this class, but not of `this` instance (we need to * access their fields to write equals, compareTo, etc.) * <li>Method parameters. * <li>Result of construction methods (including factories, builders, * ctors, etc). * </ul> * You can use any method, but you can't use yourself the result of * a getter, or field (though you can let it escape). */ private static final int ACCESSIBLE = 1; private int asForeignAsQualifier(QualifiableExpression e) { return foreignDegree(Objects.requireNonNull(e.getQualifier())); } private int moreForeignThanQualifier(QualifiableExpression e) { return 1 + foreignDegree(Objects.requireNonNull(e.getQualifier())); } }
16,491
40.437186
124
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ImmutableFieldRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.util.CollectionUtil.setOf; import java.util.Set; import net.sourceforge.pmd.lang.ast.NodeStream; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; 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.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTLambdaExpression; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.ast.JModifier; 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.AssignmentEntry; import net.sourceforge.pmd.lang.java.rule.internal.DataflowPass.DataflowResult; import net.sourceforge.pmd.util.CollectionUtil; public class ImmutableFieldRule extends AbstractJavaRulechainRule { private static final Set<String> INVALIDATING_CLASS_ANNOT = setOf( "lombok.Builder", "lombok.Data", "lombok.Setter", "lombok.Value" ); private static final Set<String> INVALIDATING_FIELD_ANNOT = setOf( "lombok.Setter" ); public ImmutableFieldRule() { super(ASTFieldDeclaration.class); } @Override public Object visit(ASTFieldDeclaration field, Object data) { ASTAnyTypeDeclaration enclosingType = field.getEnclosingType(); if (field.getEffectiveVisibility().isAtMost(Visibility.V_PRIVATE) && !field.getModifiers().hasAny(JModifier.VOLATILE, JModifier.STATIC, JModifier.FINAL) && !JavaAstUtils.hasAnyAnnotation(enclosingType, INVALIDATING_CLASS_ANNOT) && !JavaAstUtils.hasAnyAnnotation(field, INVALIDATING_FIELD_ANNOT)) { DataflowResult dataflow = DataflowPass.getDataflowResult(field.getRoot()); outer: for (ASTVariableDeclaratorId varId : field.getVarIds()) { boolean hasWrite = false; for (ASTNamedReferenceExpr usage : varId.getLocalUsages()) { if (usage.getAccessType() == AccessType.WRITE) { hasWrite = true; JavaNode enclosing = usage.ancestors().map(NodeStream.asInstanceOf(ASTLambdaExpression.class, ASTAnyTypeDeclaration.class, ASTConstructorDeclaration.class)).first(); if (!(enclosing instanceof ASTConstructorDeclaration) || enclosing.getEnclosingType() != enclosingType) { continue outer; // written-to outside ctor } } } // we now know that the field is maybe not written to, // or maybe just inside constructors. boolean isBlank = varId.getInitializer() == null; if (!hasWrite && !isBlank) { //todo this case may also handle static fields easily. asCtx(data).addViolation(varId, varId.getName()); } else if (hasWrite && defaultValueDoesNotReachEndOfCtor(dataflow, varId)) { asCtx(data).addViolation(varId, varId.getName()); } } } return null; } private boolean defaultValueDoesNotReachEndOfCtor(DataflowResult dataflow, ASTVariableDeclaratorId varId) { AssignmentEntry fieldDef = DataflowPass.getFieldDefinition(varId); // first assignments to the field Set<AssignmentEntry> killers = dataflow.getKillers(fieldDef); // no killer isFieldAssignmentAtEndOfCtor => the field is assigned on all code paths // no killer isReassignedOnSomeCodePath => the field is assigned at most once // => the field is assigned exactly once. return CollectionUtil.none( killers, killer -> killer.isFieldAssignmentAtEndOfCtor() || isReassignedOnSomeCodePath(dataflow, killer) ); } private boolean isReassignedOnSomeCodePath(DataflowResult dataflow, AssignmentEntry anAssignment) { Set<AssignmentEntry> killers = dataflow.getKillers(anAssignment); return CollectionUtil.any(killers, killer -> !killer.isFieldAssignmentAtEndOfCtor()); } }
4,797
42.618182
189
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/NcssCountRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodOrConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.ast.internal.PrettyPrintingUtil; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics; import net.sourceforge.pmd.lang.java.metrics.JavaMetrics.NcssOption; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.metrics.MetricOptions; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.AssertionUtil; /** * Simple rule for Ncss. Maybe to be enriched with type specific thresholds. * * @author Clément Fournier */ public final class NcssCountRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Integer> METHOD_REPORT_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("methodReportLevel") .desc("NCSS reporting threshold for methods") .require(positive()) .defaultValue(60) .build(); private static final PropertyDescriptor<Integer> CLASS_REPORT_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("classReportLevel") .desc("NCSS reporting threshold for classes") .require(positive()) .defaultValue(1500) .build(); private static final PropertyDescriptor<List<NcssOption>> NCSS_OPTIONS_DESCRIPTOR; static { Map<String, NcssOption> options = new HashMap<>(); options.put(NcssOption.COUNT_IMPORTS.valueName(), NcssOption.COUNT_IMPORTS); NCSS_OPTIONS_DESCRIPTOR = PropertyFactory.enumListProperty("ncssOptions", options) .desc("Choose options for the computation of Ncss") .emptyDefaultValue() .build(); } public NcssCountRule() { super(ASTMethodOrConstructorDeclaration.class, ASTAnyTypeDeclaration.class); definePropertyDescriptor(METHOD_REPORT_LEVEL_DESCRIPTOR); definePropertyDescriptor(CLASS_REPORT_LEVEL_DESCRIPTOR); definePropertyDescriptor(NCSS_OPTIONS_DESCRIPTOR); } @Override public Object visitJavaNode(JavaNode node, Object data) { int methodReportLevel = getProperty(METHOD_REPORT_LEVEL_DESCRIPTOR); int classReportLevel = getProperty(CLASS_REPORT_LEVEL_DESCRIPTOR); MetricOptions ncssOptions = MetricOptions.ofOptions(getProperty(NCSS_OPTIONS_DESCRIPTOR)); if (node instanceof ASTAnyTypeDeclaration) { visitTypeDecl((ASTAnyTypeDeclaration) node, classReportLevel, ncssOptions, (RuleContext) data); } else if (node instanceof ASTMethodOrConstructorDeclaration) { visitMethod((ASTMethodOrConstructorDeclaration) node, methodReportLevel, ncssOptions, (RuleContext) data); } else { throw AssertionUtil.shouldNotReachHere("unreachable"); } return data; } private void visitTypeDecl(ASTAnyTypeDeclaration node, int level, MetricOptions ncssOptions, RuleContext data) { if (JavaMetrics.NCSS.supports(node)) { int classSize = MetricsUtil.computeMetric(JavaMetrics.NCSS, node, ncssOptions); int classHighest = (int) MetricsUtil.computeStatistics(JavaMetrics.NCSS, node.getOperations(), ncssOptions).getMax(); if (classSize >= level) { String[] messageParams = {PrettyPrintingUtil.getPrintableNodeKind(node), node.getSimpleName(), classSize + " (Highest = " + classHighest + ")", }; addViolation(data, node, messageParams); } } } private void visitMethod(ASTMethodOrConstructorDeclaration node, int level, MetricOptions ncssOptions, RuleContext data) { if (JavaMetrics.NCSS.supports(node)) { int methodSize = MetricsUtil.computeMetric(JavaMetrics.NCSS, node, ncssOptions); if (methodSize >= level) { addViolation(data, node, new String[] { node instanceof ASTMethodDeclaration ? "method" : "constructor", PrettyPrintingUtil.displaySignature(node), "" + methodSize, }); } } } }
5,178
40.103175
129
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/AvoidDeeplyNestedIfStmtsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTIfStatement; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class AvoidDeeplyNestedIfStmtsRule extends AbstractJavaRule { private int depth; private int depthLimit; private static final PropertyDescriptor<Integer> PROBLEM_DEPTH_DESCRIPTOR = PropertyFactory.intProperty("problemDepth") .desc("The if statement depth reporting threshold") .require(positive()).defaultValue(3).build(); public AvoidDeeplyNestedIfStmtsRule() { definePropertyDescriptor(PROBLEM_DEPTH_DESCRIPTOR); } @Override public Object visit(ASTCompilationUnit node, Object data) { depth = 0; depthLimit = getProperty(PROBLEM_DEPTH_DESCRIPTOR); return super.visit(node, data); } @Override public Object visit(ASTIfStatement node, Object data) { if (!node.hasElse()) { depth++; } super.visit(node, data); if (depth == depthLimit) { addViolation(data, node); } depth--; return data; } }
1,549
30
85
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ExcessiveParameterListRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; import net.sourceforge.pmd.lang.java.ast.AccessNode.Visibility; import net.sourceforge.pmd.lang.java.rule.internal.AbstractJavaCounterCheckRule; /** * This rule detects an abnormally long parameter list. Note: This counts Nodes, * and not necessarily parameters, so the numbers may not match up. (But * topcount and sigma should work.) */ public class ExcessiveParameterListRule extends AbstractJavaCounterCheckRule<ASTFormalParameters> { public ExcessiveParameterListRule() { super(ASTFormalParameters.class); } @Override protected int defaultReportLevel() { return 10; } @Override protected boolean isIgnored(ASTFormalParameters node) { return areParametersOfPrivateConstructor(node); } private boolean areParametersOfPrivateConstructor(ASTFormalParameters params) { Node parent = params.getParent(); return parent instanceof ASTConstructorDeclaration && ((ASTConstructorDeclaration) parent).getVisibility() == Visibility.V_PRIVATE; } @Override protected boolean isViolation(ASTFormalParameters node, int reportLevel) { return node.size() > reportLevel; } }
1,498
32.311111
99
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/GodClassRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.ACCESS_TO_FOREIGN_DATA; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.TIGHT_CLASS_COHESION; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.WEIGHED_METHOD_COUNT; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.util.StringUtil; /** * The God Class Rule detects the God Class design flaw using metrics. A god class does too many things, is very big and * complex. It should be split apart to be more object-oriented. The rule uses the detection strategy described in [1]. * The violations are reported against the entire class. * * <p>[1] Lanza. Object-Oriented Metrics in Practice. Page 80. * * @since 5.0 */ public class GodClassRule extends AbstractJavaRulechainRule { /** * Very high threshold for WMC (Weighted Method Count). See: Lanza. Object-Oriented Metrics in Practice. Page 16. */ private static final int WMC_VERY_HIGH = 47; /** * Few means between 2 and 5. See: Lanza. Object-Oriented Metrics in Practice. Page 18. */ private static final int FEW_ATFD_THRESHOLD = 5; /** * One third is a low value. See: Lanza. Object-Oriented Metrics in Practice. Page 17. */ private static final double TCC_THRESHOLD = 1.0 / 3.0; public GodClassRule() { super(ASTClassOrInterfaceDeclaration.class); } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (!MetricsUtil.supportsAll(node, WEIGHED_METHOD_COUNT, TIGHT_CLASS_COHESION, ACCESS_TO_FOREIGN_DATA)) { return data; } int wmc = MetricsUtil.computeMetric(WEIGHED_METHOD_COUNT, node); double tcc = MetricsUtil.computeMetric(TIGHT_CLASS_COHESION, node); int atfd = MetricsUtil.computeMetric(ACCESS_TO_FOREIGN_DATA, node); if (wmc >= WMC_VERY_HIGH && atfd > FEW_ATFD_THRESHOLD && tcc < TCC_THRESHOLD) { addViolation(data, node, new Object[] {wmc, StringUtil.percentageString(tcc, 3), atfd, }); } return data; } }
2,499
34.714286
120
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/SwitchDensityRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch; import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression; import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike; import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.rule.internal.CommonPropertyDescriptors; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Switch Density - This is the number of statements over the number of * cases within a switch. The higher the value, the more work each case * is doing. * * <p>Its my theory, that when the Switch Density is high, you should start * looking at Subclasses or State Pattern to alleviate the problem.</p> * * @author David Dixon-Peugh * @author Clément Fournier */ public class SwitchDensityRule extends AbstractJavaRulechainRule { private static final PropertyDescriptor<Integer> REPORT_LEVEL = CommonPropertyDescriptors.reportLevelProperty() .desc("Threshold above which a switch statement or expression is reported") .require(positive()) .defaultValue(10) .build(); public SwitchDensityRule() { super(ASTSwitchStatement.class, ASTSwitchExpression.class); definePropertyDescriptor(REPORT_LEVEL); } @Override public Object visit(ASTSwitchStatement node, Object data) { return visitSwitchLike(node, data); } @Override public Object visit(ASTSwitchExpression node, Object data) { return visitSwitchLike(node, data); } public Void visitSwitchLike(ASTSwitchLike node, Object data) { // note: this does not cross find boundaries. int stmtCount = node.descendants(ASTStatement.class).count(); int labelCount = node.getBranches() .map(ASTSwitchBranch::getLabel) .sumBy(label -> label.isDefault() ? 1 : label.getExprList().count()); // note: if labelCount is zero, double division will produce +Infinity or NaN, not ArithmeticException double density = stmtCount / (double) labelCount; if (density >= getProperty(REPORT_LEVEL)) { addViolation(data, node); } return null; } }
2,582
36.985294
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/DataClassRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.NUMBER_OF_ACCESSORS; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.NUMBER_OF_PUBLIC_FIELDS; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.WEIGHED_METHOD_COUNT; import static net.sourceforge.pmd.lang.java.metrics.JavaMetrics.WEIGHT_OF_CLASS; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.JavaNode; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.util.StringUtil; /** * @author Clément Fournier * @since 6.0.0 */ public class DataClassRule extends AbstractJavaRulechainRule { // probably not worth using properties private static final int ACCESSOR_OR_FIELD_FEW_LEVEL = 3; private static final int ACCESSOR_OR_FIELD_MANY_LEVEL = 5; private static final double WOC_LEVEL = 1. / 3.; private static final int WMC_HIGH_LEVEL = 31; private static final int WMC_VERY_HIGH_LEVEL = 47; public DataClassRule() { super(ASTAnyTypeDeclaration.class); } @Override public Object visitJavaNode(JavaNode node, Object data) { visitTypeDecl((ASTAnyTypeDeclaration) node, (RuleContext) data); return null; } private void visitTypeDecl(ASTAnyTypeDeclaration node, RuleContext data) { if (!MetricsUtil.supportsAll(node, NUMBER_OF_ACCESSORS, NUMBER_OF_PUBLIC_FIELDS, WEIGHED_METHOD_COUNT, WEIGHT_OF_CLASS)) { return; } boolean isDataClass = interfaceRevealsData(node) && classRevealsDataAndLacksComplexity(node); if (isDataClass) { double woc = MetricsUtil.computeMetric(WEIGHT_OF_CLASS, node); int nopa = MetricsUtil.computeMetric(NUMBER_OF_PUBLIC_FIELDS, node); int noam = MetricsUtil.computeMetric(NUMBER_OF_ACCESSORS, node); int wmc = MetricsUtil.computeMetric(WEIGHED_METHOD_COUNT, node); addViolation(data, node, new Object[] {node.getSimpleName(), StringUtil.percentageString(woc, 3), nopa, noam, wmc, }); } } private boolean interfaceRevealsData(ASTAnyTypeDeclaration node) { double woc = MetricsUtil.computeMetric(WEIGHT_OF_CLASS, node); return woc < WOC_LEVEL; } private boolean classRevealsDataAndLacksComplexity(ASTAnyTypeDeclaration node) { int nopa = MetricsUtil.computeMetric(NUMBER_OF_PUBLIC_FIELDS, node); int noam = MetricsUtil.computeMetric(NUMBER_OF_ACCESSORS, node); int wmc = MetricsUtil.computeMetric(WEIGHED_METHOD_COUNT, node); return nopa + noam > ACCESSOR_OR_FIELD_FEW_LEVEL && wmc < WMC_HIGH_LEVEL || nopa + noam > ACCESSOR_OR_FIELD_MANY_LEVEL && wmc < WMC_VERY_HIGH_LEVEL; } }
3,108
38.35443
130
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/LoosePackageCouplingRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit; import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertySource; /** * The loose package coupling Rule can be used to ensure coupling outside of a * package hierarchy is minimized to all but an allowed set of classes from * within the package hierarchy. * * <p>For example, supposed you have the following package hierarchy: * <ul> * <li><code>org.sample</code></li> * <li><code>org.sample.impl</code></li> * <li><code>org.sample.util</code></li> * </ul> * And the allowed class <code>org.sample.SampleInterface</code>. * * <p>This rule can be used to ensure that all classes within the * <code>org.sample</code> package and its sub-packages are not used outside of * the <code>org.sample</code> package hierarchy. Further, the only allowed * usage outside of a class in the <code>org.sample</code> hierarchy would be * via <code>org.sample.SampleInterface</code>. */ public class LoosePackageCouplingRule extends AbstractJavaRule { private static final PropertyDescriptor<List<String>> PACKAGES_DESCRIPTOR = stringListProperty("packages").desc("Restricted packages").emptyDefaultValue().delim(',').build(); private static final PropertyDescriptor<List<String>> CLASSES_DESCRIPTOR = stringListProperty("classes").desc("Allowed classes").emptyDefaultValue().delim(',').build(); // The package of this source file private String thisPackage; // The restricted packages private List<String> restrictedPackages; public LoosePackageCouplingRule() { definePropertyDescriptor(PACKAGES_DESCRIPTOR); definePropertyDescriptor(CLASSES_DESCRIPTOR); } @Override public Object visit(ASTCompilationUnit node, Object data) { // Sort the restricted packages in reverse order. This will ensure the // child packages are in the list before their parent packages. this.restrictedPackages = new ArrayList<>(super.getProperty(PACKAGES_DESCRIPTOR)); restrictedPackages.sort(Collections.reverseOrder()); this.thisPackage = node.getPackageName(); node.children(ASTImportDeclaration.class).forEach(it -> it.acceptVisitor(this, data)); return data; } @Override public Object visit(ASTImportDeclaration node, Object data) { String importPackage = node.getPackageName(); // Check each restricted package for (String pkg : getRestrictedPackages()) { // Is this import restricted? Use the deepest sub-package which // restricts this import. if (isContainingPackage(pkg, importPackage)) { // Is this source in a sub-package of restricted package? if (pkg.equals(thisPackage) || isContainingPackage(pkg, thisPackage)) { // Valid usage break; } else { // On demand imports automatically fail because they include // everything if (node.isImportOnDemand()) { addViolation(data, node, new Object[] { node.getImportedName(), pkg }); break; } else { if (!isAllowedClass(node)) { addViolation(data, node, new Object[] { node.getImportedName(), pkg }); break; } } } } } return data; } protected List<String> getRestrictedPackages() { return restrictedPackages; } // Is 1st package a containing package of the 2nd package? protected boolean isContainingPackage(String pkg1, String pkg2) { return pkg1.equals(pkg2) || pkg1.length() < pkg2.length() && pkg2.startsWith(pkg1) && pkg2.charAt(pkg1.length()) == '.'; } protected boolean isAllowedClass(ASTImportDeclaration node) { String importedName = node.getImportedName(); for (String clazz : getProperty(CLASSES_DESCRIPTOR)) { if (importedName.equals(clazz)) { return true; } } return false; } public boolean checksNothing() { return getProperty(PACKAGES_DESCRIPTOR).isEmpty() && getProperty(CLASSES_DESCRIPTOR).isEmpty(); } /** * @see PropertySource#dysfunctionReason() */ @Override public String dysfunctionReason() { return checksNothing() ? "No packages or classes specified" : null; } }
5,051
35.875912
111
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/design/ExcessivePublicCountRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design; import static net.sourceforge.pmd.lang.java.ast.JModifier.FINAL; import static net.sourceforge.pmd.lang.java.ast.JModifier.PUBLIC; import static net.sourceforge.pmd.lang.java.ast.JModifier.STATIC; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.AccessNode; import net.sourceforge.pmd.lang.java.rule.internal.AbstractJavaCounterCheckRule; /** * Rule attempts to count all public methods and public attributes * defined in a class. * * <p>If a class has a high number of public operations, it might be wise * to consider whether it would be appropriate to divide it into * subclasses.</p> * * <p>A large proportion of public members and operations means the class * has high potential to be affected by external classes. Futhermore, * increased effort will be required to thoroughly test the class. * </p> * * @author aglover */ public class ExcessivePublicCountRule extends AbstractJavaCounterCheckRule<ASTAnyTypeDeclaration> { public ExcessivePublicCountRule() { super(ASTAnyTypeDeclaration.class); } @Override protected int defaultReportLevel() { return 45; } @Override protected boolean isViolation(ASTAnyTypeDeclaration node, int reportLevel) { long publicCount = node.getDeclarations() .filterIs(AccessNode.class) .filter(it -> it.hasModifiers(PUBLIC)) // filter out constants .filter(it -> !(it instanceof ASTFieldDeclaration && it.hasModifiers(STATIC, FINAL))) .count(); return publicCount >= reportLevel; } }
1,914
34.462963
116
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/JavaPropertyUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.internal; import static net.sourceforge.pmd.properties.PropertyFactory.stringListProperty; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * */ public final class JavaPropertyUtil { private JavaPropertyUtil() { // utility class } public static PropertyDescriptor<List<String>> ignoredAnnotationsDescriptor(Collection<String> defaults) { List<String> sortedDefaults = new ArrayList<>(defaults); sortedDefaults.sort(Comparator.naturalOrder()); return stringListProperty("ignoredAnnotations") .desc("Fully qualified names of the annotation types that should be ignored by this rule") .defaultValue(sortedDefaults) .build(); } public static PropertyDescriptor<List<String>> ignoredAnnotationsDescriptor(String... defaults) { return ignoredAnnotationsDescriptor(Arrays.asList(defaults)); } }
1,177
27.731707
110
java
pmd
pmd-master/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/JavaRuleUtil.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.internal; import static net.sourceforge.pmd.lang.java.types.JPrimitiveType.PrimitiveTypeKind.LONG; import static net.sourceforge.pmd.util.CollectionUtil.immutableSetOf; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectStreamField; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTArrayAccess; 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.ASTBodyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTConstructorCall; import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTInfixExpression; import net.sourceforge.pmd.lang.java.ast.ASTInitializer; import net.sourceforge.pmd.lang.java.ast.ASTMethodCall; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTNullLiteral; import net.sourceforge.pmd.lang.java.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.java.ast.ASTUnaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.ast.AccessNode; 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.JModifier; 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.symbols.JVariableSymbol; import net.sourceforge.pmd.lang.java.types.InvocationMatcher; import net.sourceforge.pmd.lang.java.types.InvocationMatcher.CompoundInvocationMatcher; import net.sourceforge.pmd.lang.java.types.TypeTestUtil; /** * Utilities shared between rules. */ public final class JavaRuleUtil { // this is a hacky way to do it, but let's see where this goes private static final CompoundInvocationMatcher KNOWN_PURE_METHODS = InvocationMatcher.parseAll( "_#toString()", "_#hashCode()", "_#equals(java.lang.Object)", "java.lang.String#_(_*)", // actually not all of them, probs only stream of some type // arg which doesn't implement Closeable... "java.util.stream.Stream#_(_*)", "java.util.Collection#size()", "java.util.List#get(int)", "java.util.Map#get(_)", "java.lang.Iterable#iterator()", "java.lang.Comparable#compareTo(_)" ); public static final Set<String> LOMBOK_ANNOTATIONS = immutableSetOf( "lombok.Data", "lombok.Getter", "lombok.Setter", "lombok.Value", "lombok.RequiredArgsConstructor", "lombok.AllArgsConstructor", "lombok.NoArgsConstructor", "lombok.Builder", "lombok.EqualsAndHashCode", "lombok.experimental.Delegate" ); private JavaRuleUtil() { // utility class } /** * Return true if the given expression is enclosed in a zero check. * The expression must evaluate to a natural number (ie >= 0), so that * {@code e < 1} actually means {@code e == 0}. * * @param e Expression */ public static boolean isZeroChecked(ASTExpression e) { JavaNode parent = e.getParent(); if (parent instanceof ASTInfixExpression) { BinaryOp op = ((ASTInfixExpression) parent).getOperator(); int checkLiteralAtIdx = 1 - e.getIndexInParent(); JavaNode comparand = parent.getChild(checkLiteralAtIdx); int expectedValue; if (op == BinaryOp.NE || op == BinaryOp.EQ) { // e == 0, e != 0, symmetric expectedValue = 0; } else if (op == BinaryOp.LT || op == BinaryOp.GE) { // e < 1 // 0 < e // e >= 1 (e != 0) // 1 >= e (e == 0 || e == 1) // 0 >= e (e == 0) // e >= 0 (true) expectedValue = checkLiteralAtIdx; } else if (op == BinaryOp.GT || op == BinaryOp.LE) { // 1 > e // e > 0 // 1 <= e (e != 0) // e <= 1 (e == 0 || e == 1) // e <= 0 (e == 0) // 0 <= e (true) expectedValue = 1 - checkLiteralAtIdx; } else { return false; } return JavaAstUtils.isLiteralInt(comparand, expectedValue); } return false; } /** * Returns true if the expression is a stringbuilder (or stringbuffer) * append call, or a constructor call for one of these classes. * * <p>If it is a constructor call, returns false if this is a call to * the constructor with a capacity parameter. */ public static boolean isStringBuilderCtorOrAppend(@Nullable ASTExpression e) { if (e instanceof ASTMethodCall) { ASTMethodCall call = (ASTMethodCall) e; if ("append".equals(call.getMethodName())) { ASTExpression qual = ((ASTMethodCall) e).getQualifier(); return qual != null && isStringBufferOrBuilder(qual); } } else if (e instanceof ASTConstructorCall) { return isStringBufferOrBuilder(((ASTConstructorCall) e).getTypeNode()); } return false; } private static boolean isStringBufferOrBuilder(TypeNode node) { return TypeTestUtil.isExactlyA(StringBuilder.class, node) || TypeTestUtil.isExactlyA(StringBuffer.class, node); } /** * Returns true if the node is a utility class, according to this * custom definition. */ public static boolean isUtilityClass(ASTAnyTypeDeclaration node) { if (!node.isRegularClass()) { return false; } ASTClassOrInterfaceDeclaration classNode = (ASTClassOrInterfaceDeclaration) node; // A class with a superclass or interfaces should not be considered if (classNode.getSuperClassTypeNode() != null || !classNode.getSuperInterfaceTypeNodes().isEmpty()) { return false; } // A class without declarations shouldn't be reported boolean hasAny = false; for (ASTBodyDeclaration declNode : classNode.getDeclarations()) { if (declNode instanceof ASTFieldDeclaration || declNode instanceof ASTMethodDeclaration) { hasAny = isNonPrivate(declNode) && !JavaAstUtils.isMainMethod(declNode); if (!((AccessNode) declNode).hasModifiers(JModifier.STATIC)) { return false; } } else if (declNode instanceof ASTInitializer) { if (!((ASTInitializer) declNode).isStatic()) { return false; } } } return hasAny; } private static boolean isNonPrivate(ASTBodyDeclaration decl) { return ((AccessNode) decl).getVisibility() != Visibility.V_PRIVATE; } /** * Whether the name may be ignored by unused rules like UnusedAssignment. */ public static boolean isExplicitUnusedVarName(String name) { return name.startsWith("ignored") || name.startsWith("unused") || "_".equals(name); // before java 9 it's ok } /** * Returns true if the string has the given word as a strict prefix. * There needs to be a camelcase word boundary after the prefix. * * <code> * startsWithCamelCaseWord("getter", "get") == false * startsWithCamelCaseWord("get", "get") == false * startsWithCamelCaseWord("getX", "get") == true * </code> * * @param camelCaseString A string * @param prefixWord A prefix */ public static boolean startsWithCamelCaseWord(String camelCaseString, String prefixWord) { return camelCaseString.startsWith(prefixWord) && camelCaseString.length() > prefixWord.length() && Character.isUpperCase(camelCaseString.charAt(prefixWord.length())); } /** * Returns true if the string has the given word as a word, not at the start. * There needs to be a camelcase word boundary after the prefix. * * <code> * containsCamelCaseWord("isABoolean", "Bool") == false * containsCamelCaseWord("isABoolean", "A") == true * containsCamelCaseWord("isABoolean", "is") == error (not capitalized) * </code> * * @param camelCaseString A string * @param capitalizedWord A word, non-empty, capitalized * * @throws AssertionError If the word is empty or not capitalized */ public static boolean containsCamelCaseWord(String camelCaseString, String capitalizedWord) { assert capitalizedWord.length() > 0 && Character.isUpperCase(capitalizedWord.charAt(0)) : "Not a capitalized string \"" + capitalizedWord + "\""; int index = camelCaseString.indexOf(capitalizedWord); if (index >= 0 && camelCaseString.length() > index + capitalizedWord.length()) { return Character.isUpperCase(camelCaseString.charAt(index + capitalizedWord.length())); } return index >= 0 && camelCaseString.length() == index + capitalizedWord.length(); } public static boolean isGetterOrSetterCall(ASTMethodCall call) { return isGetterCall(call) || isSetterCall(call); } private static boolean isSetterCall(ASTMethodCall call) { return call.getArguments().size() > 0 && startsWithCamelCaseWord(call.getMethodName(), "set"); } public static boolean isGetterCall(ASTMethodCall call) { return call.getArguments().size() == 0 && (startsWithCamelCaseWord(call.getMethodName(), "get") || startsWithCamelCaseWord(call.getMethodName(), "is")); } public static boolean isGetterOrSetter(ASTMethodDeclaration node) { return isGetter(node) || isSetter(node); } /** Attempts to determine if the method is a getter. */ private static boolean isGetter(ASTMethodDeclaration node) { if (node.getArity() != 0 || node.isVoid()) { return false; } ASTAnyTypeDeclaration enclosing = node.getEnclosingType(); if (startsWithCamelCaseWord(node.getName(), "get")) { return JavaAstUtils.hasField(enclosing, node.getName().substring(3)); } else if (startsWithCamelCaseWord(node.getName(), "is") && TypeTestUtil.isA(boolean.class, node.getResultTypeNode())) { return JavaAstUtils.hasField(enclosing, node.getName().substring(2)); } return JavaAstUtils.hasField(enclosing, node.getName()); } /** Attempts to determine if the method is a setter. */ private static boolean isSetter(ASTMethodDeclaration node) { if (node.getArity() != 1 || !node.isVoid()) { return false; } ASTAnyTypeDeclaration enclosing = node.getEnclosingType(); if (startsWithCamelCaseWord(node.getName(), "set")) { return JavaAstUtils.hasField(enclosing, node.getName().substring(3)); } return JavaAstUtils.hasField(enclosing, node.getName()); } // TODO at least UnusedPrivateMethod has some serialization-related logic. /** * Whether some variable declared by the given node is a serialPersistentFields * (serialization-specific field). */ public static boolean isSerialPersistentFields(final ASTFieldDeclaration field) { return field.hasModifiers(JModifier.FINAL, JModifier.STATIC, JModifier.PRIVATE) && field.getVarIds().any(it -> "serialPersistentFields".equals(it.getName()) && TypeTestUtil.isA(ObjectStreamField[].class, it)); } /** * Whether some variable declared by the given node is a serialVersionUID * (serialization-specific field). */ public static boolean isSerialVersionUID(ASTFieldDeclaration field) { return field.hasModifiers(JModifier.FINAL, JModifier.STATIC) && field.getVarIds().any(it -> "serialVersionUID".equals(it.getName()) && it.getTypeMirror().isPrimitive(LONG)); } /** * True if the method is a {@code readObject} method defined for serialization. */ public static boolean isSerializationReadObject(ASTMethodDeclaration node) { return node.getVisibility() == Visibility.V_PRIVATE && "readObject".equals(node.getName()) && JavaAstUtils.hasExceptionList(node, InvalidObjectException.class) && JavaAstUtils.hasParameters(node, ObjectInputStream.class); } /** * Whether the node or one of its descendants is an expression with * side effects. Conservatively, any method call is a potential side-effect, * as well as assignments to fields or array elements. We could relax * this assumption with (much) more data-flow logic, including a memory model. * * <p>By default assignments to locals are not counted as side-effects, * unless the lhs is in the given set of symbols. * * @param node A node * @param localVarsToTrack Local variables to track */ public static boolean hasSideEffect(@Nullable JavaNode node, Set<? extends JVariableSymbol> localVarsToTrack) { return node != null && node.descendantsOrSelf() .filterIs(ASTExpression.class) .any(e -> hasSideEffectNonRecursive(e, localVarsToTrack)); } /** * Returns true if the expression has side effects we don't track. * Does not recurse into sub-expressions. */ private static boolean hasSideEffectNonRecursive(ASTExpression e, Set<? extends JVariableSymbol> localVarsToTrack) { if (e instanceof ASTAssignmentExpression) { ASTAssignableExpr lhs = ((ASTAssignmentExpression) e).getLeftOperand(); return isNonLocalLhs(lhs) || JavaAstUtils.isReferenceToVar(lhs, localVarsToTrack); } else if (e instanceof ASTUnaryExpression) { ASTUnaryExpression unary = (ASTUnaryExpression) e; ASTExpression lhs = unary.getOperand(); return !unary.getOperator().isPure() && (isNonLocalLhs(lhs) || JavaAstUtils.isReferenceToVar(lhs, localVarsToTrack)); } // when there are throw statements, // then this side effect can never be observed in containing code, // because control flow jumps out of the method return e.ancestors(ASTThrowStatement.class).isEmpty() && (e instanceof ASTMethodCall && !isPure((ASTMethodCall) e) || e instanceof ASTConstructorCall); } private static boolean isNonLocalLhs(ASTExpression lhs) { return lhs instanceof ASTArrayAccess || !JavaAstUtils.isReferenceToLocal(lhs); } /** * Whether the invocation has no side-effects. Very conservative. */ private static boolean isPure(ASTMethodCall call) { return isGetterCall(call) || KNOWN_PURE_METHODS.anyMatch(call); } public static @Nullable ASTVariableDeclaratorId getReferencedNode(ASTNamedReferenceExpr expr) { JVariableSymbol referencedSym = expr.getReferencedSym(); return referencedSym == null ? null : referencedSym.tryGetNode(); } /** * Checks whether the given node is annotated with any lombok annotation. * The node should be annotateable. * * @param node * the Annotatable node to check * @return <code>true</code> if a lombok annotation has been found */ public static boolean hasLombokAnnotation(Annotatable node) { return LOMBOK_ANNOTATIONS.stream().anyMatch(node::isAnnotationPresent); } /** * Returns true if the expression is a null check on the given variable. */ public static boolean isNullCheck(ASTExpression expr, JVariableSymbol var) { return isNullCheck(expr, StablePathMatcher.matching(var)); } public static boolean isNullCheck(ASTExpression expr, StablePathMatcher matcher) { if (expr instanceof ASTInfixExpression) { ASTInfixExpression condition = (ASTInfixExpression) expr; if (condition.getOperator().hasSamePrecedenceAs(BinaryOp.EQ)) { ASTNullLiteral nullLit = condition.firstChild(ASTNullLiteral.class); if (nullLit != null) { return matcher.matches(JavaAstUtils.getOtherOperandIfInInfixExpr(nullLit)); } } } return false; } /** * Returns true if the expr is in a null check (its parent is a null check). */ public static boolean isNullChecked(ASTExpression expr) { if (expr.getParent() instanceof ASTInfixExpression) { ASTInfixExpression infx = (ASTInfixExpression) expr.getParent(); if (infx.getOperator().hasSamePrecedenceAs(BinaryOp.EQ)) { return JavaAstUtils.getOtherOperandIfInInfixExpr(expr) instanceof ASTNullLiteral; } } return false; } }
17,765
39.19457
141
java