auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isNestedNewResourceCreation(ExpressionTree expr) { if (expr.is(Tree.Kind.NEW_CLASS)) { Arguments arguments = ((NewClassTree) expr).arguments(); if (arguments.stream().noneMatch(UnclosedResourcesCheck::isCloseable)) { return true; } START return arguments.stream().filter(UnclosedResourcesCheck::isCloseable).allMatch(this::isNestedNewResourceCreation); END } return false; } all match returns true if the stream is empty so no need for the previous if.

Target:
private boolean isNestedNewResourceCreation(ExpressionTree expr) { if (expr.is(Tree.Kind.NEW_CLASS)) { return ((NewClassTree) expr).arguments().stream() .filter(UnclosedResourcesCheck::isCloseable) .allMatch(this::isNestedNewResourceCreation); } return false; }
Source:
private ExecutorService createExecutor() { int numThreads = Runtime.getRuntime().availableProcessors() + 1; return Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat("SonarJava-parallel-analysis-%d").build()); START } END ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Make "createExecutor" a "static" method. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2325)

Target:
private ExecutorService createExecutor() { // int numThreads = Runtime.getRuntime().availableProcessors() + 1; int numThreads = 2; return Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat("SonarJava-parallel-analysis-%d").build()); }
Source:
private static boolean hasOnlyNonNullConstraint(ConstraintsByDomain constraints) { List<Class<? extends Constraint>> domains = constraints.domains().collect(Collectors.toList()); START return domains.size() == 1 && constraints.get(ObjectConstraint.class) == ObjectConstraint.NOT_NULL; END } why not directly `constraints.domains().count() == 1` ?

Target:
private static boolean hasOnlyNonNullConstraint(ConstraintsByDomain constraints) { return constraints.domains().count() == 1 && constraints.get(ObjectConstraint.class) == ObjectConstraint.NOT_NULL; }
Source:
private boolean isConstraintFromObjectDomain(@Nullable Constraint constraint) { START return constraint != null && constraint.getClass().isAssignableFrom(ObjectConstraint.class); END } why not simply use `constraint instanceof ObjectConstraint` ? if null, it will return `false`.

Target:
private boolean isConstraintFromObjectDomain(@Nullable Constraint constraint) { return constraint instanceof ObjectConstraint; }
Source:
public MethodInvariantContext(MethodTree methodTree) { this.methodTree = methodTree; TypeTree returnType = methodTree.returnType(); this.returnStatementTrees = extractReturnStatements(methodTree); methodToCheck = !isConstructorOrVoid(returnType) && returnStatementTrees.size() > 1; START returnImmutableType = methodToCheck && (returnType.symbolType().isPrimitive() || returnType.symbolType().is("java.lang.String")); END } no need for `this.`

Target:
MethodInvariantContext(MethodTree methodTree) { this.methodTree = methodTree; TypeTree returnType = methodTree.returnType(); this.returnStatementTrees = extractReturnStatements(methodTree); methodToCheck = !isConstructorOrVoid(methodTree, returnType) && returnStatementTrees.size() > 1; returnImmutableType = methodToCheck && (returnType.symbolType().isPrimitive() || returnType.symbolType().is("java.lang.String")); }
Source:
public int hashCode() { if (hashCode == 0) { START hashCode = Objects.hash(values, constraints, peekValue(), lastAssociatedSymbol); END } return hashCode; } Same remarks as for equals. I doubt about the interest of having the last associated symbols taken into account here. LastEvaluated symbol was not part of it.

Target:
public int hashCode() { if (hashCode == 0) { hashCode = Objects.hash(values, constraints, peekValue()); } return hashCode; }
Source:
void fun() { Object test = new Object[]{"1"}; START String[] test2 = new Object[]{"1"}; END Object[] test3 = new String[]{"1"}; System.out.println(((Object[])test)[0]); // compliant : target type is array access System.out.println(((Object[])test2)[0]); // Noncompliant System.out.println(((String[])test3)[0]); // compliant } Does not compile, but not really important.

Target:
void fun() { Object test = new Object[]{"1"}; String[] test2 = new String[]{"1"}; Object[] test3 = new String[]{"1"}; System.out.println(((Object[])test)[0]); // compliant : target type is array access System.out.println(((Object[])test2)[0]); // Noncompliant System.out.println(((String[])test3)[0]); // compliant }
Source:
private Edge(Node child, Node parent) { START Preconditions.checkState(!Objects.equals(child, parent)); END this.child = child; this.parent = parent; hashcode = Objects.hash(child, parent); } Maybe worth removing the call to `Objects.equals()` here too, as both child and parent can not be null.

Target:
private Edge(Node child, Node parent) { Preconditions.checkState(!child.equals(parent)); this.child = child; this.parent = parent; hashcode = Objects.hash(child, parent); }
Source:
private static boolean hasProperEquals(MethodTree methodTree) { START Symbol.MethodSymbol symbol = methodTree.symbol(); END if (symbol == null) { return true; } Symbol.TypeSymbol enclosingClass = symbol.enclosingClass(); if (enclosingClass == null) { return true; } return enclosingClass.memberSymbols().stream().anyMatch(MethodNamedEqualsCheck::isEqualsMethod); } This can only happen if semantic is not present (symbol method is not annotated as returning null). As such you should test if semantic is present and not raise an issue if it is not the case.

Target:
private static boolean hasProperEquals(MethodTree methodTree) { Symbol.MethodSymbol symbol = methodTree.symbol(); Symbol.TypeSymbol enclosingClass = symbol.enclosingClass(); return enclosingClass != null && enclosingClass.memberSymbols().stream().anyMatch(MethodNamedEqualsCheck::isEqualsMethod); }
Source:
private static boolean invalidMethodAndVariable(Symbol currentMember, Symbol knownMember) { Symbol methodSymbol = currentMember.isMethodSymbol() ? currentMember : knownMember; Symbol variableSymbol = methodSymbol == currentMember ? knownMember : currentMember; START return sameVisibilityNotPrivate(currentMember, knownMember) END && !methodReturningVariableWithSameName(methodSymbol, variableSymbol) && !isBuilderPattern(methodSymbol, variableSymbol); } I would first start the method by ``` if(!sameVisibilityNotPrivate(currentMember, knownMember)) { return false; } ``` as this operation does not requires knowing which one is the method or the variable.

Target:
private static boolean invalidMethodAndVariable(Symbol currentMember, Symbol knownMember) { if (!sameVisibilityNotPrivate(currentMember, knownMember)) { return false; } Symbol methodSymbol = currentMember.isMethodSymbol() ? currentMember : knownMember; Symbol variableSymbol = methodSymbol == currentMember ? knownMember : currentMember; return !methodReturningVariableWithSameName(methodSymbol, variableSymbol) && !isBuilderPattern(methodSymbol, variableSymbol); }
Source:
START public Set<String> done(){ END ParametrizedTypeJavaType.typeSubstitutionSolver = null; bytecodeCompleter.done(); return bytecodeCompleter.classesNotFound(); } I really don't like this returned value. I would prefer to have a dedicated object containing errors related to the semantic model, even if (at first? for the time being?) it only contains the classes not found.

Target:
public void done(){ ParametrizedTypeJavaType.typeSubstitutionSolver = null; bytecodeCompleter.done(); }
Source:
public boolean accept(FilterableIssue issue) { if (filterAnyRule) { return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(ANY_RULE_KEY).contains(issue.line())); START } END return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(issue.ruleKey().rule()).contains(issue.line())); } This should be rewritten to just change the key depending of filterAnyRule.

Target:
public boolean accept(FilterableIssue issue) { return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(issue.ruleKey().rule()).contains(issue.line())); }
Source:
private static boolean isClassController(Symbol.MethodSymbol methodSymbol) { SymbolMetadata parentClassOwner = methodSymbol.owner().metadata(); START return parentClassOwner.isAnnotatedWith("org.springframework.stereotype.Controller"); END } you can inline the `parentClassOwner`(Metadata) variable

Target:
private static boolean isClassController(Symbol.MethodSymbol methodSymbol) { return methodSymbol.owner().metadata().isAnnotatedWith("org.springframework.stereotype.Controller"); }
Source:
private static boolean isNullLiteral(ExpressionTree lastArgument) { ExpressionTree arg = ExpressionUtils.skipParentheses(lastArgument); return arg.is(Tree.Kind.NULL_LITERAL) START || (arg.is(Tree.Kind.TYPE_CAST) && ((TypeCastTree) arg).expression().is(Tree.Kind.NULL_LITERAL)); END } wonder if smart or over cautious but the last operand could be replaced by `isNullLiteral((TypeCastTree) arg).expression())` And this should be tested with something like : `IOUtils.write(s, output, ((String) (null)));`

Target:
private static boolean isNullLiteral(ExpressionTree lastArgument) { ExpressionTree arg = ExpressionUtils.skipParentheses(lastArgument); return arg.is(Tree.Kind.NULL_LITERAL) || (arg.is(Tree.Kind.TYPE_CAST) && isNullLiteral(((TypeCastTree) arg).expression())); }
Source:
public String toString() { START return String.valueOf(leftOp) + kind.operand + rightOp; END } why not call the toString directly ? and I was a bit confused by the fact that you rely on the + operator of strings which will make implicit toString calls.

Target:
public String toString() { return leftOp.toString() + kind.operand + rightOp.toString(); }
Source:
void f() { if (this == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } START if (super == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} END } } I'm pretty sure `super` can not be used as simple identifier, see [JLS-11.11.2](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.11.2). It does not impacts the fix itself, but this code does not compile and it's bothering me a bit.

Target:
void f() { if (this == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } super.toString(); // Compliant, as super is never null }
Source:
START public static Stream<Constraint> pmapToStream(@Nullable PMap<Class<? extends Constraint>, Constraint> pmap) { END if(pmap == null) { return Stream.empty(); } Stream.Builder<Constraint> result = Stream.builder(); pmap.forEach((d, c) -> result.add(c)); return result.build(); } This one should also probably not have an extended visibility but rather be reimplemented.

Target:
static Stream<Constraint> pmapToStream(@Nullable PMap<Class<? extends Constraint>, Constraint> pmap) { if(pmap == null) { return Stream.empty(); } Stream.Builder<Constraint> result = Stream.builder(); pmap.forEach((d, c) -> result.add(c)); return result.build(); }
Source:
START ExecutionPath(@Nullable ExplodedGraph.Edge edge, PSet<ExplodedGraph.Edge> visited, @Nullable Symbol trackSymbol, List<JavaFileScannerContext.Location> flow, boolean finished) { END this.trackSymbol = trackSymbol; this.lastEdge = edge; this.visited = visited; this.flow = flow; this.finished = finished; } I would set it private as this class ought to be externalized at one point.

Target:
private ExecutionPath(@Nullable ExplodedGraph.Edge edge, PSet<ExplodedGraph.Edge> visited, @Nullable Symbol trackSymbol, List<JavaFileScannerContext.Location> flow, boolean finished) { this.trackSymbol = trackSymbol; this.lastEdge = edge; this.visited = visited; this.flow = flow; this.finished = finished; }
Source:
public LearnedConstraint(SymbolicValue sv, @Nullable Constraint constraint) { START Objects.requireNonNull(sv); END this.sv = sv; this.constraint = constraint; } unrelated to this commit.

Target:
public LearnedConstraint(SymbolicValue sv, @Nullable Constraint constraint) { this.sv = sv; this.constraint = constraint; }
Source:
START public Type getClassType(String fullyQualifiedName) { END return bytecodeCompleter.loadClass(fullyQualifiedName).type; } I did not spot the unit test of that one. Especially to check how this one reacts with edgecases. (null or empty string, non existing class, etc.)

Target:
public Type getClassType(String fullyQualifiedName) { return bytecodeCompleter.loadClass(fullyQualifiedName).type(); }
Source:
private static boolean isWithinTryHeader(Tree syntaxNode) { Tree parent = syntaxNode; START while ((parent = parent.parent()) != null) { END if (parent.is(Tree.Kind.VARIABLE)) { break; } } if (parent != null && parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; } Please don't do assignement and comparison within the same expression. You can also avoid the break by testing nullness and kind in while condition and doing the assignement in the body of the while.

Target:
private static boolean isWithinTryHeader(Tree syntaxNode) { Tree parent = syntaxNode; while (parent != null && !parent.is(Tree.Kind.VARIABLE) ) { parent = parent.parent(); } if (parent != null && parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }
Source:
START private void enqueueThrownExceptionalPaths(Symbol symbol) { END if (symbol.isMethodSymbol()) { ProgramState ps = programState.clearStack(); ((Symbol.MethodSymbol) symbol).thrownTypes().stream() .map(constraintManager::createExceptionalSymbolicValue) .forEach(exceptionSV -> enqueueExceptionalPaths(ps, exceptionSV)); } } I think this one could rely on MethodInvocationTree : that would allow to not declare methodSymbol local variable.

Target:
private void enqueueThrownExceptionalPaths(Symbol symbol) { if (!symbol.isMethodSymbol()) { // do nothing for unknown methods return; } ProgramState ps = programState.clearStack(); ((Symbol.MethodSymbol) symbol).thrownTypes().stream() .map(constraintManager::createExceptionalSymbolicValue) .forEach(exceptionSV -> enqueueExceptionalPaths(ps, exceptionSV)); }
Source:
public void while_statement() { Lock lock = new ReentrantLock(); while (foo) { lock.tryLock(); } lock.unlock(); START while (Random.nextBoolean()) { END lock.tryLock(); // Noncompliant lock = new ReentrantLock(); } lock.unlock(); } I don't get why you had to change this test case. The behavior of how we are handling fields should not have changed with your changes. Moreover, class `Random` is not imported, so it's an unknown method call, which changes the meaning of the test.

Target:
public void while_statement() { Lock lock = new ReentrantLock(); while (foo) { lock.tryLock(); } lock.unlock(); while (foo) { lock.tryLock(); // Noncompliant lock = new ReentrantLock(); } lock.unlock(); }
Source:
START private boolean isWithinTryHeader(Tree syntaxNode) { END final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; } And when `isTryStatementResource` is static, this one can be static as well.

Target:
private static boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }
Source:
START private boolean isTryStatementResource(VariableTree variable) { END final TryStatementTree tryStatement = getEnclosingTryStatement(variable); return tryStatement != null && tryStatement.resources().contains(variable); } This one can be static.

Target:
private static boolean isTryStatementResource(VariableTree variable) { final TryStatementTree tryStatement = getEnclosingTryStatement(variable); return tryStatement != null && tryStatement.resources().contains(variable); }
Source:
private Map<String, Object> loadYamlConfig(String configFile) { START Path configPath = Paths.get(configFile); END if (!resources.exists(configPath)) { return emptyMap(); } try { return YamlParser.INSTANCE.parseMap(resources.sourceFile(configPath)); } catch (IOException e) { throw new IllegalStateException("Unable to read " + configFile, e); } } You don't need to fill the body of that method, you just need it to use it as lambda.

Target:
private Map<String, Object> loadYamlConfig(String configFile) { return emptyMap(); }
Source:
START void activateDeferredProfile() throws ProfileDataException{ END } Replace the exception by `Exception`, so your test is self contained.

Target:
void activateDeferredProfile() throws Exception{ }
Source:
static MethodMatcher levelTestMatcher(String typeDefinition, String level) { return MethodMatcher.create() .typeDefinition(typeDefinition) START .name(String.format("is%c%sEnabled", level.charAt(0), level.toLowerCase(Locale.ROOT).substring(2))) END .withoutParameter(); } Are you sure about `.substring(2)` ? With `INFO`, I'll get `isIfoEnabled`...

Target:
private static MethodMatcher levelTestMatcher(String typeDefinition, String level) { return MethodMatcher.create() .typeDefinition(typeDefinition) .name(String.format("is%c%sEnabled", level.charAt(0), level.toLowerCase(Locale.ROOT).substring(1))) .withoutParameter(); }
Source:
public void leaveNode(Tree tree) { if (!hasSemantic()) { return; } START if (tree.is(METHOD) || tree.is(CONSTRUCTOR)) { END synchronizedStack.pop(); } } no need for the ||

Target:
public void leaveNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(METHOD, CONSTRUCTOR)) { synchronizedStack.pop(); } }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } START if (tree.is(SYNCHRONIZED_STATEMENT)) { END SynchronizedStatementTree synchronizedTree = (SynchronizedStatementTree) tree; if (synchronizedTree.expression().is(METHOD_INVOCATION)) { MethodInvocationTree synchronizedExpr = (MethodInvocationTree) synchronizedTree.expression(); if (GET_CLASS_MATCHER.matches(synchronizedExpr) && !isEnclosingClassFinal(synchronizedExpr.methodSelect())) { reportIssue(synchronizedExpr, "Synchronize on the static class name instead."); } } } } no need for that if.

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } SynchronizedStatementTree synchronizedTree = (SynchronizedStatementTree) tree; if (synchronizedTree.expression().is(METHOD_INVOCATION)) { MethodInvocationTree synchronizedExpr = (MethodInvocationTree) synchronizedTree.expression(); if (GET_CLASS_MATCHER.matches(synchronizedExpr) && !isEnclosingClassFinal(synchronizedExpr.methodSelect())) { reportIssue(synchronizedExpr, "Synchronize on the static class name instead."); } } }
Source:
private static boolean isEnclosingClassFinal(ExpressionTree expressionTree) { //if it's identifier we go up the tree to get the method and check if owner of the method is final if (expressionTree.is(IDENTIFIER)) { Tree parent = expressionTree.parent(); while (!parent.is(METHOD)) { parent = parent.parent(); } return ((MethodTree) parent).symbol().owner().isFinal(); START } else { END //if it's member select, we check the type of the member select expression return ((MemberSelectExpressionTree) expressionTree).expression().symbolType().symbol().isFinal(); } } I would remove the else given that you return at the end of the if.

Target:
private static boolean isEnclosingClassFinal(ExpressionTree expressionTree) { if (expressionTree.is(IDENTIFIER)) { Tree parent = expressionTree.parent(); while (!parent.is(METHOD)) { parent = parent.parent(); } return ((MethodTree) parent).symbol().owner().isFinal(); } return ((MemberSelectExpressionTree) expressionTree).expression().symbolType().symbol().isFinal(); }
Source:
public void visitMethod(MethodTree tree) { START if (tree == writeObjectMethodTree || moreThanSingleLock) { END return; } if (hasModifier(tree.modifiers(), SYNCHRONIZED)) { moreThanSingleLock = true; } super.visitMethod(tree); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Change this comparison to use the equals method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/sonarqube/coding_rules#rule_key=squid%3AS1698)

Target:
public void visitMethod(MethodTree tree) { if (tree == writeObjectMethodTree || moreThanSingleLock) { return; } if (hasModifier(tree.modifiers(), SYNCHRONIZED)) { moreThanSingleLock = true; return; } super.visitMethod(tree); }
Source:
START void setThreshold(int threshold) { END this.threshold = threshold; } It is not visible for testing actually : it is visible so the value can be set by instantiators of the Check class (ie the platform) and so should be public and without the annotation.

Target:
public void setThreshold(int threshold) { this.threshold = threshold; }
Source:
private static boolean nullAgainstParam(ExpressionTree o1, ExpressionTree o2, LambdaExpressionTree tree) { START if (o1.is(Tree.Kind.NULL_LITERAL) && (o2.is(Tree.Kind.IDENTIFIER))) { END List<VariableTree> parameters = tree.parameters(); return parameters.size() == 1 && parameters.get(0).symbol().equals(((IdentifierTree) o2).symbol()); } return false; } what about : ``` (f) == null ```

Target:
private static boolean nullAgainstParam(ExpressionTree o1, ExpressionTree o2, LambdaExpressionTree tree) { if (o1.is(Tree.Kind.NULL_LITERAL) && o2.is(Tree.Kind.IDENTIFIER)) { List<VariableTree> parameters = tree.parameters(); return parameters.size() == 1 && parameters.get(0).symbol().equals(((IdentifierTree) o2).symbol()); } return false; }
Source:
private static Set<Type> primitiveWrappers(Set<Type> types) { START if (!types.stream().allMatch(Type::isPrimitive)) { END return types.stream().map(t -> !t.isPrimitive() ? t : ((JavaType) t).primitiveWrapperType()).collect(Collectors.toCollection(LinkedHashSet::new)); } return types; } I would just not negate the condition.

Target:
private static Set<Type> primitiveWrappers(Set<Type> types) { if (types.stream().allMatch(Type::isPrimitive)) { return types; } return types.stream().map(t -> !t.isPrimitive() ? t : ((JavaType) t).primitiveWrapperType()).collect(Collectors.toCollection(LinkedHashSet::new)); }
Source:
START private boolean isSerializable(Type type) { END if (type.isPrimitive()) { return true; } if (isSerializableArray(type)) { return true; } if (isParametrized(type)) { return isSerializableParametrized((ParametrizedTypeJavaType) type); } return type.isSubtypeOf("java.io.Serializable"); } This method can be static, as all the methods it calls.

Target:
private static boolean isSerializable(Type type) { if (type.isPrimitive()) { return true; } if (isSerializableArray(type)) { return true; } if (isParametrized(type)) { return isSerializableParametrized((ParametrizedTypeJavaType) type); } return type.isSubtypeOf("java.io.Serializable"); }
Source:
private static boolean isZeroDimension(ArrayDimensionTree dim) { ExpressionTree expression = dim.expression(); START return expression == null || (expression.is(Tree.Kind.INT_LITERAL) && "0".equals(((LiteralTree) expression).value())); END } The method name doesn't match this behavior. If `expression == null` that doesn't mean that the dimension of the array is zero. It means that there has to be an initializer that defines the size.

Target:
private static boolean isZeroDimension(ArrayDimensionTree dim) { ExpressionTree expression = dim.expression(); return expression != null && expression.is(Tree.Kind.INT_LITERAL) && "0".equals(((LiteralTree) expression).value()); }
Source:
private void handleConstructor(NewClassTree tree) { START if (PASSWORD_AUTHENTICATION_CONSTRUCTOR.matches(tree)) { END ExpressionTree secondArg = tree.arguments().get(1); if (secondArg.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) secondArg; if (isCallOnStringLiteral(mit.methodSelect()) && STRING_TO_CHAR_ARRAY.matches(mit)) { reportIssue(secondArg); } } } } It's a matter of style, but I would reverse the conditions to not nest 3 `if` statements.

Target:
private void handleConstructor(NewClassTree tree) { if (!PASSWORD_AUTHENTICATION_CONSTRUCTOR.matches(tree)) { return; } ExpressionTree secondArg = tree.arguments().get(1); if (secondArg.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) secondArg; if (isCallOnStringLiteral(mit.methodSelect()) && STRING_TO_CHAR_ARRAY.matches(mit)) { reportIssue(secondArg); } } }
Source:
public DeferredStatusHolderSV(int id, Status deferredStatus) { super(id); START this.deferedStatus = deferredStatus; END } typo. Should have two r.

Target:
public DeferredStatusHolderSV(int id, Status deferredStatus) { super(id); this.deferredStatus = deferredStatus; }
Source:
protected static boolean isSerializableAndValueBased(Type type) { // we check first the ParametrizedTypeJavaType, in order to filter out the non-serializable // generic value-based class Optional<T> JavaType javaType = (JavaType)type; if (javaType.isParameterized()) { ParametrizedTypeJavaType parameterizedType = (ParametrizedTypeJavaType)javaType; return isSubtypeOfCollectionApi(parameterizedType) && parameterizedType.typeParameters().stream() .anyMatch(t -> isSerializableAndValueBased(parameterizedType.substitution(t))); START } else { END return ValueBasedUtils.isValueBased(javaType); } } No need for the else here.

Target:
private static boolean isSerializableAndValueBased(Type type) { // we check first the ParametrizedTypeJavaType, in order to filter out the non-serializable // generic value-based class Optional<T> JavaType javaType = (JavaType) type; if (javaType.isParameterized()) { ParametrizedTypeJavaType parameterizedType = (ParametrizedTypeJavaType) javaType; return isSubtypeOfCollectionApi(parameterizedType) && parameterizedType.typeParameters().stream() .anyMatch(t -> isSerializableAndValueBased(parameterizedType.substitution(t))); } return ValueBasedUtils.isValueBased(javaType); }
Source:
private static boolean isInJavaTimePackage(String className) { START if (className.contains(".")) { END return "java.time".equals(className.substring(0, className.lastIndexOf('.'))); } else { return false; } } This whole if can be a single return statement

Target:
private static boolean isInJavaTimePackage(String className) { return className.startsWith("java.time"); }
Source:
public void visitNode(Tree tree) { TypeSymbol classSymbol = ((ClassTree) tree).symbol(); START Set<Symbol> fieldsReadOnAnotherInstance = FieldsReadOnAnotherInstanceVisitor.getFrom(classSymbol); END classSymbol.memberSymbols().stream() .filter(PrivateFieldUsedLocallyCheck::isPrivateField) .filter(s -> !s.usages().isEmpty()) .filter(s -> !fieldsReadOnAnotherInstance.contains(s)) .forEach(s -> checkPrivateField(s, classSymbol)); } The getFrom method should take the classTree not the symbol.

Target:
public void visitNode(Tree tree) { TypeSymbol classSymbol = ((ClassTree) tree).symbol(); Set<Symbol> fieldsReadOnAnotherInstance = FieldsReadOnAnotherInstanceVisitor.getFrom(tree); classSymbol.memberSymbols().stream() .filter(PrivateFieldUsedLocallyCheck::isPrivateField) .filter(s -> !s.usages().isEmpty()) .filter(s -> !fieldsReadOnAnotherInstance.contains(s)) .forEach(s -> checkPrivateField(s, classSymbol)); }
Source:
public void visitBinaryExpression(BinaryExpressionTree binaryExpression) { String message = "Remove this null-check of an \"Optional\"."; if (binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO)) { ExpressionTree left = binaryExpression.leftOperand(); ExpressionTree right = binaryExpression.rightOperand(); if ((isOptional(left) && isNull(right)) || (isNull(left) && isOptional(right))) { START context.reportIssue(this, binaryExpression, message); END } } super.visitBinaryExpression(binaryExpression); } you can put directly the message into the call to `reportIssue`, no need to use a dedicated variable.

Target:
public void visitBinaryExpression(BinaryExpressionTree binaryExpression) { // check that an @Optional is not compared to "null" if (binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO)) { ExpressionTree left = binaryExpression.leftOperand(); ExpressionTree right = binaryExpression.rightOperand(); if ((isOptional(left) && isNull(right)) || (isNull(left) && isOptional(right))) { context.reportIssue(this, binaryExpression, "Remove this null-check of an \"Optional\"."); } } super.visitBinaryExpression(binaryExpression); }
Source:
public void visitReturnStatement(ReturnStatementTree returnStatement) { ExpressionTree expression = returnStatement.expression(); if (!checkNull(expression) && expression.is(Kind.CONDITIONAL_EXPRESSION)) { START ConditionalExpressionTree conditionalExpression = (ConditionalExpressionTree)expression; END checkNull(conditionalExpression.trueExpression()); checkNull(conditionalExpression.falseExpression()); } } You should extract this part into the `visitConditionalExpression` method, and start the method by checking if the type of the expression is `Optional`.

Target:
public void visitReturnStatement(ReturnStatementTree returnStatement) { checkNull(returnStatement.expression()); super.visitReturnStatement(returnStatement); }
Source:
public ProgramState addConstraint(SymbolicValue symbolicValue, Constraint constraint) { PMap<SymbolicValue, Constraint> newConstraints = constraints.put(symbolicValue, constraint); START if (newConstraints != constraints && !isSymbolicValueOfVolatileField(symbolicValue)) { END return new ProgramState(this, newConstraints); } return this; } Wondering if it wouldn't not be better to test for "volatileness" of SV prior to adding the constraints.

Target:
public ProgramState addConstraint(SymbolicValue symbolicValue, Constraint constraint) { PMap<SymbolicValue, Constraint> newConstraints = constraints.put(symbolicValue, constraint); if (newConstraints != constraints) { return new ProgramState(this, newConstraints); } return this; }
Source:
public void testSensorDefinition() { START org.fest.assertions.Assertions.assertThat(sensor.toString()).isEqualTo("JaCoCoOverallSensor"); END } `assertThat` is already part of the `static import`. No need to use the fully qualified name (line 40).

Target:
public void testSensorDefinition() { assertThat(sensor.toString()).isEqualTo("JaCoCoOverallSensor"); }
Source:
START ClassJavaType(int tag, JavaSymbol.TypeJavaSymbol symbol) { END super(tag, symbol); } should be protected

Target:
protected ClassJavaType(int tag, JavaSymbol.TypeJavaSymbol symbol) { super(tag, symbol); }
Source:
private static boolean superTypesHaveOnlyStaticMethods(Symbol.TypeSymbol newClassTypeSymbol) { Type superClass = newClassTypeSymbol.superClass(); if (superClass != null && !superClass.is("java.lang.Object")) { START if (!hasOnlyStaticMethodsAndFields(superClass.symbol())) { END return false; } } for (Type superInterface : newClassTypeSymbol.interfaces()) { if (!hasOnlyStaticMethodsAndFields(superInterface.symbol())) { return false; } } return true; } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Merge this if statement with the enclosing one. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/sonarqube/coding_rules#rule_key=squid%3AS1066)

Target:
private static boolean superTypesHaveOnlyStaticMethods(Symbol.TypeSymbol newClassTypeSymbol) { Type superClass = newClassTypeSymbol.superClass(); if (superClass != null && !superClass.is("java.lang.Object") && !hasOnlyStaticMethodsAndFields(superClass.symbol())) { return false; } for (Type superInterface : newClassTypeSymbol.interfaces()) { if (!hasOnlyStaticMethodsAndFields(superInterface.symbol())) { return false; } } return true; }
Source:
START private boolean applicableWithUncheckedConversion(JavaSymbol.MethodJavaSymbol candidate, JavaType callSite, List<JavaType> typeParams) { END return !candidate.isStatic() && isRawTypeOfParametrizedType(callSite) && typeParams.isEmpty(); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "applicableWithUncheckedConversion" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/sonarqube/coding_rules#rule_key=squid%3AS2325)

Target:
private static boolean applicableWithUncheckedConversion(JavaSymbol.MethodJavaSymbol candidate, JavaType callSite, List<JavaType> typeParams) { return !candidate.isStatic() && isRawTypeOfParametrizedType(callSite) && typeParams.isEmpty(); }
Source:
public CodeVisitor[] checkClasses() { List<CodeVisitor> visitors = Lists.newArrayList(); // add issue filters BEFORE all the other checks START for (JavaIssueFilter issueFilter : issueFilters) { END visitors.add(issueFilter); } for (Checks<JavaCheck> checksElement : checks) { Collection<JavaCheck> checksCollection = checksElement.all(); if (!checksCollection.isEmpty()) { visitors.addAll(checksCollection); } } return visitors.toArray(new CodeVisitor[visitors.size()]); } addAll ?

Target:
public CodeVisitor[] checkClasses() { List<CodeVisitor> visitors = Lists.newArrayList(); for (Checks<JavaCheck> checksElement : checks) { Collection<JavaCheck> checksCollection = checksElement.all(); if (!checksCollection.isEmpty()) { visitors.addAll(checksCollection); } } return visitors.toArray(new CodeVisitor[visitors.size()]); }
Source:
private static boolean differentContract(JavaSymbol.MethodJavaSymbol method, JavaSymbol.MethodJavaSymbol overridee) { START return removingParametrizedAspect(method, overridee) END || differentReturnType(method, overridee) || differentParameters(method, overridee) || differentAnnotations(method, overridee) || differentThrows(method, overridee); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Reduce the number of conditional operators (4) used in the expression (maximum allowed 3). [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/coding_rules#rule_key=squid%3AS1067)

Target:
private static boolean differentContract(JavaSymbol.MethodJavaSymbol method, JavaSymbol.MethodJavaSymbol overridee) { return removingParametrizedAspect(method, overridee) || differentThrows(method, overridee) || differentReturnType(method, overridee) || differentParameters(method, overridee) || differentAnnotations(method.metadata(), overridee.metadata()); }
Source:
START public @Nonnull String colorMix() { END return null; // Noncompliant {{This method's return value is marked "javax.annotation.Nonnull" but null is returned.}} } Usually we place the annotation related to the return type of the method before the modifiers. See for instance: https://github.com/SonarSource/sonar-java/blob/master/java-frontend/src/main/java/org/sonar/java/se/ProgramState.java#L327

Target:
public String colorMix() { return null; // Noncompliant {{This method's return value is marked "javax.annotation.Nonnull" but null is returned.}} }
Source:
START private boolean isSAM(ClassTree classBody) { END if(hasOnlyOneMethod(classBody.members()) && classBody.symbol().isTypeSymbol()) { // Verify class body is a subtype of an interface JavaSymbol.TypeJavaSymbol symbol = (JavaSymbol.TypeJavaSymbol) classBody.symbol(); return symbol.getInterfaces().size() == 1 && symbol.getSuperclass().is("java.lang.Object"); } return false; } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "isSAM" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/coding_rules#rule_key=squid%3AS2325)

Target:
private static boolean isSAM(ClassTree classBody) { if(hasOnlyOneMethod(classBody.members()) && classBody.symbol().isTypeSymbol()) { // Verify class body is a subtype of an interface JavaSymbol.TypeJavaSymbol symbol = (JavaSymbol.TypeJavaSymbol) classBody.symbol(); return symbol.getInterfaces().size() == 1 && symbol.getSuperclass().is("java.lang.Object"); } return false; }
Source:
START private boolean isExcluded(VariableTree variable) { END return isStaticOrFinal(variable) || variable.symbol().metadata().isAnnotatedWith("javax.inject.Inject"); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "isExcluded" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/coding_rules#rule_key=squid%3AS2325)

Target:
private static boolean isExcluded(VariableTree variable) { return isStaticOrFinal(variable) || variable.symbol().metadata().isAnnotatedWith("javax.inject.Inject"); }
Source:
public void visitIdentifier(IdentifierTree tree) { super.visitIdentifier(tree); if ("class".equals(tree.name()) || methodReferences.isEmpty()) { return; } Symbol symbol = tree.symbol(); START final MethodReference currentMethod = methodReferences.peek(); END if (symbol.isUnknown()) { currentMethod.setNonStaticReference(); return; } for (MethodReference methodReference : methodReferences) { methodReference.checkSymbol(symbol); } } remove `final` modifier.

Target:
public void visitIdentifier(IdentifierTree tree) { super.visitIdentifier(tree); if ("class".equals(tree.name()) || methodReferences.isEmpty()) { return; } Symbol symbol = tree.symbol(); MethodReference currentMethod = methodReferences.peek(); if (symbol.isUnknown()) { currentMethod.setNonStaticReference(); return; } for (MethodReference methodReference : methodReferences) { methodReference.checkSymbol(symbol); } }
Source:
START protected BinaryRelation combineUnordered(BinaryRelation relation) { END BinaryRelation combined = null; if (rightOp.equals(relation.leftOp)) { combined = relation.combineOrdered(this); } else if (rightOp.equals(relation.rightOp)) { combined = relation.symmetric().combineOrdered(this); } return combined; } add `@VisibleForTest` and remove the `protected` modifier.

Target:
BinaryRelation combineUnordered(BinaryRelation relation) { BinaryRelation combined = null; if (rightOp.equals(relation.leftOp)) { combined = relation.combineOrdered(this); } else if (rightOp.equals(relation.rightOp)) { combined = relation.symmetric().combineOrdered(this); } return combined; }
Source:
private static String skipFirstProperty(String text) { START String newText = text.substring(text.indexOf(POM_PROPERTY_PREFIX)); END return newText.substring(newText.indexOf(POM_PROPERTY_SUFFIX)); } no need to do two substring, you should search for index of suffix starting at index of prefix

Target:
private static String skipFirstProperty(String text) { return text.substring(text.indexOf(POM_PROPERTY_SUFFIX, text.indexOf(POM_PROPERTY_PREFIX))); }
Source:
public boolean isAnnotatedOverride() { for (AnnotationTree annotationTree : modifiers.annotations()) { if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER) && isOverride((IdentifierTree) annotationTree.annotationType())) { return true; START } else if (annotationTree.annotationType().is(Kind.MEMBER_SELECT) && isJavaLangOverride((MemberSelectExpressionTree) annotationTree.annotationType())) { END return true; } } return false; } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) This branch's code block is the same as the block for the branch on line 293. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/coding_rules#rule_key=squid%3AS1871)

Target:
public boolean isAnnotatedOverride() { for (AnnotationTree annotationTree : modifiers.annotations()) { if (isJavaLangOverride(annotationTree.annotationType())) { return true; } } return false; }
Source:
public void visitNode(Tree tree) { if (tree.is(Kind.METHOD) && isServletInit((MethodTree) tree)) { tree.accept(new AssignmentVisitor()); } else if (tree.is(Kind.VARIABLE)) { VariableTree variable = (VariableTree) tree; START if (hasSemantic() && isOwnedByAServlet(variable) && !isStaticOrFinal(variable)) { END issuableVariables.add(variable); } } } checking for the semantic should be done before checking the type of the tree, as semantic is used to get the parameter type of the method.

Target:
public void visitNode(Tree tree) { if (tree.is(Kind.METHOD) && isServletInit((MethodTree) tree)) { tree.accept(new AssignmentVisitor()); } else if (tree.is(Kind.VARIABLE)) { VariableTree variable = (VariableTree) tree; if (isOwnedByAServlet(variable) && !isStaticOrFinal(variable)) { issuableVariables.add(variable); } } }
Source:
START public Boolean implies(SymbolicValueRelation relation) { END if (v1.equals(relation.v1) && v2.equals(relation.v2)) { return relation.isImpliedBy(this); } else if (v1.equals(relation.v2) && v2.equals(relation.v1)) { return relation.isImpliedBy(symmetric()); } return null; } why `public` when all the other are `protected`.

Target:
protected Boolean implies(SymbolicValueRelation relation) { if (v1.equals(relation.v1) && v2.equals(relation.v2)) { return relation.isImpliedBy(this); } else if (v1.equals(relation.v2) && v2.equals(relation.v1)) { return relation.isImpliedBy(symmetric()); } return null; }
Source:
public void visitNode(Tree tree) { MethodTreeImpl methodTree = (MethodTreeImpl) tree; Symbol.MethodSymbol methodSymbol = methodTree.symbol(); START if (methodSymbol.isMethodSymbol()) { END JavaSymbol.MethodJavaSymbol overridee = ((JavaSymbol.MethodJavaSymbol) methodSymbol).overriddenSymbol(); if (overridee != null && overridee.isMethodSymbol()) { checkContractChange(methodTree, overridee); } } } As you know it's a method symbol from getting it the `methodTree`, why testing it again? Is it to cover the case of unknown symbol? If it's the case, I would prefer to test it by using `!methodSymbol.isUnknown()`. Moreover, this case is not covered by your test cases. The same remarks apply to the overridee below.

Target:
public void visitNode(Tree tree) { MethodTreeImpl methodTree = (MethodTreeImpl) tree; Symbol.MethodSymbol methodSymbol = methodTree.symbol(); JavaSymbol.MethodJavaSymbol overridee = ((JavaSymbol.MethodJavaSymbol) methodSymbol).overriddenSymbol(); if (overridee != null && overridee.isMethodSymbol()) { checkContractChange(methodTree, overridee); } }
Source:
START static boolean isWithinTryHeader(Tree syntaxNode) { END final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; } should be private.

Target:
private static boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }
Source:
START static boolean isTryStatementResource(VariableTree variable) { END final TryStatementTree tryStatement = getEnclosingTryStatement(variable); if (tryStatement != null) { return tryStatement.resources().contains(variable); } return false; } should be private.

Target:
private static boolean isTryStatementResource(VariableTree variable) { final TryStatementTree tryStatement = getEnclosingTryStatement(variable); return tryStatement != null && tryStatement.resources().contains(variable); }
Source:
START public JavaVersionImpl(int javaVersion) { END this.javaVersion = javaVersion; this.initialized = true; } Should deserve a @VisibleForTesting ?

Target:
public JavaVersionImpl(int javaVersion) { this.javaVersion = javaVersion; }
Source:
public Set<SymbolicValue> getFieldValues() { START final HashSet<SymbolicValue> fieldValues = new HashSet<>(); END values.forEach(new PMap.Consumer<Symbol, SymbolicValue>() { @Override public void accept(Symbol key, SymbolicValue value) { if (isField(key)) { fieldValues.add(value); } } }); return fieldValues; } No special need for final and please use interface. No need to know implementation. I would even recommend to use ImmutableSet from guava for safety.

Target:
public Set<SymbolicValue> getFieldValues() { final Set<SymbolicValue> fieldValues = new HashSet<>(); values.forEach(new PMap.Consumer<Symbol, SymbolicValue>() { @Override public void accept(Symbol key, SymbolicValue value) { if (isField(key)) { fieldValues.add(value); } } }); return fieldValues; }
Source:
public void newInstanceBis() throws IllegalAccessException, InstantiationException { try { // Refind the constructor after a deserialization (if needed) if (constructor == null) { this.setDynaBeanClass(); } // Invoke the constructor to create a new bean instance return ((DynaBean) constructor.newInstance(constructorValues)); } catch (final InvocationTargetException e) { throw new InstantiationException (e.getTargetException().getMessage()); } START } END This test case seems overcomplicated. All what is not necessary should be removed : (generics, try catch, etc).

Target:
public void newInstanceBis() throws IllegalAccessException, InstantiationException { if (constructor == null) { this.setDynaBeanClass(); } return ((DynaBean) constructor.newInstance(constructorValues)); }
Source:
public Resolution findMethod(Env env, JavaType site, String name, List<JavaType> argTypes) { START return findMethod(env, site, site, name, argTypes, ImmutableList.<JavaType>of()); END } Maybe you could have let the `false` parameter to avoid the initial call to the new method `findMethod`

Target:
public Resolution findMethod(Env env, JavaType site, String name, List<JavaType> argTypes) { return findMethod(env, site, site, name, argTypes, ImmutableList.<JavaType>of(), false); }
Source:
private String registerClassInternalName(String name) { int num; if (internalNames.containsKey(name)) { num = internalNames.get(name) + 1; } else { START num = 1; END } internalNames.put(name, num); return num + name; } initialize num to 1 and get rid of else.

Target:
private String registerClassInternalName(String name) { internalNames.add(name); return internalNames.count(name) + name; }
Source:
public Set<Symbol> getOut(CFG.Block block) { START return ImmutableSet.copyOf(out.get(block)); END } @benzonico copy should be done outside of getter - at the end of analysis

Target:
public Set<Symbol> getOut(CFG.Block block) { return out.get(block); }
Source:
int increment_operator() { int i = 0; int b = 12; START ++b; END int j = -1; while ((j = foo(++j)) != -1) { System.out.println(""); } if(i != 0) { return i++; // Noncompliant } else { return ++i; } } @benzonico false-negative

Target:
int increment_operator() { int i = 0; int b = 12; ++b; // Noncompliant int c = 0; foo(++c); // compliant not last element of block int j = -1; while ((j = foo(++j)) != -1) { System.out.println(""); } if(i != 0) { return i++; // Noncompliant } else { return ++i; } }
Source:
private boolean isSearchedVariable(ExpressionTree variable) { START return variable.is(Tree.Kind.IDENTIFIER) && usages.contains((IdentifierTree) variable); END } @m-g-sonar `(IdentifierTree)` cast not needed.

Target:
private boolean isSearchedVariable(ExpressionTree variable) { return variable.is(Tree.Kind.IDENTIFIER) && usages.contains(variable); }
Source:
START private boolean operandsAreOnSameLine(BinaryExpressionTree formatStringTree) { END return FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.leftOperand()).line() == FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.rightOperand()).line(); } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "operandsAreOnSameLine" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AS2325)

Target:
private static boolean operandsAreOnSameLine(BinaryExpressionTree formatStringTree) { return FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.leftOperand()).line() == FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.rightOperand()).line(); }
Source:
START private ExpressionTree getPackageName(CompilationUnitTree cut) { END return cut.packageDeclaration() != null ? cut.packageDeclaration().packageName() : null; } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "getPackageName" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AS2325)

Target:
private static ExpressionTree getPackageName(CompilationUnitTree cut) { return cut.packageDeclaration() != null ? cut.packageDeclaration().packageName() : null; }