auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testItValidatesMaxSizeOfPhotoShareByMessage() throws MalformedURLException { SharePhotoContent sharePhotoContent = new SharePhotoContent.Builder().addPhoto(buildSharePhoto("https://facebook.com/awesome-1.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-2.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-3.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-4.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-5.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-6.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-7.gif")) .build(); ShareContentValidation.validateForMessage(sharePhotoContent); }

Target:
nit put addPhoto on next line
Source:
public boolean canBePloted(World world, int x, int y, int z) { for (GhostGroupElement element : elementList) { if (!Eln.ghostManager.canCreateGhostAt(world, new BlockPos( + element.x, y + element.y, z + element.z))) return false; } return true; }

Target:
This is obviously a syntax error.
Source:
private void replaceFile(Path from, Path to) throws IOException { try { Files.move(from, to, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { Files.move(from, to, StandardCopyOption.REPLACE_EXISTING); } }

Target:
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); I would pass both parameters for the first try.
Source:
public boolean textboxKeyTyped(char par1, int par2) { if (getEnabled() && this.isFocused() && par1 == '\r') { return true; setFocused(false); } return super.textboxKeyTyped(par1, par2); }

Target:
Should be inverted
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } String qualifiedName = ((AnnotationTree) tree).annotationType().symbolType().fullyQualifiedName(); if (OLD_NEW_ANNOTATIONS_MAP.containsKey(qualifiedName)) { reportIssue(tree, String.format("Change this JUnit4 %s to the equivalent JUnit5 %s annotation.", qualifiedName, OLD_NEW_ANNOTATIONS_MAP.get(qualifiedName))); } }

Target:
It needs to be clearly discussed and clarified at one point, but the case where the semantic is missing should never happen, we already removed this check for many rules. I believe you can also remove this one (and the corresponding test).
Source:
public void visitMethodInvocation(MethodInvocationTree mit) { if (isInvocationOnVariable(mit, variable) && SET_SSL_CHECK_SERVER_ID.matches(mit) && isNotFalse(mit.arguments().get(0))) { this.isSecured = true; } super.visitMethodInvocation(mit); }

Target:
This test condition leads to FP if we are bad at resolving the variable symbol. I would prefer to replace `isInvocationOnVariable` by something like `isInvocationOnTheGivenVariableButReturnTrueIfYourAreUnsureAboutOnWhatThisMethodIsInvoked` :wink:
Source:
protected List<MethodMatcher> getMethodInvocationMatchers() { return Collections.singletonList( MethodMatcher.create() .typeDefinition(TypeCriteria.is("javax.crypto.Cipher")) .name("getInstance") .withAnyParameters()); }

Target:
You can directly use the string is you are using `TypeCriteria.is()`
Source:
private void addIssueIfNotCaught(Type thrown, Tree node) { if (isNotCaught(thrown)) { String message = "Handle the " + "\"" + thrown + "\"" + " thrown here in a \"try/catch\" block."; reportIssue(node, message); } }

Target:
Never rely on the ToString() method of a type. What if it change in implementation class for debugging purpose? Use `thrown.name()` instead.
Source:
private void usageLabel(@Nullable IdentifierTreeImpl node) { if (node == null) { return; } labels.stream() .filter(couple -> couple.label.equals(node.name())) .map(couple -> couple.symbol) .findFirst() .ifPresent(labelSymbol -> { labelSymbol.usages.add(node); node.labelSymbol = labelSymbol; }); }

Target:
Do not break the group of methods working with tokens, i.e. should be above `firstTokenIndexAfter`.
Source:
private void declaration(@Nullable IBinding binding, Tree node) { if (binding == null) { return; } sema.declarations.put(sema.declarationBinding(binding), node); }

Target:
IMO for declarations `binding == sema.declarationBinding(binding)` already.
Source:
public List<String> getStrings() { if (null == strings) { synchronized (this) { if (null == this.strings) { strings = new ArrayList<>(); // Noncompliant [[sc=11;ec=38;secondary=25,27]] {{Fully initialize "strings" before assigning it.}} strings.add("Hello"); System.out.println(); strings.add("World"); } } } return strings; }

Target:
please use a different name for the method here, this should not compile...
Source:
private static Symbol symbol(ExpressionTree tree) { return Optional.ofNullable(tree).filter(t -> t.is(Kind.IDENTIFIER)).map(t -> ((IdentifierTree) t).symbol()).orElse(null); }

Target:
You should annotate parameter with `@Nullable` , or if you don't need to handle `null` argument, you don't need `ofNullable`
Source:
private static StatementTree getBody(StatementTree tree, int expectedSize) { StatementTree statement = tree; if (statement.is(Kind.BLOCK)) { BlockTree block = (BlockTree) statement; List<StatementTree> body = block.body(); statement = body.size() == expectedSize ? body.get(0) : null; } return statement; }

Target:
Do we need this variable?
Source:
public List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.CLASS, Tree.Kind.METHOD); }

Target:
I'm not sure why you need to have both Classes and Methods here Why not only registering to CLASS, and iterate over its members (Trees)? You will then have only 2 cases to handle: * It's a VariableTree, so it's necessarily a field, you already have the declaration... And in such cases you absolutely don't need to rely on the `isField()` method. * It's a MethodTree, so it's a method... and you have everything you need to check the parameters already. * It's something else (inner class for instance), do nothing
Source:
private boolean isMessageLoggedWithAdditionalContext() { if (loggingMethodInvocations.isEmpty()) { return false; } return loggingMethodInvocations.stream().anyMatch(mit -> hasGetMessageInvocation(mit) && hasDynamicExceptionMessageUsage(mit)); }

Target:
unecessray with the anymatch afterwards.
Source:
public void scanFile(final JavaFileScannerContext context) { this.context = context; assertionInMethod.clear(); visitedMethods.clear(); inUnitTest.push(false); methodContainsAssertion.push(false); scan(context.getTree()); methodContainsAssertion.pop(); inUnitTest.pop(); assertionInMethod.clear(); visitedMethods.clear(); }

Target:
As discussed, you can probably rely on the keySet of assertionInMethod map rather than using an other set.
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree arg = mit.arguments().get(0); String domain = ConstantUtils.resolveAsStringConstant(arg); if (domain != null && !domain.substring(1).contains(".")) { reportIssue(arg, "Specify at least a second-level cookie domain."); } }

Target:
Check will crash if code contains a call to `setDomain` method with empty string `myCookie.setDomain("");`
Source:
void HttpCookie(String domain) { HttpCookie myCookie = new Cookie("name", "val"); myCookie.setDomain(".com"); // Noncompliant myCookie.setDomain(".myDomain.com"); // Compliant myCookie.setDomain(domain); // Compliant }

Target:
Should it not be `new HttpCookie` instead?
Source:
public void visitMethod(MethodTree tree) { if (!isEquals(tree)) { super.visitMethod(tree); } }

Target:
make it final. You don't want classes extending it to override this, as it's driving the analysis.
Source:
protected static boolean isBot(Type type) { return ((JavaType) type).isTagged(JavaType.BOT); }

Target:
why not private?
Source:
public void visitNewClass(NewClassTree tree) { if (tree.is(Tree.Kind.NEW_CLASS)) { checkMethodInvocationArgument(tree.arguments(), tree.constructorSymbol()); } super.visitNewClass(tree); }

Target:
the `tree` is necessarily a `NewClassTree` here, so you already know it's going to be of the good kind. You can drop the `if`.
Source:
private boolean hasNoSecurityConstraint(XmlFile file) { NodeList nodeList = evaluate(securityConstraintExpression, file.getNamespaceUnawareDocument()); return (nodeList.getLength() == 0); }

Target:
no need for the parenthesis
Source:
public void visitIdentifier(IdentifierTree tree) { if (tree.name().equals(exceptionIdentifier.name())) { isExceptionIdentifierUsed = true; } }

Target:
There is no need to recheck equality if `isExceptionIdentifierUsed` is already true
Source:
protected List<MethodMatcher> getMethodInvocationMatchers() { return ImmutableList.of( MethodMatcher.create() .typeDefinition(TypeCriteria.is("javax.crypto.Cipher")) .name("getInstance") .withAnyParameters(), MethodMatcher.create() .typeDefinition(TypeCriteria.is("org.apache.commons.crypto.utils.Utils")) .name("getCipherInstance") .withAnyParameters()); }

Target:
You can use the string overload when TypeCriteria is exact match.
Source:
private static Tree firstStatementParent(Tree node) { Tree current = node; while (true) { if (current instanceof StatementTree) { return current; } current = current.parent(); } }

Target:
probably safer to have a current != null
Source:
private static void addSecurityStandards(NewRule rule, SecurityStandards securityStandards) { for (String s : securityStandards.OWASP) { rule.addOwaspTop10(OwaspTop10.valueOf(s)); } int[] cweNumbers = Arrays.stream(securityStandards.CWE).map(cwe -> cwe.substring(4)).mapToInt(Integer::valueOf).toArray(); rule.addCwe(cweNumbers); }

Target:
hm... do we want change API? to accept full names?
Source:
private boolean methodOpeningResource(MethodInvocationTree mit) { return !excludedByRuleOption(mit.symbolType()) && !isWithinTryHeader(mit) && !handledByFramework(mit) && (JDBC_RESOURCE_CREATIONS.anyMatch(mit) || STREAMS_BACKED_BY_RESOURCE.anyMatch(mit) || (needsClosing(mit.symbolType()) && !CLOSEABLE_EXCEPTIONS.anyMatch(mit) && mitHeuristics(mit))); }

Target:
Why switching the order of the short circuit ?
Source:
private static List<StringConstant> antMatchersPatterns(MethodInvocationTree mit) { List<StringConstant> argumentsAsString = mit.arguments().stream() .map(StringConstant::of) .collect(Collectors.toList()); return argumentsAsString.stream().allMatch(Objects::nonNull) ? argumentsAsString : Collections.emptyList(); }

Target:
Why only considering the cases having only literals? I think we should also consider the following cases, as we already know they are wrong, even without considering `myVar`: ```java http.authorizeRequests().antMatchers("/admin/**", myVar, "/admin/login"); // Noncompliant ``` Therefore, I would simply skip the null values.
Source:
public void reportIssue(JavaCheck javaCheck, Tree syntaxNode, String message, List<Location> secondary, @Nullable Integer cost) { throwIfCrossFileScanner(javaCheck); List<List<Location>> flows = secondary.stream().map(Collections::singletonList).collect(Collectors.toList()); reportIssueWithFlow(javaCheck, syntaxNode, message, flows, cost); }

Target:
I wonder about throwing everywhere, as most of the `reportIssue` message are calling the same on line 123/127.
Source:
public void reportIssue(JavaCheck javaCheck, Tree tree, String message) { throwIfEndOfAnalysisCheck(javaCheck); reportIssue(javaCheck, tree, message, ImmutableList.of(), null); }

Target:
Let's use this method on overloading.
Source:
public void test() { JavaCheckVerifier.verify("src/test/files/checks/spring/SpringSecurityDisableCSRFCheck.java", new SpringSecurityDisableCSRFCheck()); JavaCheckVerifier.verifyNoIssueWithoutSemantic("src/test/files/checks/spring/SpringSecurityDisableCSRFCheck.java", new SpringSecurityDisableCSRFCheck()); }

Target:
To me this line is useless, the `AbstractMethodDetection` checks won't work without semantic, and it won't change coverage.
Source:
public void junit_assert_that() { assertThat("aaa", org.junit.matchers.JUnitMatchers.containsString("a")); }

Target:
Do not change that. Keep it explicit to show that it's a junit assert.
Source:
void testRecursion() { Math f = new Math() { // Compliant, recursion @Override public String powerOfTwo(int n) { return n == 0 ? 1 : 2 * powerOfTwo(n -1); } }; }

Target:
int powerOfTwo(int n);
Source:
private static MethodTree findEnclosingMethod(Tree tree) { while (!tree.is(Tree.Kind.CLASS, Tree.Kind.METHOD)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS)) { return null; } return (MethodTree) tree; }

Target:
this duplicates `findEnclosingMethod` on `CipherBlockChainingCheck` - should move to `ExpressionsHelper` or something similar
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; BlockTree blockTree = methodTree.block(); if (blockTree == null) { return; } if (!CHECK_CLIENT_TRUSTED_MATCHER.matches(methodTree) && !CHECK_SERVER_TRUSTED_MATCHER.matches(methodTree)) { return; } if (!ThrowExceptionVisitor.throwsException(blockTree)) { reportIssue(methodTree.simpleName(), "Change this method so it throws exceptions."); } }

Target:
Think it would be easier to read without negations and return. ``` if (CHECK_CLIENT_TRUSTED_MATCHER.matches(methodTree) || CHECK_SERVER_TRUSTED_MATCHER.matches(methodTree)) { if (!ThrowExceptionVisitor.throwsException(blockTree)) { //... } } ```
Source:
public void method_with_unknown_symbol_should_not_produce_ucfg() { CompilationUnitTree cut = getCompilationUnitTreeWithSemantics("class A {void foo(UnkownType t) {return t;}}"); UCFGJavaVisitor UCFGJavaVisitor = new UCFGJavaVisitor(tmp.getRoot()) { @Override protected void serializeUCFG(MethodTree tree, CFG cfg) { fail("should not serialize a UCFG of a method with unknown parameters"); } }; UCFGJavaVisitor.fileKey = FILE_KEY; UCFGJavaVisitor.visitCompilationUnit(cut); cut = getCompilationUnitTreeWithSemantics("class A {UnkownType foo(String t) {return t;}}"); UCFGJavaVisitor.visitCompilationUnit(cut); }

Target:
useless empty lines
Source:
public void scanFile(JavaFileScannerContext context) { this.context = context; statementSet.clear(); scan(context.getTree()); }

Target:
You should clear the set after the scan to, to be sure that references to the `IfStatementTree` are not kept for the whole scanning process. Actually, I think I'd prefer to avoid using a set altogether by using the parent to retrieve the `else` keyword (i.e. if the parent is a `IfStatementTree` and current if is the else statement of the parent). What do you think?
Source:
private static String getSuggestedType(boolean springInjectionAnnotated, Type leastSpecificType) { if (springInjectionAnnotated && leastSpecificType.is("java.lang.Iterable")) { return "java.util.Collection"; } else { return leastSpecificType.fullyQualifiedName().replace('$', '.'); } }

Target:
minor : no need for the else with the returns...
Source:
private void handleParameter(Symbol parameter, boolean springInjectionAnnotated) { Type leastSpecificType = findLeastSpecificType(parameter); if (parameter.type() != leastSpecificType && !leastSpecificType.is("java.lang.Object") && !(springInjectionAnnotated && parameter.type().is("java.util.Collection"))) { String suggestedType = getSuggestedType(springInjectionAnnotated, leastSpecificType); reportIssue(parameter.declaration(), String.format("Use '%s' here; it is a more general type than '%s'.", suggestedType, parameter.type().name())); } }

Target:
matter of style and choices but I tend to think that this last part of the && should be implemented as a filter of stream on the parameters stream.
Source:
private static boolean noSpacingBetween(SyntaxToken firstToken, SyntaxToken secondToken) { return firstToken.column() + firstToken.text().length() == secondToken.column(); }

Target:
I just realized that this could generate FPs when placed on different lines: ```java target = +num; ``` We should check that both token are sharing the same line.
Source:
private void checkMethodDefinition(MethodTree tree) { BlockTree blockTree = tree.block(); if (tree.symbol() != null && VERIFY_METHOD_MATCHER.matches(tree) && blockTree != null) { checkBlock(blockTree); } }

Target:
symbol cannot be null for a method tree.
Source:
private static boolean isHostnameVerifierSignature(LambdaExpressionTree lambdaExpressionTree) { List<VariableTree> parameters = lambdaExpressionTree.parameters(); return lambdaExpressionTree.symbolType().isSubtypeOf("javax.net.ssl.HostnameVerifier") && parameters.size() == 2 && TYPE_CRITERIA_STRING.test(parameters.get(0).type().symbolType()) && TYPE_CRITERIA_SSL_SESSION.test(parameters.get(1).type().symbolType()); }

Target:
if you have a lambda as a subtype of HostnameVerifier I don't think you need all the elements of the condition. (in other words, there is no way if this first part is true that any of the following might be false, and it is therefore uncoverable by unit test and useless) : so all the following && can be safely removed I think. (please prove me wrong if I am ;) )
Source:
private static ExpressionTree instanceofFound(ExpressionTree expressionTree, Tree.Kind kind) { if (Tree.Kind.CONDITIONAL_OR.equals(kind)) { /* if CONDITIONAL_OR we want LOGICAL COMPLEMENT before instanceof */ if (expressionTree.is(Tree.Kind.LOGICAL_COMPLEMENT)) { return instanceofLHS(ExpressionUtils.skipParentheses(((UnaryExpressionTree) expressionTree).expression())); } else { return null; } } else { return instanceofLHS(expressionTree); } }

Target:
``` kind == Tree.Kind.CONDITIONAL_OR ```
Source:
private void checkUsage(IdentifierTree parameterUsage, MethodTree methodTree) { Tree parameterParent = parameterUsage.identifierToken().parent(); while (!parameterParent.equals(methodTree) && !assertReported.contains(parameterParent)) { if (parameterParent.is(Tree.Kind.ASSERT_STATEMENT)) { assertReported.add((AssertStatementTree) parameterParent); reportIssue(parameterParent, "Replace this assert with a proper check."); return; } parameterParent = parameterParent.parent(); } }

Target:
why starting from the `identifierToken()` and not directly from `parameterUsage` ? You can directly strart from the parameter parent.
Source:
private static void logNoMatchClasses(Collection<IClassCoverage> noMatchClasses) { if (!noMatchClasses.isEmpty()) { LOG.warn("The following class(es) did not match with execution data:"); for (IClassCoverage iClassCoverage : noMatchClasses) { LOG.warn(String.format("> '%s'", iClassCoverage.getName())); } LOG.warn("In order to have accurate coverage measures, the same class files must be used as at runtime for report generation."); } }

Target:
@m-g-sonar use early return to improve readability?
Source:
public void visitNewClass(NewClassTree tree) { super.visitNewClass(tree); ClassTree classBody = tree.classBody(); if (classBody != null) { TypeTree identifier = tree.identifier(); if (!useThisIdentifier(classBody) && !enumConstants.contains(identifier) && isSAM(classBody, identifier)) { context.reportIssue(this, identifier, "Make this anonymous inner class a lambda" + context.getJavaVersion().java8CompatibilityMessage()); } } }

Target:
You don't need the identifier here. You can extract the equivalent symbol from the classBody directly in the method `isSAM`.
Source:
public void visitNode(Tree tree) { IfStatementTree treeIfStmt = (IfStatementTree) tree; StatementTree elseStmt = treeIfStmt.elseStatement(); IfStatementTree ifStmt = null; if (elseStmt != null && elseStmt.is(Tree.Kind.IF_STATEMENT)) { ifStmt = (IfStatementTree) elseStmt; } if (ifStmt != null && ifStmt.elseStatement() == null) { reportIssue(treeIfStmt.elseKeyword(), ifStmt.ifKeyword(), "\"if ... else if\" constructs should end with \"else\" clauses."); } }

Target:
I think you are over-complicating things here. Try to keep it simple and "logical" to read, introducing the variable you need and minimizing the number of validation you need to do. In this case, simply nest the 2 `if` statements, and put the definition of the `ifStmt` variable within the body of the first `if`. you can then remove the `ifStmt != null` test.
Source:
public List<Tree.Kind> nodesToVisit() { return Collections.singletonList((Tree.Kind.CONSTRUCTOR)); }

Target:
Unecessary parentheses.
Source:
public List<Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.SWITCH_STATEMENT); }

Target:
Use `Tree.Kind` instead, to remove the import.
Source:
public void visitSwitchStatement(SwitchStatementTree tree) { reportIssue((tree).switchKeyword(), "Refactor the code to eliminate this nested \"switch\"."); }

Target:
remove the useless parentheses, and no need for 2 different lines.
Source:
private static boolean isNullableThroughNonNull(Symbol symbol) { List<SymbolMetadata.AnnotationValue> valuesForAnnotation = symbol.metadata().valuesForAnnotation("javax.annotation.Nonnull"); if (valuesForAnnotation == null) { return false; } if (valuesForAnnotation.isEmpty()) { return false; } return checkAnnotationParameter(valuesForAnnotation, "when", "MAYBE") || checkAnnotationParameter(valuesForAnnotation, "when", "UNKNOWN"); }

Target:
I would factorize this in the condition of the previous if.
Source:
public static Optional<String> parameterNonNullGlobalAnnotation(Symbol.MethodSymbol method) { if (isGloballyAnnotatedWith(method, JAVAX_ANNOTATION_PARAMETERS_ARE_NONNULL_BY_DEFAULT)) { return Optional.of(JAVAX_ANNOTATION_PARAMETERS_ARE_NONNULL_BY_DEFAULT); } if (isGloballyAnnotatedWith(method, ORG_ECLIPSE_JDT_ANNOTATION_NON_NULL_BY_DEFAULT, "PARAMETER")) { return Optional.of(ORG_ECLIPSE_JDT_ANNOTATION_NON_NULL_BY_DEFAULT); } return Optional.empty(); }

Target:
as far as I understand the usage of this method it seems you don't get anything out of Optional: this method should just return null
Source:
public void setUp() { semanticModel = SETestUtils.getSemanticModel("src/test/files/se/annotations/NullableAnnotationUtils.java"); }

Target:
This change implies parsing and semantic computation for every test of this class. This seems quite some overhead.
Source:
private ProgramState handleSpecialMethods(ProgramState ps, MethodInvocationTree mit) { if (AnnotationUtils.isAnnotatedNonNull(mit.symbol())) { return ps.addConstraint(ps.peekValue(), ObjectConstraint.NOT_NULL); } else if (OBJECT_WAIT_MATCHER.matches(mit)) { return ps.resetFieldValues(constraintManager, false); } return ps; }

Target:
Wondering about having a static import for AnnotationUtils method.
Source:
static boolean enqueueExitBlock4() { try { throwSpecificException(); } catch (Throwable e) { return true; } return true; }

Target:
wonder if it would not be more interesting to have `false` here to see that we are correctly jumping into the catch.
Source:
public String toString() { return "[" + stream().map(Constraint::toString).sorted().collect(Collectors.joining(",")) + "]"; }

Target:
👍 Minor: you can provide suffix and prefix args to `Collectors.joining` and avoid adding brackets with `+`
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FieldOrMethod that = (FieldOrMethod) o; return ownerIsInterface == that.ownerIsInterface && Objects.equals(owner, that.owner) && Objects.equals(name, that.name) && Objects.equals(desc, that.desc); }

Target:
please fix this one
Source:
public void visitMethodInvocation(MethodInvocationTree tree) { if (SUPER_THREAD.matches(tree) && ThreadOverridesRunCheck.hasRunnableArgument(tree.arguments())) { callSuperWithRunnable = true; } super.visitMethodInvocation(tree); }

Target:
micro optimisation but : no need to visit further...
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; } return arguments.stream().filter(UnclosedResourcesCheck::isCloseable).allMatch(this::isNestedNewResourceCreation); } return false; }

Target:
all match returns true if the stream is empty so no need for the previous if.
Source:
private ExecutorService createExecutor() { int numThreads = Runtime.getRuntime().availableProcessors() + 1; return Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat("SonarJava-parallel-analysis-%d").build()); }

Target:
![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)
Source:
private static boolean hasOnlyNonNullConstraint(ConstraintsByDomain constraints) { List<Class<? extends Constraint>> domains = constraints.domains().collect(Collectors.toList()); return domains.size() == 1 && constraints.get(ObjectConstraint.class) == ObjectConstraint.NOT_NULL; }

Target:
why not directly `constraints.domains().count() == 1` ?
Source:
private boolean isConstraintFromObjectDomain(@Nullable Constraint constraint) { return constraint != null && constraint.getClass().isAssignableFrom(ObjectConstraint.class); }

Target:
why not simply use `constraint instanceof ObjectConstraint` ? if null, it will return `false`.
Source:
public MethodInvariantContext(MethodTree methodTree) { this.methodTree = methodTree; TypeTree returnType = methodTree.returnType(); this.returnStatementTrees = extractReturnStatements(methodTree); methodToCheck = !isConstructorOrVoid(returnType) && returnStatementTrees.size() > 1; returnImmutableType = methodToCheck && (returnType.symbolType().isPrimitive() || returnType.symbolType().is("java.lang.String")); }

Target:
no need for `this.`
Source:
public int hashCode() { if (hashCode == 0) { hashCode = Objects.hash(values, constraints, peekValue(), lastAssociatedSymbol); } return hashCode; }

Target:
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.
Source:
void fun() { Object test = new Object[]{"1"}; String[] test2 = new Object[]{"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 }

Target:
Does not compile, but not really important.
Source:
private Edge(Node child, Node parent) { Preconditions.checkState(!Objects.equals(child, parent)); this.child = child; this.parent = parent; hashcode = Objects.hash(child, parent); }

Target:
Maybe worth removing the call to `Objects.equals()` here too, as both child and parent can not be null.
Source:
private static boolean hasProperEquals(MethodTree methodTree) { Symbol.MethodSymbol symbol = methodTree.symbol(); if (symbol == null) { return true; } Symbol.TypeSymbol enclosingClass = symbol.enclosingClass(); if (enclosingClass == null) { return true; } return enclosingClass.memberSymbols().stream().anyMatch(MethodNamedEqualsCheck::isEqualsMethod); }

Target:
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.
Source:
private static boolean invalidMethodAndVariable(Symbol currentMember, Symbol knownMember) { Symbol methodSymbol = currentMember.isMethodSymbol() ? currentMember : knownMember; Symbol variableSymbol = methodSymbol == currentMember ? knownMember : currentMember; return sameVisibilityNotPrivate(currentMember, knownMember) && !methodReturningVariableWithSameName(methodSymbol, variableSymbol) && !isBuilderPattern(methodSymbol, variableSymbol); }

Target:
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.
Source:
public Set<String> done(){ ParametrizedTypeJavaType.typeSubstitutionSolver = null; bytecodeCompleter.done(); return bytecodeCompleter.classesNotFound(); }

Target:
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.
Source:
public boolean accept(FilterableIssue issue) { if (filterAnyRule) { return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(ANY_RULE_KEY).contains(issue.line())); } return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(issue.ruleKey().rule()).contains(issue.line())); }

Target:
This should be rewritten to just change the key depending of filterAnyRule.
Source:
private static boolean isClassController(Symbol.MethodSymbol methodSymbol) { SymbolMetadata parentClassOwner = methodSymbol.owner().metadata(); return parentClassOwner.isAnnotatedWith("org.springframework.stereotype.Controller"); }

Target:
you can inline the `parentClassOwner`(Metadata) variable
Source:
private static boolean isNullLiteral(ExpressionTree lastArgument) { ExpressionTree arg = ExpressionUtils.skipParentheses(lastArgument); return arg.is(Tree.Kind.NULL_LITERAL) || (arg.is(Tree.Kind.TYPE_CAST) && ((TypeCastTree) arg).expression().is(Tree.Kind.NULL_LITERAL)); }

Target:
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)));`
Source:
public String toString() { return String.valueOf(leftOp) + kind.operand + rightOp; }

Target:
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.
Source:
void f() { if (this == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } if (super == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } }

Target:
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.
Source:
public 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(); }

Target:
This one should also probably not have an extended visibility but rather be reimplemented.
Source:
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; }

Target:
I would set it private as this class ought to be externalized at one point.
Source:
public LearnedConstraint(SymbolicValue sv, @Nullable Constraint constraint) { Objects.requireNonNull(sv); this.sv = sv; this.constraint = constraint; }

Target:
unrelated to this commit.
Source:
public Type getClassType(String fullyQualifiedName) { return bytecodeCompleter.loadClass(fullyQualifiedName).type; }

Target:
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.)
Source:
private static boolean isWithinTryHeader(Tree syntaxNode) { Tree parent = syntaxNode; while ((parent = parent.parent()) != null) { if (parent.is(Tree.Kind.VARIABLE)) { break; } } if (parent != null && parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }

Target:
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.
Source:
private void enqueueThrownExceptionalPaths(Symbol symbol) { if (symbol.isMethodSymbol()) { ProgramState ps = programState.clearStack(); ((Symbol.MethodSymbol) symbol).thrownTypes().stream() .map(constraintManager::createExceptionalSymbolicValue) .forEach(exceptionSV -> enqueueExceptionalPaths(ps, exceptionSV)); } }

Target:
I think this one could rely on MethodInvocationTree : that would allow to not declare methodSymbol local variable.
Source:
public void while_statement() { Lock lock = new ReentrantLock(); while (foo) { lock.tryLock(); } lock.unlock(); while (Random.nextBoolean()) { lock.tryLock(); // Noncompliant lock = new ReentrantLock(); } lock.unlock(); }

Target:
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.
Source:
private boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }

Target:
And when `isTryStatementResource` is static, this one can be static as well.
Source:
private boolean isTryStatementResource(VariableTree variable) { final TryStatementTree tryStatement = getEnclosingTryStatement(variable); return tryStatement != null && tryStatement.resources().contains(variable); }

Target:
This one can be static.
Source:
private Map<String, Object> loadYamlConfig(String configFile) { Path configPath = Paths.get(configFile); 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); } }

Target:
You don't need to fill the body of that method, you just need it to use it as lambda.
Source:
void activateDeferredProfile() throws ProfileDataException{ }

Target:
Replace the exception by `Exception`, so your test is self contained.
Source:
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(2))) .withoutParameter(); }

Target:
Are you sure about `.substring(2)` ? With `INFO`, I'll get `isIfoEnabled`...
Source:
public void leaveNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(METHOD) || tree.is(CONSTRUCTOR)) { synchronizedStack.pop(); } }

Target:
no need for the ||
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(SYNCHRONIZED_STATEMENT)) { 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."); } } } }

Target:
no need for that if.
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(); } else { //if it's member select, we check the type of the member select expression return ((MemberSelectExpressionTree) expressionTree).expression().symbolType().symbol().isFinal(); } }

Target:
I would remove the else given that you return at the end of the if.
Source:
public void visitMethod(MethodTree tree) { if (tree == writeObjectMethodTree || moreThanSingleLock) { return; } if (hasModifier(tree.modifiers(), SYNCHRONIZED)) { moreThanSingleLock = true; } super.visitMethod(tree); }

Target:
![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)
Source:
void setThreshold(int threshold) { this.threshold = threshold; }

Target:
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.
Source:
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; }

Target:
what about : ``` (f) == null ```
Source:
private static Set<Type> primitiveWrappers(Set<Type> types) { if (!types.stream().allMatch(Type::isPrimitive)) { return types.stream().map(t -> !t.isPrimitive() ? t : ((JavaType) t).primitiveWrapperType()).collect(Collectors.toCollection(LinkedHashSet::new)); } return types; }

Target:
I would just not negate the condition.
Source:
private 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"); }

Target:
This method can be static, as all the methods it calls.
Source:
private static boolean isZeroDimension(ArrayDimensionTree dim) { ExpressionTree expression = dim.expression(); return expression == null || (expression.is(Tree.Kind.INT_LITERAL) && "0".equals(((LiteralTree) expression).value())); }

Target:
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.
Source:
private void handleConstructor(NewClassTree tree) { if (PASSWORD_AUTHENTICATION_CONSTRUCTOR.matches(tree)) { 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); } } } }

Target:
It's a matter of style, but I would reverse the conditions to not nest 3 `if` statements.
Source:
public DeferredStatusHolderSV(int id, Status deferredStatus) { super(id); this.deferedStatus = deferredStatus; }

Target:
typo. Should have two r.
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))); } else { return ValueBasedUtils.isValueBased(javaType); } }

Target:
No need for the else here.
Source:
private static boolean isInJavaTimePackage(String className) { if (className.contains(".")) { return "java.time".equals(className.substring(0, className.lastIndexOf('.'))); } else { return false; } }

Target:
This whole if can be a single return statement
Source:
public void visitNode(Tree tree) { TypeSymbol classSymbol = ((ClassTree) tree).symbol(); Set<Symbol> fieldsReadOnAnotherInstance = FieldsReadOnAnotherInstanceVisitor.getFrom(classSymbol); classSymbol.memberSymbols().stream() .filter(PrivateFieldUsedLocallyCheck::isPrivateField) .filter(s -> !s.usages().isEmpty()) .filter(s -> !fieldsReadOnAnotherInstance.contains(s)) .forEach(s -> checkPrivateField(s, classSymbol)); }

Target:
The getFrom method should take the classTree not the symbol.
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))) { context.reportIssue(this, binaryExpression, message); } } super.visitBinaryExpression(binaryExpression); }

Target:
you can put directly the message into the call to `reportIssue`, no need to use a dedicated variable.
Source:
public void visitReturnStatement(ReturnStatementTree returnStatement) { ExpressionTree expression = returnStatement.expression(); if (!checkNull(expression) && expression.is(Kind.CONDITIONAL_EXPRESSION)) { ConditionalExpressionTree conditionalExpression = (ConditionalExpressionTree)expression; checkNull(conditionalExpression.trueExpression()); checkNull(conditionalExpression.falseExpression()); } }

Target:
You should extract this part into the `visitConditionalExpression` method, and start the method by checking if the type of the expression is `Optional`.
Source:
public ProgramState addConstraint(SymbolicValue symbolicValue, Constraint constraint) { PMap<SymbolicValue, Constraint> newConstraints = constraints.put(symbolicValue, constraint); if (newConstraints != constraints && !isSymbolicValueOfVolatileField(symbolicValue)) { return new ProgramState(this, newConstraints); } return this; }

Target:
Wondering if it wouldn't not be better to test for "volatileness" of SV prior to adding the constraints.
Source:
public void testSensorDefinition() { org.fest.assertions.Assertions.assertThat(sensor.toString()).isEqualTo("JaCoCoOverallSensor"); }

Target:
`assertThat` is already part of the `static import`. No need to use the fully qualified name (line 40).
Source:
ClassJavaType(int tag, JavaSymbol.TypeJavaSymbol symbol) { super(tag, symbol); }

Target:
should be protected
Source:
private static boolean superTypesHaveOnlyStaticMethods(Symbol.TypeSymbol newClassTypeSymbol) { Type superClass = newClassTypeSymbol.superClass(); if (superClass != null && !superClass.is("java.lang.Object")) { if (!hasOnlyStaticMethodsAndFields(superClass.symbol())) { return false; } } for (Type superInterface : newClassTypeSymbol.interfaces()) { if (!hasOnlyStaticMethodsAndFields(superInterface.symbol())) { return false; } } return true; }

Target:
![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)
Source:
private boolean applicableWithUncheckedConversion(JavaSymbol.MethodJavaSymbol candidate, JavaType callSite, List<JavaType> typeParams) { return !candidate.isStatic() && isRawTypeOfParametrizedType(callSite) && typeParams.isEmpty(); }

Target:
![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)
Source:
public CodeVisitor[] checkClasses() { List<CodeVisitor> visitors = Lists.newArrayList(); // add issue filters BEFORE all the other checks for (JavaIssueFilter issueFilter : issueFilters) { 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()]); }

Target:
addAll ?
Source:
private static boolean differentContract(JavaSymbol.MethodJavaSymbol method, JavaSymbol.MethodJavaSymbol overridee) { return removingParametrizedAspect(method, overridee) || differentReturnType(method, overridee) || differentParameters(method, overridee) || differentAnnotations(method, overridee) || differentThrows(method, overridee); }

Target:
![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)
Source:
public @Nonnull String colorMix() { return null; // Noncompliant {{This method's return value is marked "javax.annotation.Nonnull" but null is returned.}} }

Target:
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
Source:
private 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; }

Target:
![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)
Source:
private boolean isExcluded(VariableTree variable) { return isStaticOrFinal(variable) || variable.symbol().metadata().isAnnotatedWith("javax.inject.Inject"); }

Target:
![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)
Source:
public void visitIdentifier(IdentifierTree tree) { super.visitIdentifier(tree); if ("class".equals(tree.name()) || methodReferences.isEmpty()) { return; } Symbol symbol = tree.symbol(); final MethodReference currentMethod = methodReferences.peek(); if (symbol.isUnknown()) { currentMethod.setNonStaticReference(); return; } for (MethodReference methodReference : methodReferences) { methodReference.checkSymbol(symbol); } }

Target:
remove `final` modifier.
Source:
protected 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; }

Target:
add `@VisibleForTest` and remove the `protected` modifier.
Source:
private static String skipFirstProperty(String text) { String newText = text.substring(text.indexOf(POM_PROPERTY_PREFIX)); return newText.substring(newText.indexOf(POM_PROPERTY_SUFFIX)); }

Target:
no need to do two substring, you should search for index of suffix starting at index of prefix
Source:
public boolean isAnnotatedOverride() { for (AnnotationTree annotationTree : modifiers.annotations()) { if (annotationTree.annotationType().is(Tree.Kind.IDENTIFIER) && isOverride((IdentifierTree) annotationTree.annotationType())) { return true; } else if (annotationTree.annotationType().is(Kind.MEMBER_SELECT) && isJavaLangOverride((MemberSelectExpressionTree) annotationTree.annotationType())) { return true; } } return false; }

Target:
![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)
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; if (hasSemantic() && isOwnedByAServlet(variable) && !isStaticOrFinal(variable)) { issuableVariables.add(variable); } } }

Target:
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.