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; }
public MethodTree createHashCodeMethod(List<VariableTree> fields) { StringBuilder body = new StringBuilder(20 + fields.size() * 30); body.append("{"); // NOI18N body.append("int hash = 0;"); // NOI18N for (VariableTree field : fields) { body.append(createHashCodeLineForField(field)); } body.append("return hash;"); // NOI18N body.append("}"); // NOI18N TreeMaker make = copy.getTreeMaker(); // XXX Javadoc return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC), Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "hashCode", make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body.toString(), null); }
public MethodTree createEqualsMethod(String simpleClassName, List<VariableTree> fields) { StringBuilder body = new StringBuilder(50 + fields.size() * 30); body.append("{"); // NOI18N body.append("// TODO: Warning - this method won't work in the case the id fields are not set\n"); // NOI18N body.append("if (!(object instanceof "); // NOI18N body.append(simpleClassName + ")) {return false;}"); // NOI18N body.append(simpleClassName + " other = (" + simpleClassName + ")object;"); // NOI18N for (VariableTree field : fields) { body.append(createEqualsLineForField(field)); } body.append("return true;"); // NOI18N body.append("}"); // NOI18N TreeMaker make = copy.getTreeMaker(); // XXX Javadoc return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC), Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "equals", make.PrimitiveType(TypeKind.BOOLEAN), Collections.<TypeParameterTree>emptyList(), Collections.singletonList(genUtils.createVariable(scope, "object", "java.lang.Object")), Collections.<ExpressionTree>emptyList(), body.toString(), null); }
public MethodTree createToStringMethod(String fqn, List<VariableTree> fields) { StringBuilder body = new StringBuilder(30 + fields.size() * 30); body.append("{"); // NOI18N body.append("return \"" + fqn + "[ "); // NOI18N for (Iterator<VariableTree> i = fields.iterator(); i.hasNext();) { String fieldName = i.next().getName().toString(); body.append(fieldName + "=\" + " + fieldName + " + \""); //NOI18N body.append(i.hasNext() ? ", " : " ]\";"); //NOI18N } body.append("}"); // NOI18N TreeMaker make = copy.getTreeMaker(); // XXX Javadoc return make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC), Collections.singletonList(genUtils.createAnnotation("java.lang.Override"))), "toString", genUtils.createType("java.lang.String", scope), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body.toString(), null); }
/** * Makes a list of trees representing the given type parameter elements. */ private static List<TypeParameterTree> makeTypeParamsCopy( List<? extends TypeParameterElement> typeParams, TreeMaker maker) { if (typeParams.isEmpty()) { return Collections.emptyList(); } int size = typeParams.size(); if (size == 1) { return Collections.singletonList(makeCopy(typeParams.get(0), maker)); } List<TypeParameterTree> result = new ArrayList(size); for (TypeParameterElement typeParam : typeParams) { result.add(makeCopy(typeParam, maker)); } return result; }
/** * Creates a public static {@code main(String[])} method * with the body taken from settings. * * @param maker {@code TreeMaker} to use for creating the method * @return created {@code main(...)} method, * or {@code null} if the method body would be empty */ private MethodTree createMainMethod(TreeMaker maker) { String initialMainMethodBody = getInitialMainMethodBody(); if (initialMainMethodBody.length() == 0) { return null; } ModifiersTree modifiers = maker.Modifiers( createModifierSet(Modifier.PUBLIC, Modifier.STATIC)); VariableTree param = maker.Variable( maker.Modifiers(Collections.<Modifier>emptySet()), "argList", //NOI18N maker.Identifier("String[]"), //NOI18N null); //initializer - not used in params MethodTree mainMethod = maker.Method( modifiers, //public static "main", //method name "main"//NOI18N maker.PrimitiveType(TypeKind.VOID), //return type "void" Collections.<TypeParameterTree>emptyList(), //type params Collections.<VariableTree>singletonList(param), //method param Collections.<ExpressionTree>emptyList(), //throws-list '{' + initialMainMethodBody + '}', //body text null); //only for annotations return mainMethod; }
/** */ @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 }
/** */ @Override protected MethodTree composeNewTestMethod(String testMethodName, BlockTree testMethodBody, List<ExpressionTree> throwsList, WorkingCopy workingCopy) { TreeMaker maker = workingCopy.getTreeMaker(); return maker.Method( createModifiersTree(ANN_TEST, createModifierSet(PUBLIC), workingCopy), testMethodName, maker.PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), throwsList, testMethodBody, null); //default value - used by annotations }
/** * Does not omit the leading '<', which should be associated with the type name. */ private void typeParametersRest( List<? extends TypeParameterTree> typeParameters, Indent plusIndent) { builder.open(plusIndent); builder.breakOp(); builder.open(ZERO); boolean first = true; for (TypeParameterTree typeParameter : typeParameters) { if (!first) { token(","); builder.breakOp(" "); } scan(typeParameter, null); first = false; } token(">"); builder.close(); builder.close(); }
/** */ protected ClassTree composeNewTestClass(WorkingCopy workingCopy, String name, List<? extends Tree> members) { final TreeMaker maker = workingCopy.getTreeMaker(); ModifiersTree modifiers = maker.Modifiers( Collections.<Modifier>singleton(PUBLIC)); Tree extendsClause = getClassIdentifierTree(TEST_CASE, workingCopy); return maker.Class( modifiers, //modifiers name, //name Collections.<TypeParameterTree>emptyList(),//type params extendsClause, //extends Collections.<ExpressionTree>emptyList(), //implements members); //members }
/** */ protected MethodTree composeNewTestMethod(String testMethodName, BlockTree testMethodBody, List<ExpressionTree> throwsList, WorkingCopy workingCopy) { TreeMaker maker = workingCopy.getTreeMaker(); return maker.Method( maker.Modifiers(createModifierSet(PUBLIC)), testMethodName, maker.PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), throwsList, testMethodBody, null); //default value - used by annotations }
/** * Creates a public static {@literal main(String[])} method * with the body taken from settings. * * @param maker {@literal TreeMaker} to use for creating the method * @return created {@literal main(...)} method, * or {@literal null} if the method body would be empty */ private MethodTree createMainMethod(TreeMaker maker) { String initialMainMethodBody = getInitialMainMethodBody(); if (initialMainMethodBody.length() == 0) { return null; } ModifiersTree modifiers = maker.Modifiers( createModifierSet(Modifier.PUBLIC, Modifier.STATIC)); VariableTree param = maker.Variable( maker.Modifiers(Collections.<Modifier>emptySet()), "argList", //NOI18N maker.Identifier("String[]"), //NOI18N null); //initializer - not used in params MethodTree mainMethod = maker.Method( modifiers, //public static "main", //method name "main"//NOI18N maker.PrimitiveType(TypeKind.VOID), //return type "void" Collections.<TypeParameterTree>emptyList(), //type params Collections.<VariableTree>singletonList(param), //method param Collections.<ExpressionTree>emptyList(), //throws-list '{' + initialMainMethodBody + '}', //body text null); //only for annotations return mainMethod; }
@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); }
@Override public Number visitClass(ClassTree node, Void p) { String name = node.getSimpleName().toString(); String newName = name; if (name.startsWith("$")) { if (parameterNames.containsKey(name)) { newName = parameterNames.get(name); } } List<? extends TypeParameterTree> typeParams = resolveMultiParameters(node.getTypeParameters()); List<? extends Tree> implementsClauses = resolveMultiParameters(node.getImplementsClause()); List<? extends Tree> members = resolveMultiParameters(Utilities.filterHidden(getCurrentPath(), node.getMembers())); Tree extend = resolveOptionalValue(node.getExtendsClause()); ClassTree nue = make.Class(node.getModifiers(), newName, typeParams, extend, implementsClauses, members); rewrite(node, nue); return super.visitClass(nue, p); }
@Override public Void visitTypeParameter(TypeParameterTree node, Void p) { Element el = info.getTrees().getElement(getCurrentPath()); if (toFind.equals(el)) { try { int[] span = treeUtils.findNameSpan(node); if(span != null) { MutablePositionRegion region = createRegion(doc, span[0], span[1]); usages.add(region); } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } return super.visitTypeParameter(node, p); }
/** * 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()); }
private static StringBuilder getTreeInfo(Tree t) { StringBuilder info = new StringBuilder("\n"); //NOI18N if (t != null) { switch (t.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: info.append("CLASS: ").append(((ClassTree) t).getSimpleName().toString()); //NOI18N break; case VARIABLE: info.append("VARIABLE: ").append(((VariableTree) t).getName().toString()); //NOI18N break; case METHOD: info.append("METHOD: ").append(((MethodTree) t).getName().toString()); //NOI18N break; case TYPE_PARAMETER: info.append("TYPE_PARAMETER: ").append(((TypeParameterTree) t).getName().toString()); //NOI18N break; default: info.append("TREE: <unknown>"); //NOI18N break; } } return info; }
/** * 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. * @param parameters the constructor parameters; cannot be null. * @return the new constructor; never null. */ public MethodTree createAssignmentConstructor(ModifiersTree modifiersTree, String constructorName, List 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(int i=0; i < parameters.size();i++ ) { VariableTree parameter = (VariableTree)parameters.get(i); 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()); }
private static MethodTree createHashCodeMethod(WorkingCopy wc, Iterable<? extends VariableElement> hashCodeFields, Scope scope) { TreeMaker make = wc.getTreeMaker(); Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC); int startNumber = generatePrimeNumber(2, 10); int multiplyNumber = generatePrimeNumber(10, 100); List<StatementTree> statements = new ArrayList<>(); //int hash = <startNumber>; statements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "hash", make.PrimitiveType(TypeKind.INT), make.Literal(startNumber))); //NOI18N for (VariableElement ve : hashCodeFields) { TypeMirror tm = ve.asType(); ExpressionTree variableRead = prepareExpression(wc, HASH_CODE_PATTERNS, tm, ve, scope); statements.add(make.ExpressionStatement(make.Assignment(make.Identifier("hash"), make.Binary(Tree.Kind.PLUS, make.Binary(Tree.Kind.MULTIPLY, make.Literal(multiplyNumber), make.Identifier("hash")), variableRead)))); //NOI18N } statements.add(make.Return(make.Identifier("hash"))); //NOI18N BlockTree body = make.Block(statements, false); ModifiersTree modifiers = prepareModifiers(wc, mods,make); return make.Method(modifiers, "hashCode", make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree> emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N }
/** * 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()); }
/** * Creates a new public property getter method. * * @param modifiersTree the method modifiers; cannot be null. * @param propertyType the property type; cannot be null. * @param propertyName the property name; cannot be null. * @return the new method; never null. */ public MethodTree createPropertyGetterMethod(ModifiersTree modifiersTree, String propertyName, Tree propertyType) { Parameters.notNull("modifiersTree", modifiersTree); // NOI18N Parameters.javaIdentifier("propertyName", propertyName); // NOI18N Parameters.notNull("propertyType", propertyType); // NOI18N return getTreeMaker().Method( modifiersTree, createPropertyAccessorName(propertyName, true), propertyType, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{ return " + propertyName + "; }", // NOI18N null); }
public static ClassTree addConstructor(WorkingCopy copy, ClassTree tree, Modifier[] modifiers, String[] parameters, Object[] paramTypes, String bodyText, String comment) { TreeMaker maker = copy.getTreeMaker(); ModifiersTree modifiersTree = createModifiersTree(copy, modifiers, null, null); ModifiersTree paramModTree = maker.Modifiers(Collections.<Modifier>emptySet()); List<VariableTree> paramTrees = new ArrayList<VariableTree>(); if (parameters != null) { for (int i = 0; i < parameters.length; i++) { paramTrees.add(maker.Variable(paramModTree, parameters[i], createTypeTree(copy, paramTypes[i]), null)); } } MethodTree methodTree = maker.Constructor(modifiersTree, Collections.<TypeParameterTree>emptyList(), paramTrees, Collections.<ExpressionTree>emptyList(), bodyText); if (comment != null) { maker.addComment(methodTree, createJavaDocComment(comment), true); } return maker.addClassMember(tree, methodTree); }
public ClassTree generate() { ClassTree modifiedClazz = getClassTree(); ModifiersTree methodModifiers = getTreeMaker().Modifiers( getGenerationOptions().getModifiers(), Collections.<AnnotationTree>emptyList() ); FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()){ modifiedClazz = createEntityManager(Initialization.INIT); } MethodTree newMethod = getTreeMaker().Method( methodModifiers, computeMethodName(), getTreeMaker().PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), getParameterList(), Collections.<ExpressionTree>emptyList(), "{ " + getMethodBody(em)+ "}", null ); return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod)); }
public ClassTree generate() { ClassTree modifiedClazz = getClassTree(); String body = ""; FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()){ FieldInfo emf = getEntityManagerFactoryFieldInfo(); if (!emf.isExisting()){ modifiedClazz = getTreeMaker().insertClassMember(getClassTree(), getIndexForField(getClassTree()), createEntityManagerFactory(emf.getName())); } body += getEmInitCode(em, emf); } body += getMethodBody(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(modifiedClazz, importFQNs(newMethod)); }
public ClassTree generate(){ ClassTree modifiedClazz = getClassTree(); String body = ""; FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()){ FieldInfo emf = getEntityManagerFactoryFieldInfo(); if (!emf.isExisting()){ modifiedClazz = getTreeMaker().insertClassMember(getClassTree(), getIndexForField(getClassTree()), createEntityManagerFactory(emf.getName())); } body += getEmInitCode(em, emf); } body += getMethodBody(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(modifiedClazz, importFQNs(newMethod)); }
public ChangeInfo implement(){ CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>(){ public void cancel() {} public void run(WorkingCopy workingCopy) throws Exception { workingCopy.toPhase(JavaSource.Phase.RESOLVED); TypeElement clazz = classHandle.resolve(workingCopy); if (clazz != null){ ClassTree clazzTree = workingCopy.getTrees().getTree(clazz); TreeMaker make = workingCopy.getTreeMaker(); ModifiersTree modifiers = make.Modifiers(Collections.singleton(Modifier.PUBLIC)); MethodTree constr = make.Constructor( modifiers, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}"); //NOI18N ClassTree newClass = make.insertClassMember(clazzTree, getPositionToInsert(clazzTree), constr); workingCopy.rewrite(clazzTree, newClass); } } }; JavaSource javaSource = JavaSource.forFileObject(fileObject); try{ javaSource.runModificationTask(task).commit(); } catch (IOException e){ JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e); } return null; }
/** * Makes a tree representing the given {@code TypeParameterElement}. * * @param typeParamElem {@code TypeParameterElement} to make a copy of * @param maker tree maker to use when for creation of the copy * @return {@code Tree} respresenting the given * {@code TypeParameterElement} */ private static TypeParameterTree makeCopy(TypeParameterElement typeParamElem, TreeMaker maker) { return maker.TypeParameter( typeParamElem.getSimpleName(), makeDeclaredTypesCopy((List<? extends DeclaredType>) typeParamElem.getBounds(), maker)); }
/** * Generates a set-up or a tear-down method. * The generated method will have no arguments, void return type * and a declaration that it may throw {@code java.lang.Exception}. * The method will have a declared protected member access. * The method contains call of the corresponding super method, i.e. * {@code super.setUp()} or {@code super.tearDown()}. * * @param methodName name of the method to be created * @return created method */ private MethodTree generateInitMethod(String methodName, String annotationClassName, boolean isStatic, WorkingCopy workingCopy) { Set<Modifier> methodModifiers = isStatic ? createModifierSet(PUBLIC, STATIC) : Collections.<Modifier>singleton(PUBLIC); ModifiersTree modifiers = createModifiersTree(annotationClassName, methodModifiers, workingCopy); TreeMaker maker = workingCopy.getTreeMaker(); BlockTree methodBody = maker.Block( Collections.<StatementTree>emptyList(), false); MethodTree method = maker.Method( modifiers, // modifiers methodName, // name maker.PrimitiveType(TypeKind.VOID), // return type Collections.<TypeParameterTree>emptyList(), // type params Collections.<VariableTree>emptyList(), // parameters Collections.<ExpressionTree>singletonList( maker.Identifier("Exception")), // throws...//NOI18N methodBody, null); // default value return method; }
@Override public Tree visitTypeParameter(TypeParameterTree tree, Void p) { TypeParameterTree n = make.TypeParameter(tree.getName(), (List<? extends ExpressionTree>)tree.getBounds()); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
public Boolean visitTypeParameter(TypeParameterTree node, TreePath p) { if (p == null) return super.visitTypeParameter(node, p); TypeParameterTree t = (TypeParameterTree) p.getLeaf(); String name = t.getName().toString(); if (name.startsWith("$")) { //XXX: there should be a utility method for this check String existingName = bindState.variables2Names.get(name); String currentName = node.getName().toString(); if (existingName != null) { if (!existingName.equals(currentName)) { return false; } bindState.variables.put(name + "$" + ++bindState.matchCount, currentPath); } else { //XXX: putting the variable into both variables and variable2Names. //variables is needed by the declarative hints to support conditions like //referencedIn($variable, $statements$): //causes problems in JavaFix, see visitIdentifier there. bindState.variables.put(name, getCurrentPath()); bindState.variables2Names.put(name, currentName); } } else { if (!node.getName().contentEquals(name)) return false; } return checkLists(node.getBounds(), t.getBounds(), p); }
public MethodTree makeMethod() { Set<Modifier> emptyModifs = Collections.emptySet(); List<TypeParameterTree> emptyTpt= Collections.emptyList(); List<VariableTree> emptyVt = Collections.emptyList(); List<ExpressionTree> emptyEt = Collections.emptyList(); return make.Method( make.Modifiers(emptyModifs), (CharSequence)"", (ExpressionTree) null, emptyTpt, emptyVt, emptyEt, (BlockTree) null, (ExpressionTree)null); }
public void testChangeInterfaceModifier() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package flaska;\n" + "\n" + "public interface Test {\n" + "}\n" ); String golden = "package flaska;\n" + "\n" + "interface Test {\n" + "}\n"; JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile)); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws java.io.IOException { workingCopy.toPhase(Phase.RESOLVED); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0); ModifiersTree mods = clazz.getModifiers(); Set<Modifier> flags = new HashSet<Modifier>(mods.getFlags()); flags.remove(Modifier.PUBLIC); ModifiersTree modified = make.Modifiers(flags); ClassTree copy = make.Interface( modified, clazz.getSimpleName(), Collections.<TypeParameterTree>emptyList(), Collections.<Tree>emptyList(), clazz.getMembers() ); workingCopy.rewrite(clazz, copy); } }; testSource.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
public void testStringQualIdentNewlyCreatedNestedClassesToCurrent() throws Exception { clearWorkDir(); testFile = new File(getWorkDir(), "hierbas/del/litoral/Test.java"); assertTrue(testFile.getParentFile().mkdirs()); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n" + "\n" + "public class Test {\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n" + "\n" + "public class Test {\n" + "\n" + " A l;\n\n" + " class A {\n" + " }\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); TreeMaker make = workingCopy.getTreeMaker(); ClassTree nueClass = make.Class(make.Modifiers(EnumSet.noneOf(Modifier.class)), "A", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList()); CompilationUnitTree node = workingCopy.getCompilationUnit(); ClassTree clazz = (ClassTree) node.getTypeDecls().get(0); VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "l", make.QualIdent("hierbas.del.litoral.Test.A"), null); workingCopy.rewrite(clazz, make.addClassMember(make.addClassMember(clazz, vt), nueClass)); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
public Void visitClass(ClassTree node, Object p) { TypeElement te = (TypeElement)model.getElement(node); if (te != null) { List<Tree> members = new ArrayList<Tree>(node.getMembers()); int pos = putBefore != null ? members.indexOf(putBefore) + 1: members.size(); Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC); //create body: List<StatementTree> statements = new ArrayList(); List<VariableTree> arguments = new ArrayList(); for (VariableElement ve : fields) { AssignmentTree a = make.Assignment(make.MemberSelect(make.Identifier("this"), ve.getSimpleName()), make.Identifier(ve.getSimpleName())); statements.add(make.ExpressionStatement(a)); arguments.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), ve.getSimpleName(), make.Type(ve.asType()), null)); } BlockTree body = make.Block(statements, false); members.add(pos, make.Method(make.Modifiers(mods), "<init>", null, Collections.<TypeParameterTree> emptyList(), arguments, Collections.<ExpressionTree>emptyList(), body, 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; }
public Void visitTypeParameter(TypeParameterTree node, Object p) { System.err.println("visitTypeParameter: " + node.getName()); super.visitTypeParameter(node, p); TypeParameterTree copy = make.setLabel(node, node.getName() + "0"); this.copy.rewrite(node, copy); return null; }
public void testRewriteRewrittenTree() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "public class Test {\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + "\n" + " @Deprecated\n" + " public void taragui() {\n" + " }\n" + "}\n"; JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile)); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws java.io.IOException { workingCopy.toPhase(Phase.RESOLVED); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0); ModifiersTree mods = make.Modifiers(EnumSet.of(Modifier.PUBLIC)); MethodTree method = make.Method(mods, "taragui", make.Type(workingCopy.getTypes().getNoType(TypeKind.VOID)), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null); workingCopy.rewrite(clazz, make.addClassMember(clazz, method)); ModifiersTree nueMods = make.Modifiers(EnumSet.of(Modifier.PUBLIC), Collections.singletonList(make.Annotation(make.QualIdent(workingCopy.getElements().getTypeElement("java.lang.Deprecated")), Collections.<ExpressionTree>emptyList()))); workingCopy.rewrite(mods, nueMods); } }; testSource.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
public void run(WorkingCopy copy) throws Exception { copy.toPhase(JavaSource.Phase.RESOLVED); TreePath tp = copy.getTreeUtilities().pathFor(offset); assertTrue(TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())); ClassTree ct = (ClassTree)tp.getLeaf(); GeneratorUtilities utilities = GeneratorUtilities.get(copy); assertNotNull(utilities); TreeMaker maker = copy.getTreeMaker(); ArrayList<Tree> members = new ArrayList<Tree>(1); switch(kind) { case FIELD: members.add(maker.Variable(maker.Modifiers(modifiers), "test", maker.PrimitiveType(TypeKind.INT), null)); break; case METHOD: members.add(maker.Method(maker.Modifiers(modifiers), "test", maker.PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), maker.Block(Collections.<StatementTree>emptyList(), false), null)); break; case CONSTRUCTOR: members.add(maker.Method(maker.Modifiers(modifiers), "<init>", null, Collections.<TypeParameterTree>emptyList(), Collections.singletonList(maker.Variable( maker.Modifiers(EnumSet.noneOf(Modifier.class)), "s", maker.Identifier("String"), null)), Collections.<ExpressionTree>emptyList(), maker.Block(Collections.<StatementTree>emptyList(), false), null)); break; case CLASS: members.add(maker.Class(maker.Modifiers(modifiers), "test", Collections.<TypeParameterTree>emptyList(), null, Collections.<ExpressionTree>emptyList(), Collections.<Tree>emptyList())); break; } ClassTree newCt = utilities.insertClassMembers(ct, members); copy.rewrite(ct, newCt); }