Search in sources :

Example 61 with MethodTree

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

the class JavaAstScannerTest method should_swallow_log_and_report_checks_exceptions_for_symbolic_execution.

@Test
public void should_swallow_log_and_report_checks_exceptions_for_symbolic_execution() {
    JavaAstScanner scanner = new JavaAstScanner(JavaParser.createParser(), null);
    logTester.clear();
    SonarComponents sonarComponent = new SonarComponents(null, context.fileSystem(), null, null, null, null);
    context.setRuntime(SonarRuntimeImpl.forSonarLint(Version.create(6, 7)));
    sonarComponent.setSensorContext(context);
    scanner.setVisitorBridge(new VisitorsBridge(Collections.singletonList(new SECheck() {

        @Override
        public void init(MethodTree methodTree, CFG cfg) {
            throw new NullPointerException("nobody expect the spanish inquisition !");
        }
    }), new ArrayList<>(), sonarComponent, SymbolicExecutionMode.ENABLED_WITHOUT_X_FILE));
    scanner.scan(ImmutableList.of(new File("src/test/resources/se/MethodBehavior.java")));
    assertThat(logTester.logs(LoggerLevel.ERROR)).hasSize(1);
    assertThat(logTester.logs(LoggerLevel.ERROR).get(0)).startsWith("Unable to run check class org.sonar.java.se.SymbolicExecutionVisitor");
    assertThat(sonarComponent.analysisErrors).hasSize(1);
    assertThat(sonarComponent.analysisErrors.get(0).getKind()).isSameAs(AnalysisError.Kind.SE_ERROR);
}
Also used : SonarComponents(org.sonar.java.SonarComponents) SECheck(org.sonar.java.se.checks.SECheck) MethodTree(org.sonar.plugins.java.api.tree.MethodTree) CFG(org.sonar.java.cfg.CFG) ArrayList(java.util.ArrayList) VisitorsBridge(org.sonar.java.model.VisitorsBridge) DefaultInputFile(org.sonar.api.batch.fs.internal.DefaultInputFile) File(java.io.File) Test(org.junit.Test)

Example 62 with MethodTree

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

the class UCFGJavaVisitor method buildUCfg.

private UCFG buildUCfg(MethodTree methodTree, CFG cfg) {
    String signature = signatureFor(methodTree.symbol());
    IdentifierGenerator idGenerator = new IdentifierGenerator(methodTree);
    UCFGBuilder builder = UCFGBuilder.createUCFGForMethod(signature);
    methodTree.parameters().stream().map(p -> idGenerator.lookupIdFor(p.symbol())).map(UCFGBuilder::variableWithId).forEach(builder::addMethodParam);
    BlockBuilder entryBlockBuilder = buildBasicBlock(cfg.entry(), methodTree, idGenerator);
    if (getAnnotatedStringParameters(methodTree).count() > 0) {
        builder.addStartingBlock(buildParameterAnnotationsBlock(methodTree, idGenerator, cfg));
        builder.addBasicBlock(entryBlockBuilder);
    } else {
        builder.addStartingBlock(entryBlockBuilder);
    }
    cfg.blocks().stream().filter(b -> !b.equals(cfg.entry())).forEach(b -> builder.addBasicBlock(buildBasicBlock(b, methodTree, idGenerator)));
    return builder.build();
}
Also used : JavaSymbol(org.sonar.java.resolve.JavaSymbol) Label(org.sonar.ucfg.Label) BaseTreeVisitor(org.sonar.plugins.java.api.tree.BaseTreeVisitor) JavaFileScanner(org.sonar.plugins.java.api.JavaFileScanner) Loggers(org.sonar.api.utils.log.Loggers) MemberSelectExpressionTree(org.sonar.plugins.java.api.tree.MemberSelectExpressionTree) PLUS(org.sonar.plugins.java.api.tree.Tree.Kind.PLUS) Map(java.util.Map) SyntaxToken(org.sonar.plugins.java.api.tree.SyntaxToken) Set(java.util.Set) Collectors(java.util.stream.Collectors) JavaFileScannerContext(org.sonar.plugins.java.api.JavaFileScannerContext) Sets(com.google.common.collect.Sets) List(java.util.List) UCFGtoProtobuf(org.sonar.ucfg.UCFGtoProtobuf) Stream(java.util.stream.Stream) MEMBER_SELECT(org.sonar.plugins.java.api.tree.Tree.Kind.MEMBER_SELECT) UCFGBuilder.variableWithId(org.sonar.ucfg.UCFGBuilder.variableWithId) AssignmentExpressionTree(org.sonar.plugins.java.api.tree.AssignmentExpressionTree) IdentifierTree(org.sonar.plugins.java.api.tree.IdentifierTree) Symbol(org.sonar.plugins.java.api.semantic.Symbol) ASSIGNMENT(org.sonar.plugins.java.api.tree.Tree.Kind.ASSIGNMENT) PLUS_ASSIGNMENT(org.sonar.plugins.java.api.tree.Tree.Kind.PLUS_ASSIGNMENT) UCFG(org.sonar.ucfg.UCFG) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ExpressionTree(org.sonar.plugins.java.api.tree.ExpressionTree) HashSet(java.util.HashSet) BlockBuilder(org.sonar.ucfg.UCFGBuilder.BlockBuilder) VariableTree(org.sonar.plugins.java.api.tree.VariableTree) UCFGBuilder(org.sonar.ucfg.UCFGBuilder) LiteralUtils(org.sonar.java.model.LiteralUtils) Nullable(javax.annotation.Nullable) Logger(org.sonar.api.utils.log.Logger) AnnotationTree(org.sonar.plugins.java.api.tree.AnnotationTree) BinaryExpressionTree(org.sonar.plugins.java.api.tree.BinaryExpressionTree) ReturnStatementTree(org.sonar.plugins.java.api.tree.ReturnStatementTree) LiteralTree(org.sonar.plugins.java.api.tree.LiteralTree) UCFGBuilder.call(org.sonar.ucfg.UCFGBuilder.call) METHOD_INVOCATION(org.sonar.plugins.java.api.tree.Tree.Kind.METHOD_INVOCATION) Tree(org.sonar.plugins.java.api.tree.Tree) Type(org.sonar.plugins.java.api.semantic.Type) File(java.io.File) MethodInvocationTree(org.sonar.plugins.java.api.tree.MethodInvocationTree) LocationInFile(org.sonar.ucfg.LocationInFile) CFG(org.sonar.java.cfg.CFG) VariableReadExtractor(org.sonar.java.cfg.VariableReadExtractor) Preconditions(com.google.common.base.Preconditions) Expression(org.sonar.ucfg.Expression) UCFGBuilder.constant(org.sonar.ucfg.UCFGBuilder.constant) MethodTree(org.sonar.plugins.java.api.tree.MethodTree) UCFGBuilder(org.sonar.ucfg.UCFGBuilder) BlockBuilder(org.sonar.ucfg.UCFGBuilder.BlockBuilder)

Example 63 with MethodTree

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

the class UCFGJavaVisitor method buildBasicBlock.

private UCFGBuilder.BlockBuilder buildBasicBlock(CFG.Block javaBlock, MethodTree methodTree, IdentifierGenerator idGenerator) {
    UCFGBuilder.BlockBuilder blockBuilder = UCFGBuilder.newBasicBlock(String.valueOf(javaBlock.id()), location(javaBlock));
    javaBlock.elements().forEach(e -> buildCall(e, blockBuilder, idGenerator));
    Tree terminator = javaBlock.terminator();
    if (terminator != null && terminator.is(Tree.Kind.RETURN_STATEMENT)) {
        ExpressionTree returnedExpression = ((ReturnStatementTree) terminator).expression();
        Expression retExpr = constant(IdentifierGenerator.CONST);
        if (methodTree.returnType() != null && isString(methodTree.returnType().symbolType())) {
            retExpr = idGenerator.lookupExpressionFor(returnedExpression);
        }
        blockBuilder.ret(retExpr, location(terminator));
        return blockBuilder;
    }
    Set<CFG.Block> successors = javaBlock.successors();
    if (!successors.isEmpty()) {
        blockBuilder.jumpTo(successors.stream().map(b -> UCFGBuilder.createLabel(Integer.toString(b.id()))).toArray(Label[]::new));
        return blockBuilder;
    }
    Preconditions.checkState(javaBlock.id() == 0);
    blockBuilder.ret(constant("implicit return"), location(methodTree.lastToken()));
    return blockBuilder;
}
Also used : UCFGBuilder(org.sonar.ucfg.UCFGBuilder) Expression(org.sonar.ucfg.Expression) Label(org.sonar.ucfg.Label) MemberSelectExpressionTree(org.sonar.plugins.java.api.tree.MemberSelectExpressionTree) AssignmentExpressionTree(org.sonar.plugins.java.api.tree.AssignmentExpressionTree) IdentifierTree(org.sonar.plugins.java.api.tree.IdentifierTree) ExpressionTree(org.sonar.plugins.java.api.tree.ExpressionTree) VariableTree(org.sonar.plugins.java.api.tree.VariableTree) AnnotationTree(org.sonar.plugins.java.api.tree.AnnotationTree) BinaryExpressionTree(org.sonar.plugins.java.api.tree.BinaryExpressionTree) ReturnStatementTree(org.sonar.plugins.java.api.tree.ReturnStatementTree) LiteralTree(org.sonar.plugins.java.api.tree.LiteralTree) Tree(org.sonar.plugins.java.api.tree.Tree) MethodInvocationTree(org.sonar.plugins.java.api.tree.MethodInvocationTree) MethodTree(org.sonar.plugins.java.api.tree.MethodTree) MemberSelectExpressionTree(org.sonar.plugins.java.api.tree.MemberSelectExpressionTree) AssignmentExpressionTree(org.sonar.plugins.java.api.tree.AssignmentExpressionTree) ExpressionTree(org.sonar.plugins.java.api.tree.ExpressionTree) BinaryExpressionTree(org.sonar.plugins.java.api.tree.BinaryExpressionTree) ReturnStatementTree(org.sonar.plugins.java.api.tree.ReturnStatementTree) BlockBuilder(org.sonar.ucfg.UCFGBuilder.BlockBuilder)

Example 64 with MethodTree

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

the class CompareToNotOverloadedCheck method visitNode.

@Override
public void visitNode(Tree tree) {
    MethodTree methodTree = (MethodTree) tree;
    if (hasSemantic() && isCompareToMethod(methodTree) && Boolean.FALSE.equals(methodTree.isOverriding())) {
        ClassJavaType ownerType = (ClassJavaType) methodTree.symbol().owner().type();
        ownerType.superTypes().stream().filter(supertype -> supertype.is("java.lang.Comparable")).findFirst().ifPresent(comparableType -> {
            String name = "Object";
            if (comparableType.isParameterized()) {
                ParametrizedTypeJavaType ptjt = (ParametrizedTypeJavaType) comparableType;
                name = ptjt.substitution(ptjt.typeParameters().get(0)).symbol().name();
            }
            reportIssue(methodTree.parameters().get(0), "Refactor this method so that its argument is of type '" + name + "'.");
        });
    }
}
Also used : ParametrizedTypeJavaType(org.sonar.java.resolve.ParametrizedTypeJavaType) MethodTree(org.sonar.plugins.java.api.tree.MethodTree) ClassJavaType(org.sonar.java.resolve.ClassJavaType)

Example 65 with MethodTree

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

the class DeadStoreCheck method visitNode.

@Override
public void visitNode(Tree tree) {
    if (!hasSemantic()) {
        return;
    }
    MethodTree methodTree = (MethodTree) tree;
    if (methodTree.block() == null) {
        return;
    }
    // TODO(npe) Exclude try statements with finally as CFG is incorrect for those and lead to false positive
    if (hasTryFinallyWithLocalVar(methodTree.block(), methodTree.symbol())) {
        return;
    }
    Symbol.MethodSymbol methodSymbol = methodTree.symbol();
    CFG cfg = CFG.build(methodTree);
    LiveVariables liveVariables = LiveVariables.analyze(cfg);
    // Liveness analysis provides information only for block boundaries, so we should do analysis between elements within blocks
    for (CFG.Block block : cfg.blocks()) {
        checkElements(block, liveVariables.getOut(block), methodSymbol);
    }
}
Also used : MethodTree(org.sonar.plugins.java.api.tree.MethodTree) CFG(org.sonar.java.cfg.CFG) LiveVariables(org.sonar.java.cfg.LiveVariables) Symbol(org.sonar.plugins.java.api.semantic.Symbol)

Aggregations

MethodTree (org.sonar.plugins.java.api.tree.MethodTree)143 Test (org.junit.Test)59 Tree (org.sonar.plugins.java.api.tree.Tree)43 ClassTree (org.sonar.plugins.java.api.tree.ClassTree)39 VariableTree (org.sonar.plugins.java.api.tree.VariableTree)34 Symbol (org.sonar.plugins.java.api.semantic.Symbol)31 IdentifierTree (org.sonar.plugins.java.api.tree.IdentifierTree)30 MethodInvocationTree (org.sonar.plugins.java.api.tree.MethodInvocationTree)27 CompilationUnitTree (org.sonar.plugins.java.api.tree.CompilationUnitTree)23 StatementTree (org.sonar.plugins.java.api.tree.StatementTree)20 Type (org.sonar.plugins.java.api.semantic.Type)19 ExpressionTree (org.sonar.plugins.java.api.tree.ExpressionTree)19 BlockTree (org.sonar.plugins.java.api.tree.BlockTree)18 List (java.util.List)16 ExpressionStatementTree (org.sonar.plugins.java.api.tree.ExpressionStatementTree)16 ReturnStatementTree (org.sonar.plugins.java.api.tree.ReturnStatementTree)15 ArrayList (java.util.ArrayList)14 AssignmentExpressionTree (org.sonar.plugins.java.api.tree.AssignmentExpressionTree)14 NewClassTree (org.sonar.plugins.java.api.tree.NewClassTree)14 JavaFileScannerContext (org.sonar.plugins.java.api.JavaFileScannerContext)12