com.sun.source.tree.ExpressionStatementTree Java Examples

The following examples show how to use com.sun.source.tree.ExpressionStatementTree. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CheckReturnValueHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerPattern("$method($params$);")
public static ErrorDescription hint(HintContext ctx) {
    Element invoked = ctx.getInfo().getTrees().getElement(new TreePath(ctx.getPath(), ((ExpressionStatementTree) ctx.getPath().getLeaf()).getExpression()));

    if (invoked == null || invoked.getKind() != ElementKind.METHOD || ((ExecutableElement) invoked).getReturnType().getKind() == TypeKind.VOID) return null;

    boolean found = false;

    for (AnnotationMirror am : invoked.getAnnotationMirrors()) {
        String simpleName = am.getAnnotationType().asElement().getSimpleName().toString();

        if ("CheckReturnValue".equals(simpleName)) {
            found = true;
            break;
        }
    }

    if (!found && !checkReturnValueForJDKMethods((ExecutableElement) invoked)) return null;

    String displayName = NbBundle.getMessage(CheckReturnValueHint.class, "ERR_org.netbeans.modules.java.hints.bugs.CheckReturnValueHint");
    
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
 
Example #2
Source File: AssignResultToVariable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatementTree findMatchingMethodInvocation(CompilationInfo info, BlockTree block, int offset) {
    for (StatementTree t : block.getStatements()) {
        if (t.getKind() != Kind.EXPRESSION_STATEMENT) continue;

        long statementStart = info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), t);

        if (offset < statementStart) return null;

        ExpressionStatementTree est = (ExpressionStatementTree) t;
        long statementEnd = info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), t);
        long expressionEnd = info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), est.getExpression());

        if (expressionEnd <= offset && offset < statementEnd) {
            return t;
        }
    }

    return null;
}
 
Example #3
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns default body for the test method. The generated body will
 * contains the following lines:
 * <pre><code>
 * // TODO review the generated test code and remove the default call to fail.
 * fail("The test case is a prototype.");
 * </code></pre>
 * @param maker the tree maker
 * @return an {@literal ExpressionStatementTree} for the generated body.
 * @throws MissingResourceException
 * @throws IllegalStateException
 */
private ExpressionStatementTree generateDefMethodBody(TreeMaker maker)
                    throws MissingResourceException, IllegalStateException {
    String failMsg = NbBundle.getMessage(TestCreator.class,
                               "TestCreator.variantMethods.defaultFailMsg");
    MethodInvocationTree failMethodCall =
        maker.MethodInvocation(
            Collections.<ExpressionTree>emptyList(),
            maker.Identifier("fail"),
            Collections.<ExpressionTree>singletonList(
                                                   maker.Literal(failMsg)));
    ExpressionStatementTree exprStatement =
        maker.ExpressionStatement(failMethodCall);
    if (setup.isGenerateMethodBodyComment()) {
        Comment comment =
            Comment.create(Comment.Style.LINE, -2, -2, -2,
                           NbBundle.getMessage(AbstractTestGenerator.class,
                              "TestCreator.variantMethods.defaultComment"));
        maker.addComment(exprStatement, comment, true);
    }
    return exprStatement;
}
 
Example #4
Source File: ConvertToLambdaConverter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void performRewriteToMemberReference() {
    MethodTree methodTree = getMethodFromFunctionalInterface(newClassTree);
    if (methodTree.getBody() == null || methodTree.getBody().getStatements().size() != 1)
        return;
    Tree tree = methodTree.getBody().getStatements().get(0);
    if (tree.getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
        tree = ((ExpressionStatementTree)tree).getExpression();
    } else if (tree.getKind() == Tree.Kind.RETURN) {
        tree = ((ReturnTree)tree).getExpression();
    } else {
        return;
    }
    Tree changed = null;
    if (tree.getKind() == Tree.Kind.METHOD_INVOCATION) {
        changed = methodInvocationToMemberReference(copy, tree, pathToNewClassTree, methodTree.getParameters(),
                preconditionChecker.needsCastToExpectedType());
    } else if (tree.getKind() == Tree.Kind.NEW_CLASS) {
        changed = newClassToConstructorReference(copy, tree, pathToNewClassTree, methodTree.getParameters(), preconditionChecker.needsCastToExpectedType());
    }
    if (changed != null) {
        copy.rewrite(newClassTree, changed);
    }
}
 
Example #5
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWrapAssignment() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "    public void t(AtomicBoolean ab) {\n" +
        "        new AtomicBoolean();\n" + 
        "    }\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ExpressionStatementTree init = (ExpressionStatementTree) method.getBody().getStatements().get(0);
            AssignmentTree bt = make.Assignment(make.Identifier("ab"), init.getExpression());
            workingCopy.rewrite(init, make.ExpressionStatement(bt));
        }
    }, FmtOptions.wrapAssignOps, WrapStyle.WRAP_IF_LONG.name());
}
 
Example #6
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testVariableInitWrapped() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "    public void t() {\n" +
        "        new AtomicBoolean();\n" + 
        "    }\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ExpressionStatementTree init = (ExpressionStatementTree) method.getBody().getStatements().get(0);
            VariableTree nue = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "ab", make.Type("java.util.concurrent.atomic.AtomicBoolean"), init.getExpression());
            workingCopy.rewrite(init, nue);
        }
    }, FmtOptions.wrapAssignOps, WrapStyle.WRAP_IF_LONG.name());
}
 
Example #7
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
private Symbol.MethodSymbol getSymbolOfSuperConstructor(
    Symbol.MethodSymbol anonClassConstructorSymbol, VisitorState state) {
  // get the statements in the body of the anonymous class constructor
  List<? extends StatementTree> statements =
      getTreesInstance(state).getTree(anonClassConstructorSymbol).getBody().getStatements();
  // there should be exactly one statement, which is an invocation of the super constructor
  if (statements.size() == 1) {
    StatementTree stmt = statements.get(0);
    if (stmt instanceof ExpressionStatementTree) {
      ExpressionTree expression = ((ExpressionStatementTree) stmt).getExpression();
      if (expression instanceof MethodInvocationTree) {
        return ASTHelpers.getSymbol((MethodInvocationTree) expression);
      }
    }
  }
  throw new IllegalStateException("unexpected anonymous class constructor body " + statements);
}
 
Example #8
Source File: TypeUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testTypeName() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject src  = root.createData("Test.java");
    TestUtilities.copyStringToFile(src, "package test; public class Test { { get().run(); } private <Z extends Exception&Runnable> Z get() { return null; } }");
    JavaSource js = JavaSource.create(ClasspathInfo.create(ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0])), ClassPathSupport.createClassPath(new URL[0]), ClassPathSupport.createClassPath(new URL[0])), src);
    
    js.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController info) throws IOException  {
            info.toPhase(JavaSource.Phase.RESOLVED);
            TypeElement context = info.getTopLevelElements().get(0);
            assertEquals("java.util.List<java.lang.String>[]", info.getTypeUtilities().getTypeName(info.getTreeUtilities().parseType("java.util.List<java.lang.String>[]", context), TypeUtilities.TypeNameOptions.PRINT_FQN));
            assertEquals("List<String>[]", info.getTypeUtilities().getTypeName(info.getTreeUtilities().parseType("java.util.List<java.lang.String>[]", context)));
            assertEquals("java.util.List<java.lang.String>...", info.getTypeUtilities().getTypeName(info.getTreeUtilities().parseType("java.util.List<java.lang.String>[]", context), TypeUtilities.TypeNameOptions.PRINT_FQN, TypeUtilities.TypeNameOptions.PRINT_AS_VARARG));
            assertEquals("List<String>...", info.getTypeUtilities().getTypeName(info.getTreeUtilities().parseType("java.util.List<java.lang.String>[]", context), TypeUtilities.TypeNameOptions.PRINT_AS_VARARG));
            ClassTree clazz = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);
            BlockTree init = (BlockTree) clazz.getMembers().get(1);
            ExpressionStatementTree var = (ExpressionStatementTree) init.getStatements().get(0);
            ExpressionTree getInvocation = ((MemberSelectTree) ((MethodInvocationTree) var.getExpression()).getMethodSelect()).getExpression();
            TypeMirror intersectionType = info.getTrees().getTypeMirror(info.getTrees().getPath(info.getCompilationUnit(), getInvocation));
            assertEquals("Exception & Runnable", info.getTypeUtilities().getTypeName(intersectionType));
        }
    }, true);
    
}
 
Example #9
Source File: WorkingCopy.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addSyntheticTrees(DiffContext diffContext, Tree node) {
    if (node == null) return ;
    
    if (((JCTree) node).pos == (-1)) {
        diffContext.syntheticTrees.add(node);
        return ;
    }
    
    if (node.getKind() == Kind.EXPRESSION_STATEMENT) {
        ExpressionTree est = ((ExpressionStatementTree) node).getExpression();

        if (est.getKind() == Kind.METHOD_INVOCATION) {
            ExpressionTree select = ((MethodInvocationTree) est).getMethodSelect();

            if (select.getKind() == Kind.IDENTIFIER && ((IdentifierTree) select).getName().contentEquals("super")) {
                if (getTreeUtilities().isSynthetic(diffContext.origUnit, node)) {
                    diffContext.syntheticTrees.add(node);
                }
            }
        }
    }
}
 
Example #10
Source File: ProspectiveOperation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void beautifyAssignement(Tree currentTree, Set<Name> needed) {
    AssignmentTree assigned = (AssignmentTree) ((ExpressionStatementTree) currentTree).getExpression();
    ExpressionTree variable = assigned.getVariable();
    if (variable.getKind() == Tree.Kind.IDENTIFIER) {
        IdentifierTree id = (IdentifierTree) variable;

        if (needed.contains(id.getName())) {
            this.correspondingTree = treeMaker.ExpressionStatement(assigned.getExpression());
        } else {

            this.correspondingTree = this.addReturn(castToStatementTree(currentTree), getOneFromSet(needed));
        }
    } else {
        this.correspondingTree = this.addReturn(castToStatementTree(currentTree), getOneFromSet(needed));
    }
}
 
Example #11
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }

  if (tree.getExpression().getKind().equals(Kind.METHOD_INVOCATION)) {
    MethodInvocationTree mit = (MethodInvocationTree) tree.getExpression();
    API api = getXPAPI(mit);
    if (api.equals(API.DELETE_METHOD)) {
      Description.Builder builder = buildDescription(tree);
      SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
      fixBuilder.delete(tree);
      decrementAllSymbolUsages(tree, state, fixBuilder);
      builder.addFix(fixBuilder.build());
      endPos = state.getEndPosition(tree);
      return builder.build();
    }
  }
  return Description.NO_MATCH;
}
 
Example #12
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** In case statement is an Assignment, replace it with variable declaration */
private boolean initExpression(StatementTree statement, TreeMaker make, final String name, TypeMirror proposedType, final WorkingCopy wc, TreePath tp) {
    ExpressionTree exp = ((ExpressionStatementTree) statement).getExpression();
    if (exp.getKind() == Kind.ASSIGNMENT) {
        AssignmentTree at = (AssignmentTree) exp;
        if (at.getVariable().getKind() == Kind.IDENTIFIER && ((IdentifierTree) at.getVariable()).getName().contentEquals(name)) {
            //replace the expression statement with a variable declaration:
            VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(proposedType), at.getExpression());
            vt = Utilities.copyComments(wc, statement, vt);
            wc.rewrite(statement, vt);
            return true;
        }
    }
    return false;
}
 
Example #13
Source File: IntroduceFieldFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean initializeFromMethod(WorkingCopy parameter, TreePath resolved, 
        ExpressionTree expression, String name, TypeMirror tm) {
    TreeMaker make = parameter.getTreeMaker();
    TreePath statementPath = resolved;
    statementPath = TreeUtils.findStatement(statementPath);
    if (statementPath == null) {
        //XXX: well....
        return false;
    }
    ExpressionStatementTree assignment = make.ExpressionStatement(make.Assignment(make.Identifier(name), expression));
    StatementTree statement = (StatementTree) statementPath.getLeaf();
    insertStatement(parameter, statementPath.getParentPath(), statement, assignment, true);
    return true;
}
 
Example #14
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitExpressionStatement(ExpressionStatementTree node, Void unused) {
    sync(node);
    scan(node.getExpression(), null);
    token(";");
    return null;
}
 
Example #15
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void resolveLocalVariable55(final WorkingCopy wc, TreePath tp, TreeMaker make, TypeMirror proposedType) {
    final String name = ((IdentifierTree) tp.getLeaf()).getName().toString();
    TreePath blockPath = findOutmostBlock(tp);

    if (blockPath == null) {
        return;
    }
    
    int index = 0;
    BlockTree block = ((BlockTree) blockPath.getLeaf());
    
    TreePath method = findMethod(tp);

    if (method != null && ((MethodTree) method.getLeaf()).getReturnType() == null && !block.getStatements().isEmpty()) {
        StatementTree stat = block.getStatements().get(0);
        
        if (stat.getKind() == Kind.EXPRESSION_STATEMENT) {
            Element thisMethodEl = wc.getTrees().getElement(method);
            TreePath pathToFirst = new TreePath(new TreePath(new TreePath(method, block), stat), ((ExpressionStatementTree) stat).getExpression());
            Element superCall = wc.getTrees().getElement(pathToFirst);

            if (thisMethodEl != null && superCall != null && thisMethodEl.getKind() == ElementKind.CONSTRUCTOR && superCall.getKind() == ElementKind.CONSTRUCTOR) {
                index = 1;
            }
        }
    }
    
    VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(proposedType), null);
    
    wc.rewrite(block, wc.getTreeMaker().insertBlockStatement(block, index, vt));
}
 
Example #16
Source File: ScanLocalVars.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitExpressionStatement(ExpressionStatementTree node, Void p) {
    if (node == lastStatement) {
        if (!hasReturns) {
            ExpressionTree expression = node.getExpression();
            TypeMirror type = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), expression));
            if (type != null && !TypeKind.ERROR.equals(type.getKind())) {
                returnTypes.add(type);
            }
        }
    }
    return super.visitExpressionStatement(node, p);
}
 
Example #17
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isSuperCtorInvocation(Tree t) {
    if (t.getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
        t = ((ExpressionStatementTree)t).getExpression();
    }
    if (t.getKind() != Tree.Kind.METHOD_INVOCATION) {
        return false;
    }
    MethodInvocationTree mit = (MethodInvocationTree)t;
    if (mit.getMethodSelect() == null || 
        mit.getMethodSelect().getKind() != Tree.Kind.IDENTIFIER) {
        return false;
    }
    return ((IdentifierTree)mit.getMethodSelect()).getName().contentEquals("super");
}
 
Example #18
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends TypeMirror> visitExpressionStatement(ExpressionStatementTree node, Object p) {
    if (theExpression == null) {
        initExpression(getCurrentPath());
    }
    return Collections.singletonList(info.getTypes().getNoType(TypeKind.VOID)); //info.getElements().getTypeElement("java.lang.Void").asType()); // NOI18N
}
 
Example #19
Source File: Lambda.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    final WorkingCopy copy = ctx.getWorkingCopy();
    TypeMirror samType = copy.getTrees().getTypeMirror(ctx.getPath());
    if (samType == null || samType.getKind() != TypeKind.DECLARED) {
        // FIXME: report
        return ;
    }

    LambdaExpressionTree lambda = (LambdaExpressionTree) ctx.getPath().getLeaf();
    Tree tree = lambda.getBody();
    if (tree.getKind() == Tree.Kind.BLOCK) {
        if (((BlockTree)tree).getStatements().size() == 1) {
            tree = ((BlockTree)tree).getStatements().get(0);
            if (tree.getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
                tree = ((ExpressionStatementTree)tree).getExpression();
            } else if (tree.getKind() == Tree.Kind.RETURN) {
                tree = ((ReturnTree)tree).getExpression();
            } else {
                return;
            }
        } else {
            return;
        }
    }

    Tree changed = null;
    if (tree.getKind() == Tree.Kind.METHOD_INVOCATION) {
        changed = ConvertToLambdaConverter.methodInvocationToMemberReference(copy, tree, ctx.getPath(), lambda.getParameters(), false);
    } else if (tree.getKind() == Tree.Kind.NEW_CLASS) {
        changed = ConvertToLambdaConverter.newClassToConstructorReference(copy, tree, ctx.getPath(), lambda.getParameters(), false);
    }
    if (changed != null) {
        copy.rewrite(lambda, changed);
    }
}
 
Example #20
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertExpressionStatement(ExpressionStatementTree node, TreePath parent) {
  TreeNode expr = convert(node.getExpression(), getTreePath(parent, node));
  if (expr instanceof Statement) {
    return expr;
  }
  return new ExpressionStatement().setExpression((Expression) expr);
}
 
Example #21
Source File: ProspectiveOperation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Tree getLambdaForMap() {
    Tree lambdaBody;
    if (isNumericLiteral(this.correspondingTree)) {
        lambdaBody = this.correspondingTree;
    } else {
        lambdaBody = ((ExpressionStatementTree) this.correspondingTree).getExpression();
    }
    return lambdaBody;
}
 
Example #22
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Tree> visitExpressionStatement(ExpressionStatementTree node, ExpressionScanner.ExpressionsInfo p) {
    if (acceptsTree(node)) {
        return scan(node.getExpression(), p);
    } else {
        return null;
    }
}
 
Example #23
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * A safe init method is an instance method that is either private or final (so no overriding is
 * possible)
 *
 * @param stmt the statement
 * @param enclosingClassSymbol symbol for enclosing constructor / initializer
 * @param state visitor state
 * @return element of safe init function if stmt invokes that function; null otherwise
 */
@Nullable
private Element getInvokeOfSafeInitMethod(
    StatementTree stmt, final Symbol.ClassSymbol enclosingClassSymbol, VisitorState state) {
  Matcher<ExpressionTree> invokeMatcher =
      (expressionTree, s) -> {
        if (!(expressionTree instanceof MethodInvocationTree)) {
          return false;
        }
        MethodInvocationTree methodInvocationTree = (MethodInvocationTree) expressionTree;
        Symbol.MethodSymbol symbol = ASTHelpers.getSymbol(methodInvocationTree);
        Set<Modifier> modifiers = symbol.getModifiers();
        Set<Modifier> classModifiers = enclosingClassSymbol.getModifiers();
        if ((symbol.isPrivate()
                || modifiers.contains(Modifier.FINAL)
                || classModifiers.contains(Modifier.FINAL))
            && !symbol.isStatic()
            && !modifiers.contains(Modifier.NATIVE)) {
          // check it's the same class (could be an issue with inner classes)
          if (ASTHelpers.enclosingClass(symbol).equals(enclosingClassSymbol)) {
            // make sure the receiver is 'this'
            ExpressionTree receiver = ASTHelpers.getReceiver(expressionTree);
            return receiver == null || isThisIdentifier(receiver);
          }
        }
        return false;
      };
  if (stmt.getKind().equals(EXPRESSION_STATEMENT)) {
    ExpressionTree expression = ((ExpressionStatementTree) stmt).getExpression();
    if (invokeMatcher.matches(expression, state)) {
      return ASTHelpers.getSymbol(expression);
    }
  }
  return null;
}
 
Example #24
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
private boolean isThisCall(StatementTree statementTree, VisitorState state) {
  if (statementTree.getKind().equals(EXPRESSION_STATEMENT)) {
    ExpressionTree expression = ((ExpressionStatementTree) statementTree).getExpression();
    return Matchers.methodInvocation(THIS_MATCHER).matches(expression, state);
  }
  return false;
}
 
Example #25
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Void visitExpressionStatement(ExpressionStatementTree node, Void unused) {
    sync(node);
    scan(node.getExpression(), null);
    token(";");
    return null;
}
 
Example #26
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean testStatement(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, Tree statement) {
    if (statement == null) {
        return true;
    }
    int start = (int) sp.getStartPosition(cut, statement);
    int end = (int) sp.getEndPosition(cut, statement);
    char ch = text.charAt(end - 1);
    SourceCodeAnalysis.Completeness expected = COMPLETE;
    LineMap lineMap = cut.getLineMap();
    int row = (int) lineMap.getLineNumber(start);
    int column = (int) lineMap.getColumnNumber(start);
    switch (ch) {
        case ',':
        case ';':
            expected = (statement instanceof ExpressionStatementTree)
                    ? COMPLETE
                    : COMPLETE_WITH_SEMI;
            --end;
            break;
        case '}':
            break;
        default:
            writer.write(String.format("Unexpected end: row %d, column %d: '%c' -- %s\n",
                    row, column, ch, text.substring(start, end)));
            return true;
    }
    String unit = text.substring(start, end);
    SourceCodeAnalysis.CompletionInfo ci = getAnalysis().analyzeCompletion(unit);
    if (ci.completeness() != expected) {
        if (expected == COMPLETE_WITH_SEMI && (ci.completeness() == CONSIDERED_INCOMPLETE || ci.completeness() == EMPTY)) {
            writer.write(String.format("Empty statement: row %d, column %d: -- %s\n",
                    start, end, unit));
        } else {
            writer.write(String.format("Expected %s got %s: '%s'  row %d, column %d: -- %s\n",
                    expected, ci.completeness(), unit, row, column, unit));
            return false;
        }
    }
    return true;
}
 
Example #27
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitExpressionStatement(ExpressionStatementTree node, Void unused) {
  sync(node);
  scan(node.getExpression(), null);
  token(";");
  return null;
}
 
Example #28
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isSynthetic(CompilationUnitTree cut, Tree leaf) throws NullPointerException {
    JCTree tree = (JCTree) leaf;

    if (tree.pos == (-1))
        return true;

    if (leaf.getKind() == Kind.METHOD) {
        //check for synthetic constructor:
        return (((JCMethodDecl)leaf).mods.flags & Flags.GENERATEDCONSTR) != 0L;
    }

    //check for synthetic superconstructor call:
    if (cut != null && leaf.getKind() == Kind.EXPRESSION_STATEMENT) {
        ExpressionStatementTree est = (ExpressionStatementTree) leaf;

        if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) {
            MethodInvocationTree mit = (MethodInvocationTree) est.getExpression();

            if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) {
                IdentifierTree it = (IdentifierTree) mit.getMethodSelect();

                if ("super".equals(it.getName().toString())) {
                    return ((JCCompilationUnit) cut).endPositions.getEndPos(tree) == (-1);
                }
            }
        }
    }

    return false;
}
 
Example #29
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitExpressionStatement(ExpressionStatementTree expected, Tree actual) {
  Optional<ExpressionStatementTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getExpression(), other.get().getExpression());
  return null;
}
 
Example #30
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
     * Returns default body for the test method. The generated body will
     * contains the following lines:
     * <pre><code>
     * // TODO review the generated test code and remove the default call to fail.
     * fail("The test case is a prototype.");
     * </code></pre>
     * @param maker the tree maker
     * @return an {@code ExpressionStatementTree} for the generated body.
     * @throws MissingResourceException
     * @throws IllegalStateException
     */
    @NbBundle.Messages({"TestCreator.variantMethods.defaultFailMsg=The test case is a prototype.",
        "TestCreator.variantMethods.defaultComment=TODO review the generated test code and remove the default call to fail."})
    private ExpressionStatementTree generateDefMethodBody(TreeMaker maker)
                        throws MissingResourceException, IllegalStateException {
//        String failMsg = NbBundle.getMessage(TestCreator.class,
//                                   "TestCreator.variantMethods.defaultFailMsg");
        String failMsg = Bundle.TestCreator_variantMethods_defaultFailMsg();
        MethodInvocationTree failMethodCall =
            maker.MethodInvocation(
                Collections.<ExpressionTree>emptyList(),
                maker.Identifier("fail"),
                Collections.<ExpressionTree>singletonList(
                                                       maker.Literal(failMsg)));
        ExpressionStatementTree exprStatement =
            maker.ExpressionStatement(failMethodCall);
        if (setup.isGenerateMethodBodyComment()) {
//            Comment comment =
//                Comment.create(Comment.Style.LINE, -2, -2, -2,
//                               NbBundle.getMessage(AbstractTestGenerator.class,
//                                  "TestCreator.variantMethods.defaultComment"));
            Comment comment =
                Comment.create(Comment.Style.LINE, -2, -2, -2,
                               Bundle.TestCreator_variantMethods_defaultComment());
            maker.addComment(exprStatement, comment, true);
        }
        return exprStatement;
    }