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); } } } } }
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()); }
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()); }
/** * 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; }
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); } }
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)); } }
@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); }
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; }
private static boolean isFirstStatementThisOrSuperCall(@NotNull JCTree.JCBlock body) { List<JCTree.JCStatement> statements = body.getStatements(); if (statements.isEmpty()) { return false; } JCTree.JCStatement expressionCandidate = statements.get(0); if (expressionCandidate instanceof ExpressionStatementTree) { ExpressionStatementTree expression = (ExpressionStatementTree) expressionCandidate; ExpressionTree methodInvocationCandidate = expression.getExpression(); if (methodInvocationCandidate instanceof MethodInvocationTree) { MethodInvocationTree methodInvocation = (MethodInvocationTree) methodInvocationCandidate; ExpressionTree methodSelect = methodInvocation.getMethodSelect(); if (methodSelect != null) { String select = methodSelect.toString(); return "this".equals(select) || "super".equals(select); } } } return false; }
private List<Fix> literalReplacement( MethodInvocationTree methodInvocationTree, VisitorState state, ExpressionTree lhs) { Tree parent = state.getPath().getParentPath().getLeaf(); // If the parent is an ExpressionStatement, the expression value is ignored, so we can delete // the call entirely (or replace removeAll with .clear()). Otherwise, we can't provide a good // replacement. if (parent instanceof ExpressionStatementTree) { Fix fix; if (instanceMethod().anyClass().named("removeAll").matches(methodInvocationTree, state)) { fix = SuggestedFix.replace(methodInvocationTree, lhs + ".clear()"); } else { fix = SuggestedFix.delete(parent); } return ImmutableList.of(fix); } return ImmutableList.of(); }
protected static SuggestedFix buildFix( VisitorState state, SuggestedFix.Builder fix, JCExpression expectedException, List<? extends StatementTree> statements) { fix.addStaticImport("org.junit.Assert.assertThrows"); StringBuilder prefix = new StringBuilder(); prefix.append( String.format("assertThrows(%s, () -> ", state.getSourceForNode(expectedException))); if (statements.size() == 1 && getOnlyElement(statements) instanceof ExpressionStatementTree) { ExpressionTree expression = ((ExpressionStatementTree) getOnlyElement(statements)).getExpression(); fix.prefixWith(expression, prefix.toString()); fix.postfixWith(expression, ")"); } else { prefix.append(" {"); fix.prefixWith(statements.iterator().next(), prefix.toString()); fix.postfixWith(getLast(statements), "});"); } return fix.build(); }
private Optional<Fix> rethrowFix(ImmutableList<CatchTree> catchBlocks, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); catchBlocks.forEach( c -> { // e.g. // fail("message") -> throw new AssertionError("message", cause); // assertWithMessage("message format %s", 42) -> // throw new AssertionError(String.format("message format %s", 42), cause); StatementTree statementTree = getOnlyElement(c.getBlock().getStatements()); MethodInvocationTree methodInvocationTree = (MethodInvocationTree) ((ExpressionStatementTree) statementTree).getExpression(); String message = null; if (message == null && !methodInvocationTree.getArguments().isEmpty()) { message = getMessageOrFormat(methodInvocationTree, state); } if (message != null) { // only catch and rethrow to add additional context, not for raw `fail()` calls fix.replace( statementTree, String.format( "throw new AssertionError(%s, %s);", message, c.getParameter().getName())); } }); return fix.isEmpty() ? Optional.empty() : Optional.of(fix.build()); }
private boolean abortInCatch(CatchTree catchTree, VisitorState state) { List<? extends StatementTree> statements = catchTree.getBlock().getStatements(); if (statements.isEmpty()) { return false; } StatementTree lastStmt = statements.get(statements.size() - 1); if (lastStmt.getKind() == EXPRESSION_STATEMENT) { ExpressionTree et = ((ExpressionStatementTree) lastStmt).getExpression(); Symbol sym = ASTHelpers.getSymbol(et); if (sym == null || !(sym instanceof MethodSymbol)) { return false; } String methodName = sym.getQualifiedName().toString(); String className = sym.owner.getQualifiedName().toString(); // System.out.println("DEBUG: method: " + methodName + ", className: " + className); if (methodName.contains("abort") || methodName.contains("shutdown") || (methodName.equals("exit") && className.equals("java.lang.System"))) { return true; } } return false; }
@Test public void unhandledExceptionsAreReportedWithoutBugParadeLink() throws Exception { @BugPattern(name = "", explanation = "", summary = "", maturity = EXPERIMENTAL, severity = ERROR, category = ONE_OFF) class Throwing extends BugChecker implements ExpressionStatementTreeMatcher { @Override public Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state) { throw new IllegalStateException("test123"); } } compilerBuilder.report(new ErrorProneScanner(new Throwing())); compiler = compilerBuilder.build(); int exitCode = compiler.compile( sources(getClass(), "MultipleTopLevelClassesWithErrors.java", "ExtendedMultipleTopLevelClassesWithErrors.java")); outputStream.flush(); assertThat(outputStream.toString(), exitCode, is(1)); Matcher<Iterable<Diagnostic<JavaFileObject>>> matcher = hasItem( diagnosticMessage(CoreMatchers.<String>allOf( containsString("IllegalStateException: test123"), containsString("unhandled exception was thrown by the Error Prone")))); assertTrue("Error should be reported. " + diagnosticHelper.describe(), matcher.matches(diagnosticHelper.getDiagnostics())); }
/** * @return true if the first statement in the body is a self constructor * invocation within a constructor */ public static final boolean containsThisConstructorInvocation(MethodTree node) { if (!TreeUtils.isConstructor(node) || node.getBody().getStatements().isEmpty()) return false; StatementTree st = node.getBody().getStatements().get(0); if (!(st instanceof ExpressionStatementTree) || !(((ExpressionStatementTree)st).getExpression() instanceof MethodInvocationTree)) return false; MethodInvocationTree invocation = (MethodInvocationTree) ((ExpressionStatementTree)st).getExpression(); return "this".contentEquals(TreeUtils.methodName(invocation)); }
/** * Case 5: get() is preceded by put-if-absent pattern */ private Matcher preceededByIfThenPut(final Element key, final VariableElement map) { return preceededBy(ofKind(Tree.Kind.IF, new Matcher() { @Override public Boolean visitIf(IfTree tree, Void p) { if (isNotContained(key, map, tree.getCondition())) { StatementTree first = firstStatement(tree.getThenStatement()); if (first != null && first.getKind() == Tree.Kind.EXPRESSION_STATEMENT && isInvocationOfPut(key, map, ((ExpressionStatementTree)first).getExpression())) { return true; } } return false; } })); }
/** * @return true if the first statement in the body is a self constructor invocation within a * constructor */ public static final boolean containsThisConstructorInvocation(MethodTree node) { if (!TreeUtils.isConstructor(node) || node.getBody().getStatements().isEmpty()) return false; StatementTree st = node.getBody().getStatements().get(0); if (!(st instanceof ExpressionStatementTree) || !(((ExpressionStatementTree) st).getExpression() instanceof MethodInvocationTree)) { return false; } MethodInvocationTree invocation = (MethodInvocationTree) ((ExpressionStatementTree) st).getExpression(); return "this".contentEquals(TreeUtils.methodName(invocation)); }
@Override public Wrapper visitExpressionStatement(ExpressionStatementTree arg0, Void arg1) { ExpressionTree t = arg0.getExpression(); Wrapper w = null; MethodInvocationTree mi = getMethodInvocation(arg0); if (mi != null) { if (isYieldBreak(mi)) { w = new YieldBreakWrapper(arg0, visit(t, CallMethodWrapper.class)); } else if (isYieldReturn(mi)) { w = new YieldReturnWrapper(arg0, visit(t, CallMethodWrapper.class)); } } if (w == null) { // This is something else, don't care what! w = new ExpressionStatementWrapper(arg0, visit( arg0.getExpression(), ExpressionWrapper.class)); } else { // Found a yield, set the flag! foundYieldStatement = true; } return w; }
/** * 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; }
protected BlockTree generateStubTestMethodBody(WorkingCopy workingCopy) { TreeMaker maker = workingCopy.getTreeMaker(); List<StatementTree> statements = new ArrayList<StatementTree>(8); if (setup.isGenerateDefMethodBody()) { ExpressionStatementTree exprStatementTree = generateDefMethodBody(maker); statements.add(exprStatementTree); } return maker.Block(statements, false); }
@Override public Tree visitExpressionStatement(ExpressionStatementTree tree, Void p) { ExpressionStatementTree n = make.ExpressionStatement(tree.getExpression()); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
public Boolean visitExpressionStatement(ExpressionStatementTree node, TreePath p) { if (p == null) { super.visitExpressionStatement(node, p); return false; } ExpressionStatementTree et = (ExpressionStatementTree) p.getLeaf(); return scan(node.getExpression(), et.getExpression(), p); }
public void testNewClassToFactory() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public void taragui() {\n" + " tests(Integer.MAX_VALUE, new Integer(1));\n" + " }" + " private void test(Integer i1, Integer i2) {}\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public void taragui() {\n" + " tests(Integer.MAX_VALUE, Integer.valueOf(1));\n" + " }" + " private void test(Integer i1, Integer i2) {}\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = 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); MethodInvocationTree mit = (MethodInvocationTree) ((ExpressionStatementTree) method.getBody().getStatements().get(0)).getExpression(); MethodInvocationTree valueOf = make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.Identifier("Integer"), "valueOf"), Collections.singletonList(make.Literal(1))); workingCopy.rewrite(mit.getArguments().get(1), valueOf); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
@Override public Void visitExpressionStatement(ExpressionStatementTree tree, EnumSet<UseTypes> d) { // if (tree instanceof IdentifierTree) { // handlePossibleIdentifier(tree, EnumSet.of(UseTypes.READ)); // } super.visitExpressionStatement(tree, null); return null; }
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; }
@Override public Number visitExpressionStatement(ExpressionStatementTree node, Void p) { CharSequence name = Utilities.getWildcardTreeName(node); if (name != null) { TreePath tp = parameters.get(name.toString()); if (tp != null && StatementTree.class.isAssignableFrom(tp.getLeaf().getKind().asInterface())) { rewrite(node, tp.getLeaf()); return null; } } return super.visitExpressionStatement(node, p); }
@Override public Object visitExpressionStatement(ExpressionStatementTree node, Object p) { boolean count = true; TreePath path = getCurrentPath(); Tree parent = path.getParentPath().getLeaf(); // do not count the update statement in a for-loop if (parent instanceof ForLoopTree) { count = !((ForLoopTree)parent).getUpdate().contains(node); } if (count) { statements++; } return super.visitExpressionStatement(node, p); }
@Override public Object visitMethodInvocation(MethodInvocationTree node, Object p) { TreePath parentPath = getCurrentPath().getParentPath(); if (parentPath != null) { Tree t = parentPath.getLeaf(); // do not count invocations that are a part of expression (expression statement is counted already) if (!ExpressionTree.class.isAssignableFrom(t.getKind().asInterface()) && !ExpressionStatementTree.class.isAssignableFrom(t.getKind().asInterface())) { statements++; } } return super.visitMethodInvocation(node, p); }
@Override public Void visitExpressionStatement(ExpressionStatementTree tree, List<Node> d) { List<Node> below = new ArrayList<Node>(); addCorrespondingType(below); addCorrespondingComments(below); super.visitExpressionStatement(tree, below); d.add(new TreeNode(info, getCurrentPath(), below)); return null; }
private static List<ProspectiveOperation> createProspectiveReducer(StatementTree tree, WorkingCopy workingCopy, OperationType operationType, PreconditionsChecker precond, List<ProspectiveOperation> ls) throws IllegalStateException { ExpressionTree expr = ((ExpressionStatementTree) tree).getExpression(); TreeMaker tm = workingCopy.getTreeMaker(); ProspectiveOperation redOp = null; Tree.Kind opKind = expr.getKind(); if (TreeUtilities.isCompoundAssignementAssignement(opKind)) { redOp = handleCompoundAssignementReducer(tm, expr, operationType, precond, workingCopy, ls, redOp); } else if (TreeUtilities.isPreOrPostfixOp(opKind)) { redOp = handlePreOrPostFixReducer(expr, workingCopy, tm, operationType, precond, ls, redOp); } ls.add(redOp); return ls; }
private Tree getLambdaForMap() { Tree lambdaBody; if (isNumericLiteral(this.correspondingTree)) { lambdaBody = this.correspondingTree; } else { lambdaBody = ((ExpressionStatementTree) this.correspondingTree).getExpression(); } return lambdaBody; }
private void beautifyLazy(Set<Name> needed) { if (needed.isEmpty()) { { if (!this.getNeededVariables().isEmpty()) { this.beautify(this.getNeededVariables()); } else { Set<Name> newSet = new HashSet<Name>(); newSet.add(null); beautifyLazy(newSet); } } } else { Tree currentTree = this.correspondingTree; if (currentTree.getKind() == Tree.Kind.BLOCK) { beautifyBlock(currentTree, needed); } else if (currentTree.getKind() == Tree.Kind.VARIABLE) { beautifyVariable(currentTree, needed); } else if (currentTree.getKind() == Tree.Kind.EXPRESSION_STATEMENT && ((ExpressionStatementTree) currentTree).getExpression().getKind() == Tree.Kind.ASSIGNMENT) { beautifyAssignement(currentTree, needed); } else if (isNumericLiteral(currentTree)) { //do nothing } else { this.correspondingTree = this.addReturn(castToStatementTree(currentTree), getOneFromSet(needed)); } } }
private static boolean isErroneousExpression(StatementTree statement) { if ( statement instanceof ExpressionStatementTree ) { if ( ((ExpressionStatementTree)statement).getExpression().getKind() == Kind.ERRONEOUS ) { return true; } } return false; }
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; }
/** 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; }
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)); }
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"); }
@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 }
@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); } }