Search in sources :

Example 1 with JavaFileScannerContext

use of org.sonar.plugins.java.api.JavaFileScannerContext in project sonar-java by SonarSource.

the class VisitorsBridge method visitFile.

public void visitFile(@Nullable Tree parsedTree) {
    semanticModel = null;
    CompilationUnitTree tree = new JavaTree.CompilationUnitTreeImpl(null, new ArrayList<>(), new ArrayList<>(), null, null);
    boolean fileParsed = parsedTree != null;
    if (fileParsed && parsedTree.is(Tree.Kind.COMPILATION_UNIT)) {
        tree = (CompilationUnitTree) parsedTree;
        if (isNotJavaLangOrSerializable(PackageUtils.packageName(tree.packageDeclaration(), "/"))) {
            try {
                semanticModel = SemanticModel.createFor(tree, classLoader);
            } catch (Exception e) {
                LOG.error("Unable to create symbol table for : " + currentFile.getAbsolutePath(), e);
                addAnalysisError(e, currentFile.getPath(), AnalysisError.Kind.SEMANTIC_ERROR);
                return;
            }
            createSonarSymbolTable(tree);
        } else {
            SemanticModel.handleMissingTypes(tree);
        }
    }
    JavaFileScannerContext javaFileScannerContext = createScannerContext(tree, semanticModel, sonarComponents, fileParsed);
    // Symbolic execution checks
    if (symbolicExecutionEnabled && isNotJavaLangOrSerializable(PackageUtils.packageName(tree.packageDeclaration(), "/"))) {
        runScanner(javaFileScannerContext, new SymbolicExecutionVisitor(executableScanners, behaviorCache), AnalysisError.Kind.SE_ERROR);
        behaviorCache.cleanup();
    }
    executableScanners.forEach(scanner -> runScanner(javaFileScannerContext, scanner, AnalysisError.Kind.CHECK_ERROR));
    if (semanticModel != null) {
        classesNotFound.addAll(semanticModel.classesNotFound());
    }
}
Also used : CompilationUnitTree(org.sonar.plugins.java.api.tree.CompilationUnitTree) JavaFileScannerContext(org.sonar.plugins.java.api.JavaFileScannerContext) SymbolicExecutionVisitor(org.sonar.java.se.SymbolicExecutionVisitor) IllegalRuleParameterException(org.sonar.java.IllegalRuleParameterException) InterruptedIOException(java.io.InterruptedIOException) RecognitionException(com.sonar.sslr.api.RecognitionException)

Example 2 with JavaFileScannerContext

use of org.sonar.plugins.java.api.JavaFileScannerContext in project sonar-java by SonarSource.

the class BehaviorCacheTest method verifyNoIssueOnFile.

private static void verifyNoIssueOnFile(String fileName) {
    createSymbolicExecutionVisitorAndSemantic(fileName, false, nullDereferenceCheck);
    // verify we did not raise any issue, if we did, the context will get them reported.
    JavaFileScannerContext context = mock(JavaFileScannerContext.class);
    nullDereferenceCheck.scanFile(context);
    verify(context, never()).reportIssueWithFlow(eq(nullDereferenceCheck), any(Tree.class), anyString(), anySet(), nullable(Integer.class));
}
Also used : JavaFileScannerContext(org.sonar.plugins.java.api.JavaFileScannerContext) Tree(org.sonar.plugins.java.api.tree.Tree) MethodInvocationTree(org.sonar.plugins.java.api.tree.MethodInvocationTree)

Example 3 with JavaFileScannerContext

use of org.sonar.plugins.java.api.JavaFileScannerContext in project sonar-java by SonarSource.

the class MethodYieldTest method constraints_on_varargs.

@Test
public void constraints_on_varargs() throws Exception {
    ActionParser<Tree> p = JavaParser.createParser();
    CompilationUnitTree cut = (CompilationUnitTree) p.parse(new File("src/test/files/se/VarArgsYields.java"));
    SemanticModel semanticModel = SemanticModel.createFor(cut, new SquidClassLoader(new ArrayList<>()));
    SymbolicExecutionVisitor sev = new SymbolicExecutionVisitor(Lists.newArrayList(new SECheck[] {}), new BehaviorCache(new SquidClassLoader(new ArrayList<>())));
    JavaFileScannerContext context = mock(JavaFileScannerContext.class);
    when(context.getTree()).thenReturn(cut);
    when(context.getSemanticModel()).thenReturn(semanticModel);
    sev.scanFile(context);
    MethodSymbol methodSymbol = ((MethodTree) ((ClassTree) cut.types().get(0)).members().get(0)).symbol();
    MethodBehavior mb = getMethodBehavior(sev, "varArgMethod");
    List<MethodYield> yields = mb.yields();
    assertThat(yields).hasSize(5);
    assertThat(mb.exceptionalPathYields()).hasSize(4);
    MethodYield yield = mb.happyPathYields().findFirst().get();
    // check that we have NOT_NULL constraint on the first argument
    assertThat(yield.parametersConstraints.get(0).get(ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    // check that we have NOT_NULL constraint on the variadic argument
    assertThat(yield.parametersConstraints.get(1).get(ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    List<IdentifierTree> usages = methodSymbol.usages();
    assertThat(usages).hasSize(6);
    List<List<Type>> arguments = usages.stream().map(MethodYieldTest::getMethodIncoationArgumentsTypes).collect(Collectors.toList());
    ProgramState ps = ProgramState.EMPTY_STATE;
    ProgramState psResult;
    SymbolicValue svFirstArg = new SymbolicValue();
    SymbolicValue svVarArg1 = new SymbolicValue();
    SymbolicValue svVarArg2 = new SymbolicValue();
    SymbolicValue svResult = new SymbolicValue();
    // apply constraint NotNull to parameter
    Collection<ProgramState> arrayOfA = yield.statesAfterInvocation(Lists.newArrayList(svFirstArg, svVarArg1), arguments.get(0), ps, () -> svResult).collect(Collectors.toList());
    assertThat(arrayOfA).hasSize(1);
    psResult = arrayOfA.iterator().next();
    assertThat(psResult.getConstraint(svFirstArg, ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    assertThat(psResult.getConstraint(svVarArg1, ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    // apply constraint NotNull to parameter (B[] is a subtype of A[])
    Collection<ProgramState> arrayOfB = yield.statesAfterInvocation(Lists.newArrayList(svFirstArg, svVarArg1), arguments.get(1), ps, () -> svResult).collect(Collectors.toList());
    assertThat(arrayOfB).hasSize(1);
    psResult = arrayOfB.iterator().next();
    assertThat(psResult.getConstraint(svFirstArg, ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    assertThat(psResult.getConstraint(svVarArg1, ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    // no constraint, as 'a' is not an array
    Collection<ProgramState> objectA = yield.statesAfterInvocation(Lists.newArrayList(svFirstArg, svVarArg1), arguments.get(2), ps, () -> svResult).collect(Collectors.toList());
    assertThat(objectA).hasSize(1);
    psResult = objectA.iterator().next();
    assertThat(psResult.getConstraint(svFirstArg, ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    assertThat(psResult.getConstraint(svVarArg1, ObjectConstraint.class)).isNull();
    // no constraint, as 'a' and 'b' can not receive the constraint of the array
    Collection<ProgramState> objectsAandB = yield.statesAfterInvocation(Lists.newArrayList(svFirstArg, svVarArg1, svVarArg2), arguments.get(3), ps, () -> svResult).collect(Collectors.toList());
    assertThat(objectsAandB).hasSize(1);
    psResult = objectsAandB.iterator().next();
    assertThat(psResult.getConstraint(svFirstArg, ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    assertThat(psResult.getConstraint(svVarArg1, ObjectConstraint.class)).isNull();
    assertThat(psResult.getConstraint(svVarArg2, ObjectConstraint.class)).isNull();
    // no param, we only learn something about the argument which is not variadic
    Collection<ProgramState> noParam = yield.statesAfterInvocation(Lists.newArrayList(svFirstArg), arguments.get(4), ps, () -> svResult).collect(Collectors.toList());
    assertThat(noParam).hasSize(1);
    psResult = noParam.iterator().next();
    assertThat(psResult.getConstraint(svFirstArg, ObjectConstraint.class)).isEqualTo(ObjectConstraint.NOT_NULL);
    // null param, contradiction, no resulting program state
    ps = ProgramState.EMPTY_STATE.addConstraint(svFirstArg, ObjectConstraint.NULL);
    Collection<ProgramState> nullParam = yield.statesAfterInvocation(Lists.newArrayList(svFirstArg, svVarArg1), arguments.get(5), ps, () -> svResult).collect(Collectors.toList());
    assertThat(nullParam).isEmpty();
}
Also used : MethodTree(org.sonar.plugins.java.api.tree.MethodTree) ArrayList(java.util.ArrayList) ClassTree(org.sonar.plugins.java.api.tree.ClassTree) IdentifierTree(org.sonar.plugins.java.api.tree.IdentifierTree) ProgramState(org.sonar.java.se.ProgramState) SquidClassLoader(org.sonar.java.bytecode.loader.SquidClassLoader) SECheck(org.sonar.java.se.checks.SECheck) JavaFileScannerContext(org.sonar.plugins.java.api.JavaFileScannerContext) CompilationUnitTree(org.sonar.plugins.java.api.tree.CompilationUnitTree) ClassTree(org.sonar.plugins.java.api.tree.ClassTree) IdentifierTree(org.sonar.plugins.java.api.tree.IdentifierTree) ExpressionTree(org.sonar.plugins.java.api.tree.ExpressionTree) Tree(org.sonar.plugins.java.api.tree.Tree) MethodInvocationTree(org.sonar.plugins.java.api.tree.MethodInvocationTree) MethodTree(org.sonar.plugins.java.api.tree.MethodTree) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) SymbolicValue(org.sonar.java.se.symbolicvalues.SymbolicValue) CompilationUnitTree(org.sonar.plugins.java.api.tree.CompilationUnitTree) SemanticModel(org.sonar.java.resolve.SemanticModel) SETestUtils.createSymbolicExecutionVisitor(org.sonar.java.se.SETestUtils.createSymbolicExecutionVisitor) SymbolicExecutionVisitor(org.sonar.java.se.SymbolicExecutionVisitor) MethodSymbol(org.sonar.plugins.java.api.semantic.Symbol.MethodSymbol) SETestUtils.mockMethodBehavior(org.sonar.java.se.SETestUtils.mockMethodBehavior) SETestUtils.getMethodBehavior(org.sonar.java.se.SETestUtils.getMethodBehavior) File(java.io.File) Test(org.junit.Test)

Example 4 with JavaFileScannerContext

use of org.sonar.plugins.java.api.JavaFileScannerContext in project sonar-java by SonarSource.

the class JavaAstScannerTest method should_handle_analysis_cancellation.

@Test
public void should_handle_analysis_cancellation() throws Exception {
    JavaFileScanner visitor = spy(new JavaFileScanner() {

        @Override
        public void scanFile(JavaFileScannerContext context) {
        // do nothing
        }
    });
    SonarComponents sonarComponents = mock(SonarComponents.class);
    when(sonarComponents.analysisCancelled()).thenReturn(true);
    JavaAstScanner scanner = new JavaAstScanner(JavaParser.createParser(), sonarComponents);
    scanner.setVisitorBridge(new VisitorsBridge(Lists.newArrayList(visitor), Lists.newArrayList(), sonarComponents));
    scanner.scan(ImmutableList.of(new File("src/test/files/metrics/NoSonar.java")));
    verifyZeroInteractions(visitor);
}
Also used : SonarComponents(org.sonar.java.SonarComponents) JavaFileScannerContext(org.sonar.plugins.java.api.JavaFileScannerContext) JavaFileScanner(org.sonar.plugins.java.api.JavaFileScanner) VisitorsBridge(org.sonar.java.model.VisitorsBridge) DefaultInputFile(org.sonar.api.batch.fs.internal.DefaultInputFile) File(java.io.File) Test(org.junit.Test)

Example 5 with JavaFileScannerContext

use of org.sonar.plugins.java.api.JavaFileScannerContext in project sonar-java by SonarSource.

the class StringLiteralDuplicatedCheck method scanFile.

@Override
public void scanFile(JavaFileScannerContext context) {
    occurrences.clear();
    constants.clear();
    scan(context.getTree());
    for (String entry : occurrences.keySet()) {
        Collection<LiteralTree> literalTrees = occurrences.get(entry);
        int literalOccurrence = literalTrees.size();
        if (constants.containsKey(entry)) {
            VariableTree constant = constants.get(entry);
            List<LiteralTree> duplications = literalTrees.stream().filter(literal -> literal.parent() != constant).collect(Collectors.toList());
            context.reportIssue(this, duplications.iterator().next(), "Use already-defined constant '" + constant.simpleName() + "' instead of duplicating its value here.", secondaryLocations(duplications.subList(1, duplications.size())), literalOccurrence);
        } else if (literalOccurrence >= threshold) {
            context.reportIssue(this, literalTrees.iterator().next(), "Define a constant instead of duplicating this literal " + entry + " " + literalOccurrence + " times.", secondaryLocations(literalTrees), literalOccurrence);
        }
    }
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) LiteralTree(org.sonar.plugins.java.api.tree.LiteralTree) Modifier(org.sonar.plugins.java.api.tree.Modifier) RuleProperty(org.sonar.check.RuleProperty) Collection(java.util.Collection) BaseTreeVisitor(org.sonar.plugins.java.api.tree.BaseTreeVisitor) JavaFileScanner(org.sonar.plugins.java.api.JavaFileScanner) HashMap(java.util.HashMap) Tree(org.sonar.plugins.java.api.tree.Tree) Multimap(com.google.common.collect.Multimap) ModifiersUtils(org.sonar.java.model.ModifiersUtils) Collectors(java.util.stream.Collectors) JavaFileScannerContext(org.sonar.plugins.java.api.JavaFileScannerContext) ExpressionTree(org.sonar.plugins.java.api.tree.ExpressionTree) VariableTree(org.sonar.plugins.java.api.tree.VariableTree) List(java.util.List) Map(java.util.Map) Rule(org.sonar.check.Rule) AnnotationTree(org.sonar.plugins.java.api.tree.AnnotationTree) MethodTree(org.sonar.plugins.java.api.tree.MethodTree) VariableTree(org.sonar.plugins.java.api.tree.VariableTree) LiteralTree(org.sonar.plugins.java.api.tree.LiteralTree)

Aggregations

JavaFileScannerContext (org.sonar.plugins.java.api.JavaFileScannerContext)7 File (java.io.File)3 SymbolicExecutionVisitor (org.sonar.java.se.SymbolicExecutionVisitor)3 Tree (org.sonar.plugins.java.api.tree.Tree)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Test (org.junit.Test)2 SquidClassLoader (org.sonar.java.bytecode.loader.SquidClassLoader)2 JavaFileScanner (org.sonar.plugins.java.api.JavaFileScanner)2 CompilationUnitTree (org.sonar.plugins.java.api.tree.CompilationUnitTree)2 ExpressionTree (org.sonar.plugins.java.api.tree.ExpressionTree)2 MethodInvocationTree (org.sonar.plugins.java.api.tree.MethodInvocationTree)2 MethodTree (org.sonar.plugins.java.api.tree.MethodTree)2 ArrayListMultimap (com.google.common.collect.ArrayListMultimap)1 ImmutableList (com.google.common.collect.ImmutableList)1 Multimap (com.google.common.collect.Multimap)1 RecognitionException (com.sonar.sslr.api.RecognitionException)1 InterruptedIOException (java.io.InterruptedIOException)1