@Override public MethodArgument[] visitMethodInvocation(MethodInvocationTree node, Object p) { if (!methodInvocation || offset != positions.getEndPosition(tree, node.getMethodSelect())) { return super.visitMethodInvocation(node, p); /*MethodArgument[] r = scan(node.getTypeArguments(), p); r = scanAndReduce(node.getMethodSelect(), p, r); r = scanAndReduce(node.getArguments(), p, r); return r;*/ } List<? extends ExpressionTree> args = node.getArguments(); List<? extends Tree> argTypes = node.getTypeArguments(); /*int n = args.size(); arguments = new MethodArgument[n]; for (int i = 0; i < n; i++) { arguments[i] = new MethodArgument(args.get(i).toString(), argTypes.get(i).toString()); } return arguments;*/ arguments = composeArguments(args, argTypes); return arguments; }
private void dotExpressionUpToArgs(ExpressionTree expression, Optional<BreakTag> tyargTag) { expression = getArrayBase(expression); switch (expression.getKind()) { case MEMBER_SELECT: MemberSelectTree fieldAccess = (MemberSelectTree) expression; visit(fieldAccess.getIdentifier()); break; case METHOD_INVOCATION: MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; if (!methodInvocation.getTypeArguments().isEmpty()) { builder.open(plusFour); addTypeArguments(methodInvocation.getTypeArguments(), ZERO); // TODO(jdd): Should indent the name -4. builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, tyargTag); builder.close(); } visit(getMethodName(methodInvocation)); break; case IDENTIFIER: visit(((IdentifierTree) expression).getName()); break; default: scan(expression, null); break; } }
private static MethodTree createMethod(WorkingCopy wc, MethodInfo mInfo) { TreeMaker make = wc.getTreeMaker(); TypeInfo[] pTypes = mInfo.getParameterTypes(); String[] pNames = mInfo.getParameterNames(); List<VariableTree> params = new ArrayList<VariableTree>(); for (int i = 0 ; pTypes != null && i < pTypes.length; i++) { VariableTree vtree = createVariable(wc, pNames[i], pTypes[i]); params.add(vtree); } TypeInfo[] excepTypes = mInfo.getExceptionTypes(); List<ExpressionTree> throwsList = new ArrayList<ExpressionTree>(); for (int i = 0 ; excepTypes != null && i < excepTypes.length; i++) { throwsList.add((ExpressionTree)createType(wc, excepTypes[i])); } String body = mInfo.getMethodBodyText(); if(body == null) { body = ""; } MethodTree mtree = make.Method(createModifiers(wc, mInfo.getModifiers(), mInfo.getAnnotations()), mInfo.getName(), createType(wc, mInfo.getReturnType()), Collections.<TypeParameterTree>emptyList(), params, throwsList, "{" + body + "}", null ); // if(mInfo.getCommentText() != null) { // Comment comment = Comment.create(Comment.Style.JAVADOC, -2, // -2, -2, mInfo.getCommentText()); // make.addComment(mtree, comment, true); // } return mtree; }
/** * Defines a new method as event handler, and marks it with @FXML annotation. * * @param h handler definition */ private void defineNewHandler(CharSequence handlerName, TypeElement eventType) { TreeMaker mk = wcopy.getTreeMaker(); // @FXML private void {handlerName}({eventType} event); MethodTree handler = mk.Method( mk.Modifiers(Collections.singleton(Modifier.PRIVATE), Collections.singletonList(fxmlAnnotationTree) ), handlerName, mk.PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), Collections.singletonList( mk.Variable( mk.Modifiers(Collections.<Modifier>emptySet()), "event", mk.Type(eventType.asType()), null) ), Collections.<ExpressionTree>emptyList(), mk.Block(Collections.<StatementTree>emptyList(), false), null); // add to class controllerClass = genUtils().insertClassMember(controllerClass, handler); addMethod(handlerName.toString(), eventType.asType()); }
protected ClassTree generateStubTestMethod(ClassTree tstClass, String testMethodName, WorkingCopy workingCopy) { List<? extends Tree> tstMembersOrig = tstClass.getMembers(); List<Tree> tstMembers = new ArrayList<Tree>(tstMembersOrig.size() + 4); tstMembers.addAll(tstMembersOrig); List<ExpressionTree> throwsList = Collections.emptyList(); MethodTree method = composeNewTestMethod( STUB_TEST_NAME, generateStubTestMethodBody(workingCopy), throwsList, workingCopy); tstMembers.add(method); ClassTree newClass = workingCopy.getTreeMaker().Class( tstClass.getModifiers(), tstClass.getSimpleName(), tstClass.getTypeParameters(), tstClass.getExtendsClause(), (List<? extends ExpressionTree>) tstClass.getImplementsClause(), tstMembers); return newClass; }
/** * 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; }
/** * Output a "regular" chain of dereferences, possibly in builder-style. Break before every dot. * * @param items in the chain * @param needDot whether a leading dot is needed */ private void visitRegularDot(List<ExpressionTree> items, boolean needDot) { boolean trailingDereferences = items.size() > 1; boolean needDot0 = needDot; if (!needDot0) { builder.open(plusFour); } // don't break after the first element if it is every small, unless the // chain starts with another expression int minLength = indentMultiplier * 4; int length = needDot0 ? minLength : 0; for (ExpressionTree e : items) { if (needDot) { if (length > minLength) { builder.breakOp(FillMode.UNIFIED, "", ZERO); } token("."); length++; } if (!fillFirstArgument(e, items, trailingDereferences ? ZERO : minusFour)) { BreakTag tyargTag = genSym(); dotExpressionUpToArgs(e, Optional.of(tyargTag)); Indent tyargIndent = Indent.If.make(tyargTag, plusFour, ZERO); dotExpressionArgsAndParen( e, tyargIndent, (trailingDereferences || needDot) ? plusFour : ZERO); } length += getLength(e, getCurrentPath()); needDot = true; } if (!needDot0) { builder.close(); } }
/** */ @Override protected ClassTree composeNewTestClass(WorkingCopy workingCopy, String name, List<? extends Tree> members) { final TreeMaker maker = workingCopy.getTreeMaker(); ModifiersTree modifiers = maker.Modifiers( Collections.<Modifier>singleton(PUBLIC)); return maker.Class( modifiers, //modifiers name, //name Collections.<TypeParameterTree>emptyList(),//type params null, //extends Collections.<ExpressionTree>emptyList(), //implements members); //members }
private void visitPackage( ExpressionTree packageName, List<? extends AnnotationTree> packageAnnotations) { if (!packageAnnotations.isEmpty()) { for (AnnotationTree annotation : packageAnnotations) { builder.forcedBreak(); scan(annotation, null); } builder.forcedBreak(); } builder.open(plusFour); token("package"); builder.space(); visitName(packageName); builder.close(); token(";"); }
/** * Creates a constructor which assigns its parameters to fields with the * same names. For example it can be used to generate: * * <pre> * public void Constructor(String field1, Object field2) { * this.field1 = field1; * this.field2 = field2; * } * </pre> * * @param modifiersTree the constructor modifiers. * @param constructorName the constructor name; cannot be null, it's not used inside except for assertion since 2007 (or before, TODO: remove?) * @param parameters the constructor parameters; cannot be null. * @return the new constructor; never null. */ public MethodTree createAssignmentConstructor(ModifiersTree modifiersTree, String constructorName, List<VariableTree> parameters) { Parameters.notNull("modifiersTree", modifiersTree); Parameters.javaIdentifier("constructorName", constructorName); // NOI18N Parameters.notNull("parameters", parameters); // NOI18N StringBuilder body = new StringBuilder(parameters.size() * 30); body.append("{"); // NOI18N for (VariableTree parameter : parameters) { String parameterName = parameter.getName().toString(); body.append("this." + parameterName + " = " + parameterName + ";"); // NOI18N } body.append("}"); // NOI18N TreeMaker make = getTreeMaker(); return make.Constructor( modifiersTree, Collections.<TypeParameterTree>emptyList(), parameters, Collections.<ExpressionTree>emptyList(), body.toString()); }
boolean visitSingleMemberAnnotation(AnnotationTree node) { if (node.getArguments().size() != 1) { return false; } ExpressionTree value = Iterables.getOnlyElement(node.getArguments()); if (value.getKind() == ASSIGNMENT) { return false; } boolean isArrayInitializer = value.getKind() == NEW_ARRAY; builder.open(isArrayInitializer ? ZERO : plusFour); token("@"); scan(node.getAnnotationType(), null); token("("); if (!isArrayInitializer) { builder.breakOp(); } scan(value, null); builder.close(); token(")"); return true; }
@Override protected void performRewrite(TransformationContext ctx) { WorkingCopy wc = ctx.getWorkingCopy(); TreePath tp = ctx.getPath(); TypeMirror targetType = this.type.resolve(wc); if (targetType == null) { //XXX: log return ; } TreeMaker make = wc.getTreeMaker(); ExpressionTree nue = make.TypeCast(make.Type(targetType), (ExpressionTree) tp.getLeaf()); if (JavaFixUtilities.requiresParenthesis(tp.getLeaf(), tp.getLeaf(), nue)) { nue = make.TypeCast(make.Type(targetType), make.Parenthesized((ExpressionTree) tp.getLeaf())); } wc.rewrite(tp.getLeaf(), nue); }
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); } } } } }
@Override protected void performRewrite(TransformationContext ctx) throws Exception { TreePath p = ctx.getPath(); if (p.getLeaf().getKind() != Tree.Kind.NEW_CLASS) { return; } NewClassTree origNct = (NewClassTree)p.getLeaf(); if (origNct.getArguments().size() != 1) { return; } NewClassTree nct = GeneratorUtilities.get(ctx.getWorkingCopy()).importComments(origNct, ctx.getWorkingCopy().getCompilationUnit()); ExpressionTree charArg = nct.getArguments().get(0); TreeMaker mk = ctx.getWorkingCopy().getTreeMaker(); ExpressionTree newExpr = mk.NewClass(nct.getEnclosingExpression(), (List<ExpressionTree>)nct.getTypeArguments(), nct.getIdentifier(), Collections.<ExpressionTree>emptyList(), nct.getClassBody()); Tree replace = mk.MethodInvocation( Collections.<ExpressionTree>emptyList(), mk.MemberSelect(newExpr, "append"), // NOI18N Collections.singletonList(charArg)); ctx.getWorkingCopy().rewrite(nct, replace); }
/** * In the numeric case, accept both primitives and boxed types. Each boxed type is * convertible to the appropriate primitive, and all primitive types are assignable to double. */ private boolean isCorrectType(ExpressionTree t) { if (currentMatches) { return true; } TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath()); switch (tm.getKind()) { case BOOLEAN: return logical; case BYTE: case DOUBLE: case FLOAT: case INT: case LONG: case SHORT: return !logical; case DECLARED: // can be converted to primitive return info.getTypes().isAssignable(tm, info.getTypes().getPrimitiveType(TypeKind.DOUBLE)); default: return false; } }
private List<TypeMirror> computeActualInvocationTypes(AnalyzeTask at, List<? extends ExpressionTree> arguments, TreePath currentArgument) { if (currentArgument == null) return null; int paramIndex = arguments.indexOf(currentArgument.getLeaf()); if (paramIndex == (-1)) return null; List<TypeMirror> actuals = new ArrayList<>(); for (ExpressionTree arg : arguments.subList(0, paramIndex)) { actuals.add(at.trees().getTypeMirror(new TreePath(currentArgument.getParentPath(), arg))); } return actuals; }
private static StatementTree createRethrowAsRuntimeExceptionStatement(WorkingCopy info, TreeMaker make, String name) { if (!ErrorFixesFakeHint.isRethrowAsRuntimeException(ErrorFixesFakeHint.getPreferences(info.getFileObject(), FixKind.SURROUND_WITH_TRY_CATCH))) { return null; } TypeElement runtimeException = info.getElements().getTypeElement("java.lang.RuntimeException"); if (runtimeException == null) { return null; } ExpressionTree exceptionName = make.QualIdent(runtimeException); StatementTree result = make.Throw(make.NewClass(null, Collections.<ExpressionTree>emptyList(), exceptionName, Arrays.asList(make.Identifier(name)), null)); info.tag(exceptionName, Utilities.TAG_SELECT); return result; }
void visitVariables( List<VariableTree> fragments, DeclarationKind declarationKind, Direction annotationDirection) { if (fragments.size() == 1) { VariableTree fragment = fragments.get(0); declareOne( declarationKind, annotationDirection, Optional.of(fragment.getModifiers()), fragment.getType(), VarArgsOrNot.fromVariable(fragment), ImmutableList.<AnnotationTree>of(), fragment.getName(), "", "=", Optional.fromNullable(fragment.getInitializer()), Optional.of(";"), Optional.<ExpressionTree>absent(), Optional.fromNullable(variableFragmentDims(true, 0, fragment.getType()))); } else { declareMany(fragments, annotationDirection); } }
public void testWrapMethod2() throws Exception { String code = "package hierbas.del.litoral;\n\n" + "import java.util.concurrent.atomic.AtomicBoolean;\n\n" + "public class Test {\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); ExpressionTree parsed = workingCopy.getTreeUtilities().parseExpression("new Object() { private void test(int a, int b, int c) throws java.io.FileNotFoundException, java.net.MalformedURLException { } }", new SourcePositions[1]); parsed = GeneratorUtilities.get(workingCopy).importFQNs(parsed); MethodTree method = (MethodTree) ((NewClassTree) parsed).getClassBody().getMembers().get(0); workingCopy.rewrite(clazz, make.addClassMember(clazz, method)); } }, FmtOptions.wrapMethodParams, WrapStyle.WRAP_ALWAYS.name(), FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_ALWAYS.name(), FmtOptions.wrapThrowsList, WrapStyle.WRAP_ALWAYS.name()); }
public void testWrapMethod3() throws Exception { String code = "package hierbas.del.litoral;\n\n" + "import java.util.concurrent.atomic.AtomicBoolean;\n\n" + "public class Test {\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); ExpressionTree parsed = workingCopy.getTreeUtilities().parseExpression("new Object() { public <T> void test(java.lang.Class<T> c) { } }", new SourcePositions[1]); parsed = GeneratorUtilities.get(workingCopy).importFQNs(parsed); MethodTree method = (MethodTree) ((NewClassTree) parsed).getClassBody().getMembers().get(0); workingCopy.rewrite(clazz, make.addClassMember(clazz, method)); } }, FmtOptions.wrapMethodParams, WrapStyle.WRAP_ALWAYS.name(), FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_ALWAYS.name(), FmtOptions.wrapThrowsList, WrapStyle.WRAP_ALWAYS.name()); }
public Void visitClass(ClassTree node, Boolean p) { TypeElement te = (TypeElement)model.getElement(node); if (te != null) { List<Tree> members = new ArrayList<Tree>(); for(Tree m : node.getMembers()) members.add(m); members.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", make.PrimitiveType(TypeKind.INT), null)); ClassTree decl = make.Class(node.getModifiers(), node.getSimpleName(), node.getTypeParameters(), node.getExtendsClause(), (List<ExpressionTree>)node.getImplementsClause(), members); model.setElement(decl, te); model.setType(decl, model.getType(node)); model.setPos(decl, model.getPos(node)); copy.rewrite(node, decl); } return null; }
private boolean isIterbale(ExpressionTree expression) { TypeMirror tm = workingCopy.getTrees().getTypeMirror(TreePath.getPath(workingCopy.getCompilationUnit(), expression)); if (!Utilities.isValidType(tm)) { return false; } if (tm.getKind() == TypeKind.ARRAY) { return false; } else { tm = workingCopy.getTypes().erasure(tm); TypeElement typeEl = workingCopy.getElements().getTypeElement("java.util.Collection"); if (typeEl != null) { TypeMirror collection = typeEl.asType(); collection = workingCopy.getTypes().erasure(collection); if (this.workingCopy.getTypes().isSubtype(tm, collection)) { return true; } } } return false; }
@Override public Description matchBinary(BinaryTree tree, VisitorState state) { ExpressionTree leftOperand = tree.getLeftOperand(); ExpressionTree rightOperand = tree.getRightOperand(); Type leftType = ASTHelpers.getType(leftOperand); Type rightType = ASTHelpers.getType(rightOperand); if (leftType == null || rightType == null) { throw new RuntimeException(); } if (leftType.isPrimitive() && !rightType.isPrimitive()) { return doUnboxingCheck(state, rightOperand); } if (rightType.isPrimitive() && !leftType.isPrimitive()) { return doUnboxingCheck(state, leftOperand); } return Description.NO_MATCH; }
@Override public Number visitMethod(MethodTree node, Void p) { String name = node.getName().toString(); String newName = name; if (name.startsWith("$")) { if (parameterNames.containsKey(name)) { newName = parameterNames.get(name); } } List<? extends TypeParameterTree> typeParams = resolveMultiParameters(node.getTypeParameters()); List<? extends VariableTree> params = resolveMultiParameters(node.getParameters()); List<? extends ExpressionTree> thrown = resolveMultiParameters(node.getThrows()); MethodTree nue = make.Method(node.getModifiers(), newName, node.getReturnType(), typeParams, params, thrown, node.getBody(), (ExpressionTree) node.getDefaultValue()); rewrite(node, nue); return super.visitMethod(nue, p); }
private ExpressionTree rewriteNewClass(TreePath p) { ExpressionTree expr = (ExpressionTree) p.getLeaf(); NewClassTree nct = (NewClassTree) expr; Element el = wc.getTrees().getElement(p); if (el != null && el.getKind() == ElementKind.CONSTRUCTOR) { ExecutableElement ee = (ExecutableElement) el; if (ee.getParameters().isEmpty()) { // ctor without parameters, remove return null; } TypeMirror argType = ee.getParameters().get(0).asType(); if (argType.getKind() == TypeKind.DECLARED) { ExpressionTree a = nct.getArguments().get(0); gu.copyComments(expr, a, true); gu.copyComments(expr, a, false); wc.rewrite(expr, a); return a; } return null; } return expr; }
public void testRemoveLastThrows() throws IOException { System.err.println("testRemoveLastThrows"); process( new Transformer<Void, Object>() { public Void visitMethod(MethodTree node, Object p) { super.visitMethod(node, p); if ("fooMethod".contentEquals(node.getName())) { // just to test the method ExpressionTree lastThrows = node.getThrows().get(1); MethodTree copy = make.removeMethodThrows(node, lastThrows); this.copy.rewrite(node, copy); } return null; } } ); assertFiles("testRemoveLastThrows.pass"); }
private static VariableTree addInit ( final WorkingCopy wc, final VariableTree var, final ExpressionTree init) { final ExpressionTree currentInit = var.getInitializer(); if (currentInit.getKind() == Kind.NULL_LITERAL) { final VariableTree newVar = wc.getTreeMaker().Variable(var.getModifiers(), var.getName(), var.getType(), init); rewriteCopyComments(wc, var, newVar); return newVar; } else { return var; } }
private ExpressionTree createForFQN(WorkingCopy copy, String fqn) { int dot = fqn.indexOf('.'); if (dot == (-1)) { return copy.getTreeMaker().Identifier(fqn); } else { return copy.getTreeMaker().MemberSelect(createForFQN(copy, fqn.substring(0, dot)), fqn.substring(dot + 1)); } }
public void testPrintMemberReference() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " Runnable r = null;\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " Runnable r = Test::taragui;\n" + " }\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(final WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); final TreeMaker make = workingCopy.getTreeMaker(); new ErrorAwareTreeScanner<Void, Void>() { @Override public Void visitLiteral(LiteralTree node, Void p) { workingCopy.rewrite(node, make.MemberReference(ReferenceMode.INVOKE, make.Identifier("Test"), "taragui", Collections.<ExpressionTree>emptyList())); return super.visitLiteral(node, p); } }.scan(workingCopy.getCompilationUnit(), null); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
protected VariableTree createEntityManagerFactory(String name){ return getTreeMaker().Variable(getTreeMaker().Modifiers( Collections.<Modifier>emptySet(), Collections.<AnnotationTree>emptyList()), name, getTypeTree(ENTITY_MANAGER_FACTORY_FQN), getTreeMaker().MethodInvocation( Collections.<ExpressionTree>emptyList(), getTreeMaker().MemberSelect( getTypeTree("javax.persistence.Persistence"), "createEntityManagerFactory"), // NOI18N Collections.<ExpressionTree>singletonList(getTreeMaker().Literal(getPersistenceUnitName())) ) ); }
public ClassTree generate() { String body = ""; FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()) { body += getEmInitCode(getEntityManagerFactoryFieldInfo()); } body += getInvocationCode(em); ModifiersTree methodModifiers = getTreeMaker().Modifiers( getGenerationOptions().getModifiers(), Collections.<AnnotationTree>emptyList() ); MethodTree newMethod = getTreeMaker().Method( methodModifiers, computeMethodName(), getTreeMaker().PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), getParameterList(), Collections.<ExpressionTree>emptyList(), "{ " + body + "}", null ); return getTreeMaker().addClassMember(getClassTree(), importFQNs(newMethod)); }
public static void addClassAnnotation(WorkingCopy copy, String[] annotations, Object[] annotationAttrs) { TreeMaker maker = copy.getTreeMaker(); ClassTree tree = getTopLevelClassTree(copy); ModifiersTree modifiers = tree.getModifiers(); for (int i = 0; i < annotations.length; i++) { List<ExpressionTree> attrTrees = null; Object attr = annotationAttrs[i]; if (attr != null) { attrTrees = new ArrayList<ExpressionTree>(); if (attr instanceof ExpressionTree) { attrTrees.add((ExpressionTree) attr); } else { attrTrees.add(maker.Literal(attr)); } } else { attrTrees = Collections.<ExpressionTree>emptyList(); } AnnotationTree newAnnotation = maker.Annotation(maker.Identifier(annotations[i]), attrTrees); if (modifiers != null) { modifiers = maker.addModifiersAnnotation(modifiers, newAnnotation); } } copy.rewrite(tree.getModifiers(), modifiers); }
@Override protected void performRewrite(TransformationContext ctx) { WorkingCopy wc = ctx.getWorkingCopy(); TreePath tp = ctx.getPath(); Element element = desiredType.resolve(wc); if (element == null) { Logger.getLogger("org.netbeans.modules.java.hints").log(Level.INFO, "Cannot resolve target element."); return; } ExpressionTree idt = wc.getTreeMaker().QualIdent(element); wc.rewrite(tp.getLeaf(), idt); }
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 List<? extends ExpressionTree> constructTypeList(List<? extends TypeElement> params) { List<ExpressionTree> result = new LinkedList<>(); for (TypeElement e : params) { result.add(make.QualIdent(e)); } return result; }
private int getIndexOfLambdaInArgs(Tree treeToFind, List<? extends ExpressionTree> argsToSearch) { for (int i = 0; i < argsToSearch.size(); i++) { if (argsToSearch.get(i) == treeToFind) { return i; } } return -1; }
/** */ private ExpressionTree generateNoArgConstructorCall(TreeMaker maker, TypeElement cls, CharSequence instanceClsName) { return maker.NewClass( null, //enclosing instance Collections.<ExpressionTree>emptyList(),//type arguments instanceClsName != null ? maker.Identifier(instanceClsName) : maker.QualIdent(cls), //class identifier Collections.<ExpressionTree>emptyList(),//arguments list null); //class body }
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; }
private StatementTree generateEJBCleanUpCode(TreeMaker maker) { IdentifierTree container = maker.Identifier(CONTAINER_VAR_NAME); MethodInvocationTree invocation = maker.MethodInvocation( Collections.<ExpressionTree>emptyList(), maker.MemberSelect(container, "close"), // NOI18N Collections.<ExpressionTree>emptyList() ); return maker.ExpressionStatement(invocation); }