diff options
Diffstat (limited to 'src/lombok/javac')
-rw-r--r-- | src/lombok/javac/HandlerLibrary.java | 32 | ||||
-rw-r--r-- | src/lombok/javac/Javac.java | 39 | ||||
-rw-r--r-- | src/lombok/javac/JavacAST.java | 345 | ||||
-rw-r--r-- | src/lombok/javac/JavacASTAdapter.java | 44 | ||||
-rw-r--r-- | src/lombok/javac/JavacASTVisitor.java | 118 | ||||
-rw-r--r-- | src/lombok/javac/JavacAnnotationHandler.java | 2 | ||||
-rw-r--r-- | src/lombok/javac/JavacNode.java | 200 | ||||
-rw-r--r-- | src/lombok/javac/apt/Processor.java | 49 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleCleanup.java | 58 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleData.java | 52 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleEqualsAndHashCode.java | 145 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleGetter.java | 31 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandlePrintAST.java | 8 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleSetter.java | 28 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleSneakyThrows.java | 30 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleSynchronized.java | 18 | ||||
-rw-r--r-- | src/lombok/javac/handlers/HandleToString.java | 88 | ||||
-rw-r--r-- | src/lombok/javac/handlers/PKG.java | 112 |
18 files changed, 699 insertions, 700 deletions
diff --git a/src/lombok/javac/HandlerLibrary.java b/src/lombok/javac/HandlerLibrary.java index 20902e82..3d44db7f 100644 --- a/src/lombok/javac/HandlerLibrary.java +++ b/src/lombok/javac/HandlerLibrary.java @@ -72,7 +72,7 @@ public class HandlerLibrary { this.annotationClass = annotationClass; } - public boolean handle(final JavacAST.Node node) { + public boolean handle(final JavacNode node) { return handler.handle(Javac.createAnnotation(annotationClass, node), (JCAnnotation)node.get(), node); } } @@ -97,17 +97,17 @@ public class HandlerLibrary { //No, that seemingly superfluous reference to JavacAnnotationHandler's classloader is not in fact superfluous! Iterator<JavacAnnotationHandler> it = ServiceLoader.load(JavacAnnotationHandler.class, JavacAnnotationHandler.class.getClassLoader()).iterator(); - while ( it.hasNext() ) { + while (it.hasNext()) { try { JavacAnnotationHandler<?> handler = it.next(); Class<? extends Annotation> annotationClass = SpiLoadUtil.findAnnotationClass(handler.getClass(), JavacAnnotationHandler.class); AnnotationHandlerContainer<?> container = new AnnotationHandlerContainer(handler, annotationClass); - if ( lib.annotationHandlers.put(container.annotationClass.getName(), container) != null ) { + if (lib.annotationHandlers.put(container.annotationClass.getName(), container) != null) { lib.javacWarning("Duplicate handlers for annotation type: " + container.annotationClass.getName()); } lib.typeLibrary.addType(container.annotationClass.getName()); - } catch ( ServiceConfigurationError e ) { + } catch (ServiceConfigurationError e) { lib.javacWarning("Can't load Lombok annotation handler for javac", e); } } @@ -118,11 +118,11 @@ public class HandlerLibrary { //No, that seemingly superfluous reference to JavacASTVisitor's classloader is not in fact superfluous! Iterator<JavacASTVisitor> it = ServiceLoader.load(JavacASTVisitor.class, JavacASTVisitor.class.getClassLoader()).iterator(); - while ( it.hasNext() ) { + while (it.hasNext()) { try { JavacASTVisitor handler = it.next(); lib.visitorHandlers.add(handler); - } catch ( ServiceConfigurationError e ) { + } catch (ServiceConfigurationError e) { lib.javacWarning("Can't load Lombok visitor handler for javac", e); } } @@ -146,7 +146,7 @@ public class HandlerLibrary { /** Generates an error in the Messager that was used to initialize this HandlerLibrary. */ public void javacError(String message, Throwable t) { messager.printMessage(Diagnostic.Kind.ERROR, message + (t == null ? "" : (": " + t))); - if ( t != null ) t.printStackTrace(); + if (t != null) t.printStackTrace(); } /** @@ -166,23 +166,23 @@ public class HandlerLibrary { * @param node The Lombok AST Node representing the Annotation AST Node. * @param annotation 'node.get()' - convenience parameter. */ - public boolean handleAnnotation(JCCompilationUnit unit, JavacAST.Node node, JCAnnotation annotation) { + public boolean handleAnnotation(JCCompilationUnit unit, JavacNode node, JCAnnotation annotation) { TypeResolver resolver = new TypeResolver(typeLibrary, node.getPackageDeclaration(), node.getImportStatements()); String rawType = annotation.annotationType.toString(); boolean handled = false; - for ( String fqn : resolver.findTypeMatches(node, rawType) ) { + for (String fqn : resolver.findTypeMatches(node, rawType)) { boolean isPrintAST = fqn.equals(PrintAST.class.getName()); - if ( isPrintAST == skipPrintAST ) continue; + if (isPrintAST == skipPrintAST) continue; AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn); - if ( container == null ) continue; + if (container == null) continue; try { handled |= container.handle(node); - } catch ( AnnotationValueDecodeFail fail ) { + } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); - } catch ( Throwable t ) { + } catch (Throwable t) { String sourceName = "(unknown).java"; - if ( unit != null && unit.sourcefile != null ) sourceName = unit.sourcefile.getName(); + if (unit != null && unit.sourcefile != null) sourceName = unit.sourcefile.getName(); javacError(String.format("Lombok annotation handler %s failed on " + sourceName, container.handler.getClass()), t); } } @@ -194,9 +194,9 @@ public class HandlerLibrary { * Will call all registered {@link JavacASTVisitor} instances. */ public void callASTVisitors(JavacAST ast) { - for ( JavacASTVisitor visitor : visitorHandlers ) try { + for (JavacASTVisitor visitor : visitorHandlers) try { ast.traverse(visitor); - } catch ( Throwable t ) { + } catch (Throwable t) { javacError(String.format("Lombok visitor handler %s failed", visitor.getClass()), t); } } diff --git a/src/lombok/javac/Javac.java b/src/lombok/javac/Javac.java index bc6d18f6..99a7c928 100644 --- a/src/lombok/javac/Javac.java +++ b/src/lombok/javac/Javac.java @@ -35,7 +35,6 @@ import lombok.core.TypeLibrary; import lombok.core.TypeResolver; import lombok.core.AST.Kind; import lombok.core.AnnotationValues.AnnotationValue; -import lombok.javac.JavacAST.Node; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCAssign; @@ -60,8 +59,8 @@ public class Javac { * @param type An actual annotation type, such as <code>lombok.Getter.class</code>. * @param node A Lombok AST node representing an annotation in source code. */ - public static boolean annotationTypeMatches(Class<? extends Annotation> type, Node node) { - if ( node.getKind() != Kind.ANNOTATION ) return false; + public static boolean annotationTypeMatches(Class<? extends Annotation> type, JavacNode node) { + if (node.getKind() != Kind.ANNOTATION) return false; String typeName = ((JCAnnotation)node.get()).annotationType.toString(); TypeLibrary library = new TypeLibrary(); @@ -69,8 +68,8 @@ public class Javac { TypeResolver resolver = new TypeResolver(library, node.getPackageDeclaration(), node.getImportStatements()); Collection<String> typeMatches = resolver.findTypeMatches(node, typeName); - for ( String match : typeMatches ) { - if ( match.equals(type.getName()) ) return true; + for (String match : typeMatches) { + if (match.equals(type.getName())) return true; } return false; @@ -82,23 +81,23 @@ public class Javac { * @param type An annotation class type, such as <code>lombok.Getter.class</code>. * @param node A Lombok AST node representing an annotation in source code. */ - public static <A extends Annotation> AnnotationValues<A> createAnnotation(Class<A> type, final Node node) { + public static <A extends Annotation> AnnotationValues<A> createAnnotation(Class<A> type, final JavacNode node) { Map<String, AnnotationValue> values = new HashMap<String, AnnotationValue>(); JCAnnotation anno = (JCAnnotation) node.get(); List<JCExpression> arguments = anno.getArguments(); - for ( Method m : type.getDeclaredMethods() ) { - if ( !Modifier.isPublic(m.getModifiers()) ) continue; + for (Method m : type.getDeclaredMethods()) { + if (!Modifier.isPublic(m.getModifiers())) continue; String name = m.getName(); List<String> raws = new ArrayList<String>(); List<Object> guesses = new ArrayList<Object>(); final List<DiagnosticPosition> positions = new ArrayList<DiagnosticPosition>(); boolean isExplicit = false; - for ( JCExpression arg : arguments ) { + for (JCExpression arg : arguments) { String mName; JCExpression rhs; - if ( arg instanceof JCAssign ) { + if (arg instanceof JCAssign) { JCAssign assign = (JCAssign) arg; mName = assign.lhs.toString(); rhs = assign.rhs; @@ -107,11 +106,11 @@ public class Javac { mName = "value"; } - if ( !mName.equals(name) ) continue; + if (!mName.equals(name)) continue; isExplicit = true; - if ( rhs instanceof JCNewArray ) { + if (rhs instanceof JCNewArray) { List<JCExpression> elems = ((JCNewArray)rhs).elems; - for ( JCExpression inner : elems ) { + for (JCExpression inner : elems) { raws.add(inner.toString()); guesses.add(calculateGuess(inner)); positions.add(inner.pos()); @@ -125,11 +124,11 @@ public class Javac { values.put(name, new AnnotationValue(node, raws, guesses, isExplicit) { @Override public void setError(String message, int valueIdx) { - if ( valueIdx < 0 ) node.addError(message); + if (valueIdx < 0) node.addError(message); else node.addError(message, positions.get(valueIdx)); } @Override public void setWarning(String message, int valueIdx) { - if ( valueIdx < 0 ) node.addWarning(message); + if (valueIdx < 0) node.addWarning(message); else node.addWarning(message, positions.get(valueIdx)); } }); @@ -144,18 +143,18 @@ public class Javac { * Will for example turn a TrueLiteral into 'Boolean.valueOf(true)'. */ private static Object calculateGuess(JCExpression expr) { - if ( expr instanceof JCLiteral ) { + if (expr instanceof JCLiteral) { JCLiteral lit = (JCLiteral)expr; - if ( lit.getKind() == com.sun.source.tree.Tree.Kind.BOOLEAN_LITERAL ) { + if (lit.getKind() == com.sun.source.tree.Tree.Kind.BOOLEAN_LITERAL) { return ((Number)lit.value).intValue() == 0 ? false : true; } return lit.value; - } else if ( expr instanceof JCIdent || expr instanceof JCFieldAccess ) { + } else if (expr instanceof JCIdent || expr instanceof JCFieldAccess) { String x = expr.toString(); - if ( x.endsWith(".class") ) x = x.substring(0, x.length() - 6); + if (x.endsWith(".class")) x = x.substring(0, x.length() - 6); else { int idx = x.lastIndexOf('.'); - if ( idx > -1 ) x = x.substring(idx + 1); + if (idx > -1) x = x.substring(idx + 1); } return x; } else return null; diff --git a/src/lombok/javac/JavacAST.java b/src/lombok/javac/JavacAST.java index c68d3c19..2ee3d5be 100644 --- a/src/lombok/javac/JavacAST.java +++ b/src/lombok/javac/JavacAST.java @@ -55,7 +55,7 @@ import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; * Wraps around javac's internal AST view to add useful features as well as the ability to visit parents from children, * something javac's own AST system does not offer. */ -public class JavacAST extends AST<JCTree> { +public class JavacAST extends AST<JavacAST, JavacNode, JCTree> { private final Messager messager; private final Name.Table nameTable; private final TreeMaker treeMaker; @@ -90,8 +90,8 @@ public class JavacAST extends AST<JCTree> { @Override public Collection<String> getImportStatements() { List<String> imports = new ArrayList<String>(); JCCompilationUnit unit = (JCCompilationUnit)top().get(); - for ( JCTree def : unit.defs ) { - if ( def instanceof JCImport ) { + for (JCTree def : unit.defs) { + if (def instanceof JCImport) { imports.add(((JCImport)def).qualid.toString()); } } @@ -107,22 +107,12 @@ public class JavacAST extends AST<JCTree> { top().traverse(visitor); } - private void traverseChildren(JavacASTVisitor visitor, Node node) { - for ( Node child : new ArrayList<Node>(node.down()) ) { + void traverseChildren(JavacASTVisitor visitor, JavacNode node) { + for (JavacNode child : new ArrayList<JavacNode>(node.down())) { child.traverse(visitor); } } - /** {@inheritDoc} */ - @Override public Node top() { - return (Node) super.top(); - } - - /** {@inheritDoc} */ - @Override public Node get(JCTree astNode) { - return (Node) super.get(astNode); - } - /** @return A Name object generated for the proper name table belonging to this AST. */ public Name toName(String name) { return nameTable.fromString(name); @@ -139,8 +129,8 @@ public class JavacAST extends AST<JCTree> { } /** {@inheritDoc} */ - @Override protected Node buildTree(JCTree node, Kind kind) { - switch ( kind ) { + @Override protected JavacNode buildTree(JCTree node, Kind kind) { + switch (kind) { case COMPILATION_UNIT: return buildCompilationUnit((JCCompilationUnit) node); case TYPE: @@ -164,99 +154,100 @@ public class JavacAST extends AST<JCTree> { } } - private Node buildCompilationUnit(JCCompilationUnit top) { - List<Node> childNodes = new ArrayList<Node>(); - for ( JCTree s : top.defs ) { - if ( s instanceof JCClassDecl ) { + private JavacNode buildCompilationUnit(JCCompilationUnit top) { + List<JavacNode> childNodes = new ArrayList<JavacNode>(); + for (JCTree s : top.defs) { + if (s instanceof JCClassDecl) { addIfNotNull(childNodes, buildType((JCClassDecl)s)); } // else they are import statements, which we don't care about. Or Skip objects, whatever those are. } - return new Node(top, childNodes, Kind.COMPILATION_UNIT); + return new JavacNode(this, top, childNodes, Kind.COMPILATION_UNIT); } - private Node buildType(JCClassDecl type) { - if ( setAndGetAsHandled(type) ) return null; - List<Node> childNodes = new ArrayList<Node>(); + private JavacNode buildType(JCClassDecl type) { + if (setAndGetAsHandled(type)) return null; + List<JavacNode> childNodes = new ArrayList<JavacNode>(); - for ( JCTree def : type.defs ) { - for ( JCAnnotation annotation : type.mods.annotations ) addIfNotNull(childNodes, buildAnnotation(annotation)); + for (JCTree def : type.defs) { + for (JCAnnotation annotation : type.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation)); /* A def can be: * JCClassDecl for inner types * JCMethodDecl for constructors and methods * JCVariableDecl for fields * JCBlock for (static) initializers */ - if ( def instanceof JCMethodDecl ) addIfNotNull(childNodes, buildMethod((JCMethodDecl)def)); - else if ( def instanceof JCClassDecl ) addIfNotNull(childNodes, buildType((JCClassDecl)def)); - else if ( def instanceof JCVariableDecl ) addIfNotNull(childNodes, buildField((JCVariableDecl)def)); - else if ( def instanceof JCBlock ) addIfNotNull(childNodes, buildInitializer((JCBlock)def)); + if (def instanceof JCMethodDecl) addIfNotNull(childNodes, buildMethod((JCMethodDecl)def)); + else if (def instanceof JCClassDecl) addIfNotNull(childNodes, buildType((JCClassDecl)def)); + else if (def instanceof JCVariableDecl) addIfNotNull(childNodes, buildField((JCVariableDecl)def)); + else if (def instanceof JCBlock) addIfNotNull(childNodes, buildInitializer((JCBlock)def)); } - return putInMap(new Node(type, childNodes, Kind.TYPE)); + return putInMap(new JavacNode(this, type, childNodes, Kind.TYPE)); } - private Node buildField(JCVariableDecl field) { - if ( setAndGetAsHandled(field) ) return null; - List<Node> childNodes = new ArrayList<Node>(); - for ( JCAnnotation annotation : field.mods.annotations ) addIfNotNull(childNodes, buildAnnotation(annotation)); + private JavacNode buildField(JCVariableDecl field) { + if (setAndGetAsHandled(field)) return null; + List<JavacNode> childNodes = new ArrayList<JavacNode>(); + for (JCAnnotation annotation : field.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation)); addIfNotNull(childNodes, buildExpression(field.init)); - return putInMap(new Node(field, childNodes, Kind.FIELD)); + return putInMap(new JavacNode(this, field, childNodes, Kind.FIELD)); } - private Node buildLocalVar(JCVariableDecl local, Kind kind) { - if ( setAndGetAsHandled(local) ) return null; - List<Node> childNodes = new ArrayList<Node>(); - for ( JCAnnotation annotation : local.mods.annotations ) addIfNotNull(childNodes, buildAnnotation(annotation)); + private JavacNode buildLocalVar(JCVariableDecl local, Kind kind) { + if (setAndGetAsHandled(local)) return null; + List<JavacNode> childNodes = new ArrayList<JavacNode>(); + for (JCAnnotation annotation : local.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation)); addIfNotNull(childNodes, buildExpression(local.init)); - return putInMap(new Node(local, childNodes, kind)); + return putInMap(new JavacNode(this, local, childNodes, kind)); } - private Node buildInitializer(JCBlock initializer) { - if ( setAndGetAsHandled(initializer) ) return null; - List<Node> childNodes = new ArrayList<Node>(); - for ( JCStatement statement: initializer.stats ) addIfNotNull(childNodes, buildStatement(statement)); - return putInMap(new Node(initializer, childNodes, Kind.INITIALIZER)); + private JavacNode buildInitializer(JCBlock initializer) { + if (setAndGetAsHandled(initializer)) return null; + List<JavacNode> childNodes = new ArrayList<JavacNode>(); + for (JCStatement statement: initializer.stats) addIfNotNull(childNodes, buildStatement(statement)); + return putInMap(new JavacNode(this, initializer, childNodes, Kind.INITIALIZER)); } - private Node buildMethod(JCMethodDecl method) { - if ( setAndGetAsHandled(method) ) return null; - List<Node> childNodes = new ArrayList<Node>(); - for ( JCAnnotation annotation : method.mods.annotations ) addIfNotNull(childNodes, buildAnnotation(annotation)); - for ( JCVariableDecl param : method.params ) addIfNotNull(childNodes, buildLocalVar(param, Kind.ARGUMENT)); - if ( method.body != null && method.body.stats != null ) - for ( JCStatement statement : method.body.stats ) addIfNotNull(childNodes, buildStatement(statement)); - return putInMap(new Node(method, childNodes, Kind.METHOD)); + private JavacNode buildMethod(JCMethodDecl method) { + if (setAndGetAsHandled(method)) return null; + List<JavacNode> childNodes = new ArrayList<JavacNode>(); + for (JCAnnotation annotation : method.mods.annotations) addIfNotNull(childNodes, buildAnnotation(annotation)); + for (JCVariableDecl param : method.params) addIfNotNull(childNodes, buildLocalVar(param, Kind.ARGUMENT)); + if (method.body != null && method.body.stats != null) { + for (JCStatement statement : method.body.stats) addIfNotNull(childNodes, buildStatement(statement)); + } + return putInMap(new JavacNode(this, method, childNodes, Kind.METHOD)); } - private Node buildAnnotation(JCAnnotation annotation) { - if ( setAndGetAsHandled(annotation) ) return null; - return putInMap(new Node(annotation, null, Kind.ANNOTATION)); + private JavacNode buildAnnotation(JCAnnotation annotation) { + if (setAndGetAsHandled(annotation)) return null; + return putInMap(new JavacNode(this, annotation, null, Kind.ANNOTATION)); } - private Node buildExpression(JCExpression expression) { + private JavacNode buildExpression(JCExpression expression) { return buildStatementOrExpression(expression); } - private Node buildStatement(JCStatement statement) { + private JavacNode buildStatement(JCStatement statement) { return buildStatementOrExpression(statement); } - private Node buildStatementOrExpression(JCTree statement) { - if ( statement == null ) return null; - if ( statement instanceof JCAnnotation ) return null; - if ( statement instanceof JCClassDecl ) return buildType((JCClassDecl)statement); - if ( statement instanceof JCVariableDecl ) return buildLocalVar((JCVariableDecl)statement, Kind.LOCAL); + private JavacNode buildStatementOrExpression(JCTree statement) { + if (statement == null) return null; + if (statement instanceof JCAnnotation) return null; + if (statement instanceof JCClassDecl) return buildType((JCClassDecl)statement); + if (statement instanceof JCVariableDecl) return buildLocalVar((JCVariableDecl)statement, Kind.LOCAL); - if ( setAndGetAsHandled(statement) ) return null; + if (setAndGetAsHandled(statement)) return null; return drill(statement); } - private Node drill(JCTree statement) { - List<Node> childNodes = new ArrayList<Node>(); - for ( FieldAccess fa : fieldsOf(statement.getClass()) ) childNodes.addAll(buildWithField(Node.class, statement, fa)); - return putInMap(new Node(statement, childNodes, Kind.STATEMENT)); + private JavacNode drill(JCTree statement) { + List<JavacNode> childNodes = new ArrayList<JavacNode>(); + for (FieldAccess fa : fieldsOf(statement.getClass())) childNodes.addAll(buildWithField(JavacNode.class, statement, fa)); + return putInMap(new JavacNode(this, statement, childNodes, Kind.STATEMENT)); } /** For javac, both JCExpression and JCStatement are considered as valid children types. */ @@ -267,200 +258,12 @@ public class JavacAST extends AST<JCTree> { return collection; } - private static void addIfNotNull(Collection<Node> nodes, Node node) { - if ( node != null ) nodes.add(node); - } - - /** - * Javac specific version of the AST.Node class. - */ - public class Node extends AST<JCTree>.Node { - /** - * See the {@link AST.Node} constructor for information. - */ - public Node(JCTree node, List<Node> children, Kind kind) { - super(node, children, kind); - } - - /** - * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods. - */ - public void traverse(JavacASTVisitor visitor) { - switch ( this.getKind() ) { - case COMPILATION_UNIT: - visitor.visitCompilationUnit(this, (JCCompilationUnit)get()); - traverseChildren(visitor, this); - visitor.endVisitCompilationUnit(this, (JCCompilationUnit)get()); - break; - case TYPE: - visitor.visitType(this, (JCClassDecl)get()); - traverseChildren(visitor, this); - visitor.endVisitType(this, (JCClassDecl)get()); - break; - case FIELD: - visitor.visitField(this, (JCVariableDecl)get()); - traverseChildren(visitor, this); - visitor.endVisitField(this, (JCVariableDecl)get()); - break; - case METHOD: - visitor.visitMethod(this, (JCMethodDecl)get()); - traverseChildren(visitor, this); - visitor.endVisitMethod(this, (JCMethodDecl)get()); - break; - case INITIALIZER: - visitor.visitInitializer(this, (JCBlock)get()); - traverseChildren(visitor, this); - visitor.endVisitInitializer(this, (JCBlock)get()); - break; - case ARGUMENT: - JCMethodDecl parent = (JCMethodDecl) up().get(); - visitor.visitMethodArgument(this, (JCVariableDecl)get(), parent); - traverseChildren(visitor, this); - visitor.endVisitMethodArgument(this, (JCVariableDecl)get(), parent); - break; - case LOCAL: - visitor.visitLocal(this, (JCVariableDecl)get()); - traverseChildren(visitor, this); - visitor.endVisitLocal(this, (JCVariableDecl)get()); - break; - case STATEMENT: - visitor.visitStatement(this, get()); - traverseChildren(visitor, this); - visitor.endVisitStatement(this, get()); - break; - case ANNOTATION: - switch ( up().getKind() ) { - case TYPE: - visitor.visitAnnotationOnType((JCClassDecl)up().get(), this, (JCAnnotation)get()); - break; - case FIELD: - visitor.visitAnnotationOnField((JCVariableDecl)up().get(), this, (JCAnnotation)get()); - break; - case METHOD: - visitor.visitAnnotationOnMethod((JCMethodDecl)up().get(), this, (JCAnnotation)get()); - break; - case ARGUMENT: - JCVariableDecl argument = (JCVariableDecl)up().get(); - JCMethodDecl method = (JCMethodDecl)up().up().get(); - visitor.visitAnnotationOnMethodArgument(argument, method, this, (JCAnnotation)get()); - break; - case LOCAL: - visitor.visitAnnotationOnLocal((JCVariableDecl)up().get(), this, (JCAnnotation)get()); - break; - default: - throw new AssertionError("Annotion not expected as child of a " + up().getKind()); - } - break; - default: - throw new AssertionError("Unexpected kind during node traversal: " + getKind()); - } - } - - /** {@inheritDoc} */ - @Override public String getName() { - final Name n; - - if ( node instanceof JCClassDecl ) n = ((JCClassDecl)node).name; - else if ( node instanceof JCMethodDecl ) n = ((JCMethodDecl)node).name; - else if ( node instanceof JCVariableDecl ) n = ((JCVariableDecl)node).name; - else n = null; - - return n == null ? null : n.toString(); - } - - /** {@inheritDoc} */ - @Override protected boolean calculateIsStructurallySignificant() { - if ( node instanceof JCClassDecl ) return true; - if ( node instanceof JCMethodDecl ) return true; - if ( node instanceof JCVariableDecl ) return true; - if ( node instanceof JCCompilationUnit ) return true; - return false; - } - - /** - * Convenient shortcut to the owning JavacAST object's getTreeMaker method. - * - * @see JavacAST#getTreeMaker() - */ - public TreeMaker getTreeMaker() { - return treeMaker; - } - - /** - * Convenient shortcut to the owning JavacAST object's getSymbolTable method. - * - * @see JavacAST#getSymbolTable() - */ - public Symtab getSymbolTable() { - return symtab; - } - - /** - * Convenient shortcut to the owning JavacAST object's toName method. - * - * @see JavacAST#toName(String) - */ - public Name toName(String name) { - return JavacAST.this.toName(name); - } - - /** {@inheritDoc} */ - @Override public Node getNodeFor(JCTree obj) { - return (Node) super.getNodeFor(obj); - } - - /** {@inheritDoc} */ - @Override public Node directUp() { - return (Node) super.directUp(); - } - - /** {@inheritDoc} */ - @Override public Node up() { - return (Node) super.up(); - } - - /** {@inheritDoc} */ - @Override public Node top() { - return (Node) super.top(); - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override public Collection<Node> down() { - return (Collection<Node>) super.down(); - } - - /** - * Generates an compiler error focused on the AST node represented by this node object. - */ - public void addError(String message) { - printMessage(Diagnostic.Kind.ERROR, message, this, null); - } - - /** - * Generates an compiler error focused on the AST node represented by this node object. - */ - public void addError(String message, DiagnosticPosition pos) { - printMessage(Diagnostic.Kind.ERROR, message, null, pos); - } - - /** - * Generates a compiler warning focused on the AST node represented by this node object. - */ - public void addWarning(String message) { - printMessage(Diagnostic.Kind.WARNING, message, this, null); - } - - /** - * Generates a compiler warning focused on the AST node represented by this node object. - */ - public void addWarning(String message, DiagnosticPosition pos) { - printMessage(Diagnostic.Kind.WARNING, message, null, pos); - } + private static void addIfNotNull(Collection<JavacNode> nodes, JavacNode node) { + if (node != null) nodes.add(node); } /** Supply either a position or a node (in that case, position of the node is used) */ - private void printMessage(Diagnostic.Kind kind, String message, Node node, DiagnosticPosition pos) { + void printMessage(Diagnostic.Kind kind, String message, JavacNode node, DiagnosticPosition pos) { JavaFileObject oldSource = null; JavaFileObject newSource = null; JCTree astObject = node == null ? null : node.get(); @@ -468,7 +271,7 @@ public class JavacAST extends AST<JCTree> { newSource = top.sourcefile; if (newSource != null) { oldSource = log.useSource(newSource); - if ( pos == null ) pos = astObject.pos(); + if (pos == null) pos = astObject.pos(); } try { switch (kind) { @@ -488,22 +291,20 @@ public class JavacAST extends AST<JCTree> { break; } } finally { - if (oldSource != null) - log.useSource(oldSource); + if (oldSource != null) log.useSource(oldSource); } } /** {@inheritDoc} */ - @SuppressWarnings("unchecked") @Override protected void setElementInASTCollection(Field field, Object refField, List<Collection<?>> chain, Collection<?> collection, int idx, JCTree newN) throws IllegalAccessException { - com.sun.tools.javac.util.List<?> list = setElementInConsList(chain, collection, ((List)collection).get(idx), newN); + com.sun.tools.javac.util.List<?> list = setElementInConsList(chain, collection, ((List<?>)collection).get(idx), newN); field.set(refField, list); } private com.sun.tools.javac.util.List<?> setElementInConsList(List<Collection<?>> chain, Collection<?> current, Object oldO, Object newO) { com.sun.tools.javac.util.List<?> oldL = (com.sun.tools.javac.util.List<?>) current; com.sun.tools.javac.util.List<?> newL = replaceInConsList(oldL, oldO, newO); - if ( chain.isEmpty() ) return newL; + if (chain.isEmpty()) return newL; else { List<Collection<?>> reducedChain = new ArrayList<Collection<?>>(chain); Collection<?> newCurrent = reducedChain.remove(reducedChain.size() -1); @@ -514,14 +315,14 @@ public class JavacAST extends AST<JCTree> { private com.sun.tools.javac.util.List<?> replaceInConsList(com.sun.tools.javac.util.List<?> oldL, Object oldO, Object newO) { boolean repl = false; Object[] a = oldL.toArray(); - for ( int i = 0 ; i < a.length ; i++ ) { - if ( a[i] == oldO ) { + for (int i = 0; i < a.length; i++) { + if (a[i] == oldO) { a[i] = newO; repl = true; } } - if ( repl ) return com.sun.tools.javac.util.List.<Object>from(a); + if (repl) return com.sun.tools.javac.util.List.<Object>from(a); else return oldL; } @@ -529,11 +330,11 @@ public class JavacAST extends AST<JCTree> { try { Field f = messager.getClass().getDeclaredField("errorCount"); f.setAccessible(true); - if ( f.getType() == int.class ) { + if (f.getType() == int.class) { int val = ((Number)f.get(messager)).intValue(); f.set(messager, val +1); } - } catch ( Throwable t ) { + } catch (Throwable t) { //Very unfortunate, but in most cases it still works fine, so we'll silently swallow it. } } diff --git a/src/lombok/javac/JavacASTAdapter.java b/src/lombok/javac/JavacASTAdapter.java index b720ea32..41bc46d3 100644 --- a/src/lombok/javac/JavacASTAdapter.java +++ b/src/lombok/javac/JavacASTAdapter.java @@ -21,8 +21,6 @@ */ package lombok.javac; -import lombok.javac.JavacAST.Node; - import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; @@ -37,64 +35,64 @@ import com.sun.tools.javac.tree.JCTree.JCVariableDecl; */ public class JavacASTAdapter implements JavacASTVisitor { /** {@inheritDoc} */ - @Override public void visitCompilationUnit(Node top, JCCompilationUnit unit) {} + @Override public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit) {} /** {@inheritDoc} */ - @Override public void endVisitCompilationUnit(Node top, JCCompilationUnit unit) {} + @Override public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit) {} /** {@inheritDoc} */ - @Override public void visitType(Node typeNode, JCClassDecl type) {} + @Override public void visitType(JavacNode typeNode, JCClassDecl type) {} /** {@inheritDoc} */ - @Override public void visitAnnotationOnType(JCClassDecl type, Node annotationNode, JCAnnotation annotation) {} + @Override public void visitAnnotationOnType(JCClassDecl type, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ - @Override public void endVisitType(Node typeNode, JCClassDecl type) {} + @Override public void endVisitType(JavacNode typeNode, JCClassDecl type) {} /** {@inheritDoc} */ - @Override public void visitField(Node fieldNode, JCVariableDecl field) {} + @Override public void visitField(JavacNode fieldNode, JCVariableDecl field) {} /** {@inheritDoc} */ - @Override public void visitAnnotationOnField(JCVariableDecl field, Node annotationNode, JCAnnotation annotation) {} + @Override public void visitAnnotationOnField(JCVariableDecl field, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ - @Override public void endVisitField(Node fieldNode, JCVariableDecl field) {} + @Override public void endVisitField(JavacNode fieldNode, JCVariableDecl field) {} /** {@inheritDoc} */ - @Override public void visitInitializer(Node initializerNode, JCBlock initializer) {} + @Override public void visitInitializer(JavacNode initializerNode, JCBlock initializer) {} /** {@inheritDoc} */ - @Override public void endVisitInitializer(Node initializerNode, JCBlock initializer) {} + @Override public void endVisitInitializer(JavacNode initializerNode, JCBlock initializer) {} /** {@inheritDoc} */ - @Override public void visitMethod(Node methodNode, JCMethodDecl method) {} + @Override public void visitMethod(JavacNode methodNode, JCMethodDecl method) {} /** {@inheritDoc} */ - @Override public void visitAnnotationOnMethod(JCMethodDecl method, Node annotationNode, JCAnnotation annotation) {} + @Override public void visitAnnotationOnMethod(JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ - @Override public void endVisitMethod(Node methodNode, JCMethodDecl method) {} + @Override public void endVisitMethod(JavacNode methodNode, JCMethodDecl method) {} /** {@inheritDoc} */ - @Override public void visitMethodArgument(Node argumentNode, JCVariableDecl argument, JCMethodDecl method) {} + @Override public void visitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method) {} /** {@inheritDoc} */ - @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, Node annotationNode, JCAnnotation annotation) {} + @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ - @Override public void endVisitMethodArgument(Node argumentNode, JCVariableDecl argument, JCMethodDecl method) {} + @Override public void endVisitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method) {} /** {@inheritDoc} */ - @Override public void visitLocal(Node localNode, JCVariableDecl local) {} + @Override public void visitLocal(JavacNode localNode, JCVariableDecl local) {} /** {@inheritDoc} */ - @Override public void visitAnnotationOnLocal(JCVariableDecl local, Node annotationNode, JCAnnotation annotation) {} + @Override public void visitAnnotationOnLocal(JCVariableDecl local, JavacNode annotationNode, JCAnnotation annotation) {} /** {@inheritDoc} */ - @Override public void endVisitLocal(Node localNode, JCVariableDecl local) {} + @Override public void endVisitLocal(JavacNode localNode, JCVariableDecl local) {} /** {@inheritDoc} */ - @Override public void visitStatement(Node statementNode, JCTree statement) {} + @Override public void visitStatement(JavacNode statementNode, JCTree statement) {} /** {@inheritDoc} */ - @Override public void endVisitStatement(Node statementNode, JCTree statement) {} + @Override public void endVisitStatement(JavacNode statementNode, JCTree statement) {} } diff --git a/src/lombok/javac/JavacASTVisitor.java b/src/lombok/javac/JavacASTVisitor.java index d0902006..3c5887a7 100644 --- a/src/lombok/javac/JavacASTVisitor.java +++ b/src/lombok/javac/JavacASTVisitor.java @@ -23,8 +23,6 @@ package lombok.javac; import java.io.PrintStream; -import lombok.javac.JavacAST.Node; - import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; @@ -35,64 +33,64 @@ import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; /** - * Implement so you can ask any JavacAST.Node to traverse depth-first through all children, + * Implement so you can ask any JavacAST.LombokNode to traverse depth-first through all children, * calling the appropriate visit and endVisit methods. */ public interface JavacASTVisitor { /** * Called at the very beginning and end. */ - void visitCompilationUnit(Node top, JCCompilationUnit unit); - void endVisitCompilationUnit(Node top, JCCompilationUnit unit); + void visitCompilationUnit(JavacNode top, JCCompilationUnit unit); + void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit); /** * Called when visiting a type (a class, interface, annotation, enum, etcetera). */ - void visitType(Node typeNode, JCClassDecl type); - void visitAnnotationOnType(JCClassDecl type, Node annotationNode, JCAnnotation annotation); - void endVisitType(Node typeNode, JCClassDecl type); + void visitType(JavacNode typeNode, JCClassDecl type); + void visitAnnotationOnType(JCClassDecl type, JavacNode annotationNode, JCAnnotation annotation); + void endVisitType(JavacNode typeNode, JCClassDecl type); /** * Called when visiting a field of a class. */ - void visitField(Node fieldNode, JCVariableDecl field); - void visitAnnotationOnField(JCVariableDecl field, Node annotationNode, JCAnnotation annotation); - void endVisitField(Node fieldNode, JCVariableDecl field); + void visitField(JavacNode fieldNode, JCVariableDecl field); + void visitAnnotationOnField(JCVariableDecl field, JavacNode annotationNode, JCAnnotation annotation); + void endVisitField(JavacNode fieldNode, JCVariableDecl field); /** * Called for static and instance initializers. You can tell the difference via the isStatic() method. */ - void visitInitializer(Node initializerNode, JCBlock initializer); - void endVisitInitializer(Node initializerNode, JCBlock initializer); + void visitInitializer(JavacNode initializerNode, JCBlock initializer); + void endVisitInitializer(JavacNode initializerNode, JCBlock initializer); /** * Called for both methods and constructors. */ - void visitMethod(Node methodNode, JCMethodDecl method); - void visitAnnotationOnMethod(JCMethodDecl method, Node annotationNode, JCAnnotation annotation); - void endVisitMethod(Node methodNode, JCMethodDecl method); + void visitMethod(JavacNode methodNode, JCMethodDecl method); + void visitAnnotationOnMethod(JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation); + void endVisitMethod(JavacNode methodNode, JCMethodDecl method); /** * Visits a method argument. */ - void visitMethodArgument(Node argumentNode, JCVariableDecl argument, JCMethodDecl method); - void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, Node annotationNode, JCAnnotation annotation); - void endVisitMethodArgument(Node argumentNode, JCVariableDecl argument, JCMethodDecl method); + void visitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method); + void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation); + void endVisitMethodArgument(JavacNode argumentNode, JCVariableDecl argument, JCMethodDecl method); /** * Visits a local declaration - that is, something like 'int x = 10;' on the method level. Also called * for method parameters. */ - void visitLocal(Node localNode, JCVariableDecl local); - void visitAnnotationOnLocal(JCVariableDecl local, Node annotationNode, JCAnnotation annotation); - void endVisitLocal(Node localNode, JCVariableDecl local); + void visitLocal(JavacNode localNode, JCVariableDecl local); + void visitAnnotationOnLocal(JCVariableDecl local, JavacNode annotationNode, JCAnnotation annotation); + void endVisitLocal(JavacNode localNode, JCVariableDecl local); /** * Visits a statement that isn't any of the other visit methods (e.g. JCClassDecl). * The statement object is guaranteed to be either a JCStatement or a JCExpression. */ - void visitStatement(Node statementNode, JCTree statement); - void endVisitStatement(Node statementNode, JCTree statement); + void visitStatement(JavacNode statementNode, JCTree statement); + void endVisitStatement(JavacNode statementNode, JCTree statement); /** * Prints the structure of an AST. @@ -125,142 +123,142 @@ public interface JavacASTVisitor { private void forcePrint(String text, Object... params) { StringBuilder sb = new StringBuilder(); - for ( int i = 0 ; i < indent ; i++ ) sb.append(" "); + for (int i = 0; i < indent; i++) sb.append(" "); out.printf(sb.append(text).append('\n').toString(), params); out.flush(); } private void print(String text, Object... params) { - if ( disablePrinting == 0 ) forcePrint(text, params); + if (disablePrinting == 0) forcePrint(text, params); } - @Override public void visitCompilationUnit(Node Node, JCCompilationUnit unit) { + @Override public void visitCompilationUnit(JavacNode LombokNode, JCCompilationUnit unit) { out.println("---------------------------------------------------------"); - print("<CU %s>", Node.getFileName()); + print("<CU %s>", LombokNode.getFileName()); indent++; } - @Override public void endVisitCompilationUnit(Node node, JCCompilationUnit unit) { + @Override public void endVisitCompilationUnit(JavacNode node, JCCompilationUnit unit) { indent--; print("</CUD>"); } - @Override public void visitType(Node node, JCClassDecl type) { + @Override public void visitType(JavacNode node, JCClassDecl type) { print("<TYPE %s>", type.name); indent++; - if ( printContent ) { + if (printContent) { print("%s", type); disablePrinting++; } } - @Override public void visitAnnotationOnType(JCClassDecl type, Node node, JCAnnotation annotation) { + @Override public void visitAnnotationOnType(JCClassDecl type, JavacNode node, JCAnnotation annotation) { forcePrint("<ANNOTATION: %s />", annotation); } - @Override public void endVisitType(Node node, JCClassDecl type) { - if ( printContent ) disablePrinting--; + @Override public void endVisitType(JavacNode node, JCClassDecl type) { + if (printContent) disablePrinting--; indent--; print("</TYPE %s>", type.name); } - @Override public void visitInitializer(Node node, JCBlock initializer) { + @Override public void visitInitializer(JavacNode node, JCBlock initializer) { print("<%s INITIALIZER>", initializer.isStatic() ? "static" : "instance"); indent++; - if ( printContent ) { + if (printContent) { print("%s", initializer); disablePrinting++; } } - @Override public void endVisitInitializer(Node node, JCBlock initializer) { - if ( printContent ) disablePrinting--; + @Override public void endVisitInitializer(JavacNode node, JCBlock initializer) { + if (printContent) disablePrinting--; indent--; print("</%s INITIALIZER>", initializer.isStatic() ? "static" : "instance"); } - @Override public void visitField(Node node, JCVariableDecl field) { + @Override public void visitField(JavacNode node, JCVariableDecl field) { print("<FIELD %s %s>", field.vartype, field.name); indent++; - if ( printContent ) { - if ( field.init != null ) print("%s", field.init); + if (printContent) { + if (field.init != null) print("%s", field.init); disablePrinting++; } } - @Override public void visitAnnotationOnField(JCVariableDecl field, Node node, JCAnnotation annotation) { + @Override public void visitAnnotationOnField(JCVariableDecl field, JavacNode node, JCAnnotation annotation) { forcePrint("<ANNOTATION: %s />", annotation); } - @Override public void endVisitField(Node node, JCVariableDecl field) { - if ( printContent ) disablePrinting--; + @Override public void endVisitField(JavacNode node, JCVariableDecl field) { + if (printContent) disablePrinting--; indent--; print("</FIELD %s %s>", field.vartype, field.name); } - @Override public void visitMethod(Node node, JCMethodDecl method) { + @Override public void visitMethod(JavacNode node, JCMethodDecl method) { final String type; - if ( method.name.contentEquals("<init>") ) { - if ( (method.mods.flags & Flags.GENERATEDCONSTR) != 0 ) { + if (method.name.contentEquals("<init>")) { + if ((method.mods.flags & Flags.GENERATEDCONSTR) != 0) { type = "DEFAULTCONSTRUCTOR"; } else type = "CONSTRUCTOR"; } else type = "METHOD"; print("<%s %s> returns: %s", type, method.name, method.restype); indent++; - if ( printContent ) { - if ( method.body == null ) print("(ABSTRACT)"); + if (printContent) { + if (method.body == null) print("(ABSTRACT)"); else print("%s", method.body); disablePrinting++; } } - @Override public void visitAnnotationOnMethod(JCMethodDecl method, Node node, JCAnnotation annotation) { + @Override public void visitAnnotationOnMethod(JCMethodDecl method, JavacNode node, JCAnnotation annotation) { forcePrint("<ANNOTATION: %s />", annotation); } - @Override public void endVisitMethod(Node node, JCMethodDecl method) { - if ( printContent ) disablePrinting--; + @Override public void endVisitMethod(JavacNode node, JCMethodDecl method) { + if (printContent) disablePrinting--; indent--; print("</%s %s>", "XMETHOD", method.name); } - @Override public void visitMethodArgument(Node node, JCVariableDecl arg, JCMethodDecl method) { + @Override public void visitMethodArgument(JavacNode node, JCVariableDecl arg, JCMethodDecl method) { print("<METHODARG %s %s>", arg.vartype, arg.name); indent++; } - @Override public void visitAnnotationOnMethodArgument(JCVariableDecl arg, JCMethodDecl method, Node nodeAnnotation, JCAnnotation annotation) { + @Override public void visitAnnotationOnMethodArgument(JCVariableDecl arg, JCMethodDecl method, JavacNode nodeAnnotation, JCAnnotation annotation) { forcePrint("<ANNOTATION: %s />", annotation); } - @Override public void endVisitMethodArgument(Node node, JCVariableDecl arg, JCMethodDecl method) { + @Override public void endVisitMethodArgument(JavacNode node, JCVariableDecl arg, JCMethodDecl method) { indent--; print("</METHODARG %s %s>", arg.vartype, arg.name); } - @Override public void visitLocal(Node node, JCVariableDecl local) { + @Override public void visitLocal(JavacNode node, JCVariableDecl local) { print("<LOCAL %s %s>", local.vartype, local.name); indent++; } - @Override public void visitAnnotationOnLocal(JCVariableDecl local, Node node, JCAnnotation annotation) { + @Override public void visitAnnotationOnLocal(JCVariableDecl local, JavacNode node, JCAnnotation annotation) { print("<ANNOTATION: %s />", annotation); } - @Override public void endVisitLocal(Node node, JCVariableDecl local) { + @Override public void endVisitLocal(JavacNode node, JCVariableDecl local) { indent--; print("</LOCAL %s %s>", local.vartype, local.name); } - @Override public void visitStatement(Node node, JCTree statement) { + @Override public void visitStatement(JavacNode node, JCTree statement) { print("<%s>", statement.getClass()); indent++; print("%s", statement); } - @Override public void endVisitStatement(Node node, JCTree statement) { + @Override public void endVisitStatement(JavacNode node, JCTree statement) { indent--; print("</%s>", statement.getClass()); } diff --git a/src/lombok/javac/JavacAnnotationHandler.java b/src/lombok/javac/JavacAnnotationHandler.java index fcd0cbba..84302a74 100644 --- a/src/lombok/javac/JavacAnnotationHandler.java +++ b/src/lombok/javac/JavacAnnotationHandler.java @@ -54,5 +54,5 @@ public interface JavacAnnotationHandler<T extends Annotation> { * @return <code>true</code> if you don't want to be called again about this annotation during this * compile session (you've handled it), or <code>false</code> to indicate you aren't done yet. */ - boolean handle(AnnotationValues<T> annotation, JCAnnotation ast, JavacAST.Node annotationNode); + boolean handle(AnnotationValues<T> annotation, JCAnnotation ast, JavacNode annotationNode); } diff --git a/src/lombok/javac/JavacNode.java b/src/lombok/javac/JavacNode.java new file mode 100644 index 00000000..102aa050 --- /dev/null +++ b/src/lombok/javac/JavacNode.java @@ -0,0 +1,200 @@ +/* + * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package lombok.javac; + +import java.util.List; + +import javax.tools.Diagnostic; + +import lombok.core.AST.Kind; + +import com.sun.tools.javac.code.Symtab; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCBlock; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.util.Name; +import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; + +/** + * Javac specific version of the LombokNode class. + */ +public class JavacNode extends lombok.core.LombokNode<JavacAST, JavacNode, JCTree> { + /** {@inheritDoc} */ + public JavacNode(JavacAST ast, JCTree node, List<JavacNode> children, Kind kind) { + super(ast, node, children, kind); + } + + /** + * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods. + */ + public void traverse(JavacASTVisitor visitor) { + switch (this.getKind()) { + case COMPILATION_UNIT: + visitor.visitCompilationUnit(this, (JCCompilationUnit)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitCompilationUnit(this, (JCCompilationUnit)get()); + break; + case TYPE: + visitor.visitType(this, (JCClassDecl)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitType(this, (JCClassDecl)get()); + break; + case FIELD: + visitor.visitField(this, (JCVariableDecl)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitField(this, (JCVariableDecl)get()); + break; + case METHOD: + visitor.visitMethod(this, (JCMethodDecl)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitMethod(this, (JCMethodDecl)get()); + break; + case INITIALIZER: + visitor.visitInitializer(this, (JCBlock)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitInitializer(this, (JCBlock)get()); + break; + case ARGUMENT: + JCMethodDecl parent = (JCMethodDecl) up().get(); + visitor.visitMethodArgument(this, (JCVariableDecl)get(), parent); + ast.traverseChildren(visitor, this); + visitor.endVisitMethodArgument(this, (JCVariableDecl)get(), parent); + break; + case LOCAL: + visitor.visitLocal(this, (JCVariableDecl)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitLocal(this, (JCVariableDecl)get()); + break; + case STATEMENT: + visitor.visitStatement(this, get()); + ast.traverseChildren(visitor, this); + visitor.endVisitStatement(this, get()); + break; + case ANNOTATION: + switch (up().getKind()) { + case TYPE: + visitor.visitAnnotationOnType((JCClassDecl)up().get(), this, (JCAnnotation)get()); + break; + case FIELD: + visitor.visitAnnotationOnField((JCVariableDecl)up().get(), this, (JCAnnotation)get()); + break; + case METHOD: + visitor.visitAnnotationOnMethod((JCMethodDecl)up().get(), this, (JCAnnotation)get()); + break; + case ARGUMENT: + JCVariableDecl argument = (JCVariableDecl)up().get(); + JCMethodDecl method = (JCMethodDecl)up().up().get(); + visitor.visitAnnotationOnMethodArgument(argument, method, this, (JCAnnotation)get()); + break; + case LOCAL: + visitor.visitAnnotationOnLocal((JCVariableDecl)up().get(), this, (JCAnnotation)get()); + break; + default: + throw new AssertionError("Annotion not expected as child of a " + up().getKind()); + } + break; + default: + throw new AssertionError("Unexpected kind during node traversal: " + getKind()); + } + } + + /** {@inheritDoc} */ + @Override public String getName() { + final Name n; + + if (node instanceof JCClassDecl) n = ((JCClassDecl)node).name; + else if (node instanceof JCMethodDecl) n = ((JCMethodDecl)node).name; + else if (node instanceof JCVariableDecl) n = ((JCVariableDecl)node).name; + else n = null; + + return n == null ? null : n.toString(); + } + + /** {@inheritDoc} */ + @Override protected boolean calculateIsStructurallySignificant() { + if (node instanceof JCClassDecl) return true; + if (node instanceof JCMethodDecl) return true; + if (node instanceof JCVariableDecl) return true; + if (node instanceof JCCompilationUnit) return true; + return false; + } + + /** + * Convenient shortcut to the owning JavacAST object's getTreeMaker method. + * + * @see JavacAST#getTreeMaker() + */ + public TreeMaker getTreeMaker() { + return ast.getTreeMaker(); + } + + /** + * Convenient shortcut to the owning JavacAST object's getSymbolTable method. + * + * @see JavacAST#getSymbolTable() + */ + public Symtab getSymbolTable() { + return ast.getSymbolTable(); + } + + /** + * Convenient shortcut to the owning JavacAST object's toName method. + * + * @see JavacAST#toName(String) + */ + public Name toName(String name) { + return ast.toName(name); + } + + /** + * Generates an compiler error focused on the AST node represented by this node object. + */ + public void addError(String message) { + ast.printMessage(Diagnostic.Kind.ERROR, message, this, null); + } + + /** + * Generates an compiler error focused on the AST node represented by this node object. + */ + public void addError(String message, DiagnosticPosition pos) { + ast.printMessage(Diagnostic.Kind.ERROR, message, null, pos); + } + + /** + * Generates a compiler warning focused on the AST node represented by this node object. + */ + public void addWarning(String message) { + ast.printMessage(Diagnostic.Kind.WARNING, message, this, null); + } + + /** + * Generates a compiler warning focused on the AST node represented by this node object. + */ + public void addWarning(String message, DiagnosticPosition pos) { + ast.printMessage(Diagnostic.Kind.WARNING, message, null, pos); + } +} diff --git a/src/lombok/javac/apt/Processor.java b/src/lombok/javac/apt/Processor.java index 44edd917..0c187f4b 100644 --- a/src/lombok/javac/apt/Processor.java +++ b/src/lombok/javac/apt/Processor.java @@ -39,7 +39,7 @@ import javax.tools.Diagnostic.Kind; import lombok.javac.HandlerLibrary; import lombok.javac.JavacAST; import lombok.javac.JavacASTAdapter; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; @@ -71,7 +71,7 @@ public class Processor extends AbstractProcessor { /** {@inheritDoc} */ @Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); - if ( !(processingEnv instanceof JavacProcessingEnvironment) ) { + if (!(processingEnv instanceof JavacProcessingEnvironment)) { processingEnv.getMessager().printMessage(Kind.WARNING, "You aren't using a compiler based around javac v1.6, so lombok will not work properly."); this.processingEnv = null; } else { @@ -83,72 +83,71 @@ public class Processor extends AbstractProcessor { /** {@inheritDoc} */ @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { - if ( processingEnv == null ) return false; - + if (processingEnv == null) return false; IdentityHashMap<JCCompilationUnit, Void> units = new IdentityHashMap<JCCompilationUnit, Void>(); - for ( Element element : roundEnv.getRootElements() ) { + for (Element element : roundEnv.getRootElements()) { JCCompilationUnit unit = toUnit(element); - if ( unit != null ) units.put(unit, null); + if (unit != null) units.put(unit, null); } List<JavacAST> asts = new ArrayList<JavacAST>(); - for ( JCCompilationUnit unit : units.keySet() ) asts.add(new JavacAST(trees, processingEnv, unit)); + for (JCCompilationUnit unit : units.keySet()) asts.add(new JavacAST(trees, processingEnv, unit)); handlers.skipPrintAST(); - for ( JavacAST ast : asts ) { + for (JavacAST ast : asts) { ast.traverse(new AnnotationVisitor()); handlers.callASTVisitors(ast); } handlers.skipAllButPrintAST(); - for ( JavacAST ast : asts ) { + for (JavacAST ast : asts) { ast.traverse(new AnnotationVisitor()); } return false; } private class AnnotationVisitor extends JavacASTAdapter { - @Override public void visitAnnotationOnType(JCClassDecl type, Node annotationNode, JCAnnotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnType(JCClassDecl type, JavacNode annotationNode, JCAnnotation annotation) { + if (annotationNode.isHandled()) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnField(JCVariableDecl field, Node annotationNode, JCAnnotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnField(JCVariableDecl field, JavacNode annotationNode, JCAnnotation annotation) { + if (annotationNode.isHandled()) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnMethod(JCMethodDecl method, Node annotationNode, JCAnnotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnMethod(JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) { + if (annotationNode.isHandled()) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, Node annotationNode, JCAnnotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, JavacNode annotationNode, JCAnnotation annotation) { + if (annotationNode.isHandled()) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnLocal(JCVariableDecl local, Node annotationNode, JCAnnotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnLocal(JCVariableDecl local, JavacNode annotationNode, JCAnnotation annotation) { + if (annotationNode.isHandled()) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } } private JCCompilationUnit toUnit(Element element) { TreePath path = trees == null ? null : trees.getPath(element); - if ( path == null ) return null; + if (path == null) return null; return (JCCompilationUnit) path.getCompilationUnit(); } diff --git a/src/lombok/javac/handlers/HandleCleanup.java b/src/lombok/javac/handlers/HandleCleanup.java index 7a2f232d..acee24b1 100644 --- a/src/lombok/javac/handlers/HandleCleanup.java +++ b/src/lombok/javac/handlers/HandleCleanup.java @@ -25,7 +25,7 @@ import lombok.Cleanup; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; @@ -52,34 +52,34 @@ import com.sun.tools.javac.util.Name; */ @ProviderFor(JavacAnnotationHandler.class) public class HandleCleanup implements JavacAnnotationHandler<Cleanup> { - @Override public boolean handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, Node annotationNode) { + @Override public boolean handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) { String cleanupName = annotation.getInstance().value(); - if ( cleanupName.length() == 0 ) { + if (cleanupName.length() == 0) { annotationNode.addError("cleanupName cannot be the empty string."); return true; } - if ( annotationNode.up().getKind() != Kind.LOCAL ) { + if (annotationNode.up().getKind() != Kind.LOCAL) { annotationNode.addError("@Cleanup is legal only on local variable declarations."); return true; } JCVariableDecl decl = (JCVariableDecl)annotationNode.up().get(); - if ( decl.init == null ) { + if (decl.init == null) { annotationNode.addError("@Cleanup variable declarations need to be initialized."); return true; } - Node ancestor = annotationNode.up().directUp(); + JavacNode ancestor = annotationNode.up().directUp(); JCTree blockNode = ancestor.get(); final List<JCStatement> statements; - if ( blockNode instanceof JCBlock ) { + if (blockNode instanceof JCBlock) { statements = ((JCBlock)blockNode).stats; - } else if ( blockNode instanceof JCCase ) { + } else if (blockNode instanceof JCCase) { statements = ((JCCase)blockNode).stats; - } else if ( blockNode instanceof JCMethodDecl ) { + } else if (blockNode instanceof JCMethodDecl) { statements = ((JCMethodDecl)blockNode).body.stats; } else { annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block."); @@ -89,14 +89,16 @@ public class HandleCleanup implements JavacAnnotationHandler<Cleanup> { boolean seenDeclaration = false; List<JCStatement> tryBlock = List.nil(); List<JCStatement> newStatements = List.nil(); - for ( JCStatement statement : statements ) { - if ( !seenDeclaration ) { - if ( statement == decl ) seenDeclaration = true; + for (JCStatement statement : statements) { + if (!seenDeclaration) { + if (statement == decl) seenDeclaration = true; newStatements = newStatements.append(statement); - } else tryBlock = tryBlock.append(statement); + } else { + tryBlock = tryBlock.append(statement); + } } - if ( !seenDeclaration ) { + if (!seenDeclaration) { annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent."); return true; } @@ -111,11 +113,11 @@ public class HandleCleanup implements JavacAnnotationHandler<Cleanup> { JCBlock finalizer = maker.Block(0, finalizerBlock); newStatements = newStatements.append(maker.Try(maker.Block(0, tryBlock), List.<JCCatch>nil(), finalizer)); - if ( blockNode instanceof JCBlock ) { + if (blockNode instanceof JCBlock) { ((JCBlock)blockNode).stats = newStatements; - } else if ( blockNode instanceof JCCase ) { + } else if (blockNode instanceof JCCase) { ((JCCase)blockNode).stats = newStatements; - } else if ( blockNode instanceof JCMethodDecl ) { + } else if (blockNode instanceof JCMethodDecl) { ((JCMethodDecl)blockNode).body.stats = newStatements; } else throw new AssertionError("Should not get here"); @@ -124,20 +126,20 @@ public class HandleCleanup implements JavacAnnotationHandler<Cleanup> { return true; } - private void doAssignmentCheck(Node node, List<JCStatement> statements, Name name) { - for ( JCStatement statement : statements ) doAssignmentCheck0(node, statement, name); + private void doAssignmentCheck(JavacNode node, List<JCStatement> statements, Name name) { + for (JCStatement statement : statements) doAssignmentCheck0(node, statement, name); } - private void doAssignmentCheck0(Node node, JCTree statement, Name name) { - if ( statement instanceof JCAssign ) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name); - if ( statement instanceof JCExpressionStatement ) doAssignmentCheck0(node, + private void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) { + if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name); + if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node, ((JCExpressionStatement)statement).expr, name); - if ( statement instanceof JCVariableDecl ) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name); - if ( statement instanceof JCTypeCast ) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name); - if ( statement instanceof JCIdent ) { - if ( ((JCIdent)statement).name.contentEquals(name) ) { - Node problemNode = node.getNodeFor(statement); - if ( problemNode != null ) problemNode.addWarning( + if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name); + if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name); + if (statement instanceof JCIdent) { + if (((JCIdent)statement).name.contentEquals(name)) { + JavacNode problemNode = node.getNodeFor(statement); + if (problemNode != null) problemNode.addWarning( "You're assigning an auto-cleanup variable to something else. This is a bad idea."); } } diff --git a/src/lombok/javac/handlers/HandleData.java b/src/lombok/javac/handlers/HandleData.java index 2e1d01b1..f18af241 100644 --- a/src/lombok/javac/handlers/HandleData.java +++ b/src/lombok/javac/handlers/HandleData.java @@ -30,7 +30,7 @@ import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import lombok.javac.handlers.PKG.MemberExistsResult; import org.mangosdk.spi.ProviderFor; @@ -58,32 +58,32 @@ import com.sun.tools.javac.util.List; */ @ProviderFor(JavacAnnotationHandler.class) public class HandleData implements JavacAnnotationHandler<Data> { - @Override public boolean handle(AnnotationValues<Data> annotation, JCAnnotation ast, Node annotationNode) { - Node typeNode = annotationNode.up(); + @Override public boolean handle(AnnotationValues<Data> annotation, JCAnnotation ast, JavacNode annotationNode) { + JavacNode typeNode = annotationNode.up(); JCClassDecl typeDecl = null; - if ( typeNode.get() instanceof JCClassDecl ) typeDecl = (JCClassDecl)typeNode.get(); + if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl)typeNode.get(); long flags = typeDecl == null ? 0 : typeDecl.mods.flags; boolean notAClass = (flags & (Flags.INTERFACE | Flags.ENUM | Flags.ANNOTATION)) != 0; - if ( typeDecl == null || notAClass ) { + if (typeDecl == null || notAClass) { annotationNode.addError("@Data is only supported on a class."); return false; } - List<Node> nodesForEquality = List.nil(); - List<Node> nodesForConstructor = List.nil(); - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + List<JavacNode> nodesForEquality = List.nil(); + List<JavacNode> nodesForConstructor = List.nil(); + for (JavacNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); long fieldFlags = fieldDecl.mods.flags; //Skip static fields. - if ( (fieldFlags & Flags.STATIC) != 0 ) continue; - if ( (fieldFlags & Flags.TRANSIENT) == 0 ) nodesForEquality = nodesForEquality.append(child); + if ((fieldFlags & Flags.STATIC) != 0) continue; + if ((fieldFlags & Flags.TRANSIENT) == 0) nodesForEquality = nodesForEquality.append(child); boolean isFinal = (fieldFlags & Flags.FINAL) != 0; boolean isNonNull = !findAnnotations(child, TransformationsUtil.NON_NULL_PATTERN).isEmpty(); - if ( (isFinal || isNonNull) && fieldDecl.init == null ) nodesForConstructor = nodesForConstructor.append(child); + if ((isFinal || isNonNull) && fieldDecl.init == null) nodesForConstructor = nodesForConstructor.append(child); new HandleGetter().generateGetterForField(child, annotationNode.get()); - if ( !isFinal ) new HandleSetter().generateSetterForField(child, annotationNode.get()); + if (!isFinal) new HandleSetter().generateSetterForField(child, annotationNode.get()); } new HandleToString().generateToStringForType(typeNode, annotationNode); @@ -91,12 +91,12 @@ public class HandleData implements JavacAnnotationHandler<Data> { String staticConstructorName = annotation.getInstance().staticConstructor(); - if ( constructorExists(typeNode) == MemberExistsResult.NOT_EXISTS ) { + if (constructorExists(typeNode) == MemberExistsResult.NOT_EXISTS) { JCMethodDecl constructor = createConstructor(staticConstructorName.equals(""), typeNode, nodesForConstructor); injectMethod(typeNode, constructor); } - if ( !staticConstructorName.isEmpty() && methodExists("of", typeNode) == MemberExistsResult.NOT_EXISTS ) { + if (!staticConstructorName.isEmpty() && methodExists("of", typeNode) == MemberExistsResult.NOT_EXISTS) { JCMethodDecl staticConstructor = createStaticConstructor(staticConstructorName, typeNode, nodesForConstructor); injectMethod(typeNode, staticConstructor); } @@ -104,7 +104,7 @@ public class HandleData implements JavacAnnotationHandler<Data> { return true; } - private JCMethodDecl createConstructor(boolean isPublic, Node typeNode, List<Node> fields) { + private JCMethodDecl createConstructor(boolean isPublic, JavacNode typeNode, List<JavacNode> fields) { TreeMaker maker = typeNode.getTreeMaker(); JCClassDecl type = (JCClassDecl) typeNode.get(); @@ -112,7 +112,7 @@ public class HandleData implements JavacAnnotationHandler<Data> { List<JCStatement> assigns = List.nil(); List<JCVariableDecl> params = List.nil(); - for ( Node fieldNode : fields ) { + for (JavacNode fieldNode : fields) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); List<JCAnnotation> nonNulls = findAnnotations(fieldNode, TransformationsUtil.NON_NULL_PATTERN); List<JCAnnotation> nullables = findAnnotations(fieldNode, TransformationsUtil.NULLABLE_PATTERN); @@ -133,7 +133,7 @@ public class HandleData implements JavacAnnotationHandler<Data> { null, type.typarams, params, List.<JCExpression>nil(), maker.Block(0L, nullChecks.appendList(assigns)), null); } - private JCMethodDecl createStaticConstructor(String name, Node typeNode, List<Node> fields) { + private JCMethodDecl createStaticConstructor(String name, JavacNode typeNode, List<JavacNode> fields) { TreeMaker maker = typeNode.getTreeMaker(); JCClassDecl type = (JCClassDecl) typeNode.get(); @@ -147,8 +147,8 @@ public class HandleData implements JavacAnnotationHandler<Data> { List<JCExpression> typeArgs2 = List.nil(); List<JCExpression> args = List.nil(); - if ( !type.typarams.isEmpty() ) { - for ( JCTypeParameter param : type.typarams ) { + if (!type.typarams.isEmpty()) { + for (JCTypeParameter param : type.typarams) { typeArgs1 = typeArgs1.append(maker.Ident(param.name)); typeArgs2 = typeArgs2.append(maker.Ident(param.name)); typeParams = typeParams.append(maker.TypeParameter(param.name, param.bounds)); @@ -160,16 +160,18 @@ public class HandleData implements JavacAnnotationHandler<Data> { constructorType = maker.Ident(type.name); } - for ( Node fieldNode : fields ) { + for (JavacNode fieldNode : fields) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); JCExpression pType; - if ( field.vartype instanceof JCIdent ) pType = maker.Ident(((JCIdent)field.vartype).name); - else if ( field.vartype instanceof JCTypeApply ) { + if (field.vartype instanceof JCIdent) pType = maker.Ident(((JCIdent)field.vartype).name); + else if (field.vartype instanceof JCTypeApply) { JCTypeApply typeApply = (JCTypeApply) field.vartype; List<JCExpression> tArgs = List.nil(); - for ( JCExpression arg : typeApply.arguments ) tArgs = tArgs.append(arg); + for (JCExpression arg : typeApply.arguments) tArgs = tArgs.append(arg); pType = maker.TypeApply(typeApply.clazz, tArgs); - } else pType = field.vartype; + } else { + pType = field.vartype; + } List<JCAnnotation> nonNulls = findAnnotations(fieldNode, TransformationsUtil.NON_NULL_PATTERN); List<JCAnnotation> nullables = findAnnotations(fieldNode, TransformationsUtil.NULLABLE_PATTERN); JCVariableDecl param = maker.VarDef(maker.Modifiers(Flags.FINAL, nonNulls.appendList(nullables)), field.name, pType, null); diff --git a/src/lombok/javac/handlers/HandleEqualsAndHashCode.java b/src/lombok/javac/handlers/HandleEqualsAndHashCode.java index 21966be2..fa1f4d0d 100644 --- a/src/lombok/javac/handlers/HandleEqualsAndHashCode.java +++ b/src/lombok/javac/handlers/HandleEqualsAndHashCode.java @@ -27,7 +27,7 @@ import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; @@ -58,33 +58,33 @@ import com.sun.tools.javac.util.Name; */ @ProviderFor(JavacAnnotationHandler.class) public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAndHashCode> { - private void checkForBogusFieldNames(Node type, AnnotationValues<EqualsAndHashCode> annotation) { - if ( annotation.isExplicit("exclude") ) { - for ( int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, true) ) { + private void checkForBogusFieldNames(JavacNode type, AnnotationValues<EqualsAndHashCode> annotation) { + if (annotation.isExplicit("exclude")) { + for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, true)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } - if ( annotation.isExplicit("of") ) { - for ( int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false) ) { + if (annotation.isExplicit("of")) { + for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } - @Override public boolean handle(AnnotationValues<EqualsAndHashCode> annotation, JCAnnotation ast, Node annotationNode) { + @Override public boolean handle(AnnotationValues<EqualsAndHashCode> annotation, JCAnnotation ast, JavacNode annotationNode) { EqualsAndHashCode ann = annotation.getInstance(); List<String> excludes = List.from(ann.exclude()); List<String> includes = List.from(ann.of()); - Node typeNode = annotationNode.up(); + JavacNode typeNode = annotationNode.up(); checkForBogusFieldNames(typeNode, annotation); Boolean callSuper = ann.callSuper(); - if ( !annotation.isExplicit("callSuper") ) callSuper = null; - if ( !annotation.isExplicit("exclude") ) excludes = null; - if ( !annotation.isExplicit("of") ) includes = null; + if (!annotation.isExplicit("callSuper")) callSuper = null; + if (!annotation.isExplicit("exclude")) excludes = null; + if (!annotation.isExplicit("of")) includes = null; - if ( excludes != null && includes != null ) { + if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } @@ -92,10 +92,10 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd return generateMethods(typeNode, annotationNode, excludes, includes, callSuper, true); } - public void generateEqualsAndHashCodeForType(Node typeNode, Node errorNode) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( Javac.annotationTypeMatches(EqualsAndHashCode.class, child) ) { + public void generateEqualsAndHashCodeForType(JavacNode typeNode, JavacNode errorNode) { + for (JavacNode child : typeNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (Javac.annotationTypeMatches(EqualsAndHashCode.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -105,66 +105,66 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd generateMethods(typeNode, errorNode, null, null, null, false); } - private boolean generateMethods(Node typeNode, Node errorNode, List<String> excludes, List<String> includes, + private boolean generateMethods(JavacNode typeNode, JavacNode errorNode, List<String> excludes, List<String> includes, Boolean callSuper, boolean whineIfExists) { boolean notAClass = true; - if ( typeNode.get() instanceof JCClassDecl ) { + if (typeNode.get() instanceof JCClassDecl) { long flags = ((JCClassDecl)typeNode.get()).mods.flags; notAClass = (flags & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; } - if ( notAClass ) { + if (notAClass) { errorNode.addError("@EqualsAndHashCode is only supported on a class."); return false; } boolean isDirectDescendantOfObject = true; boolean implicitCallSuper = callSuper == null; - if ( callSuper == null ) { + if (callSuper == null) { try { callSuper = ((Boolean)EqualsAndHashCode.class.getMethod("callSuper").getDefaultValue()).booleanValue(); - } catch ( Exception ignore ) {} + } catch (Exception ignore) {} } JCTree extending = ((JCClassDecl)typeNode.get()).extending; - if ( extending != null ) { + if (extending != null) { String p = extending.toString(); isDirectDescendantOfObject = p.equals("Object") || p.equals("java.lang.Object"); } - if ( isDirectDescendantOfObject && callSuper ) { + if (isDirectDescendantOfObject && callSuper) { errorNode.addError("Generating equals/hashCode with a supercall to java.lang.Object is pointless."); return true; } - if ( !isDirectDescendantOfObject && !callSuper && implicitCallSuper ) { + if (!isDirectDescendantOfObject && !callSuper && implicitCallSuper) { errorNode.addWarning("Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '@EqualsAndHashCode(callSuper=false)' to your type."); } - List<Node> nodesForEquality = List.nil(); - if ( includes != null ) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + List<JavacNode> nodesForEquality = List.nil(); + if (includes != null) { + for (JavacNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); - if ( includes.contains(fieldDecl.name.toString()) ) nodesForEquality = nodesForEquality.append(child); + if (includes.contains(fieldDecl.name.toString())) nodesForEquality = nodesForEquality.append(child); } } else { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + for (JavacNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); //Skip static fields. - if ( (fieldDecl.mods.flags & Flags.STATIC) != 0 ) continue; + if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; //Skip transient fields. - if ( (fieldDecl.mods.flags & Flags.TRANSIENT) != 0 ) continue; + if ((fieldDecl.mods.flags & Flags.TRANSIENT) != 0) continue; //Skip excluded fields. - if ( excludes != null && excludes.contains(fieldDecl.name.toString()) ) continue; + if (excludes != null && excludes.contains(fieldDecl.name.toString())) continue; //Skip fields that start with $ - if ( fieldDecl.name.toString().startsWith("$") ) continue; + if (fieldDecl.name.toString().startsWith("$")) continue; nodesForEquality = nodesForEquality.append(child); } } - switch ( methodExists("hashCode", typeNode) ) { + switch (methodExists("hashCode", typeNode)) { case NOT_EXISTS: JCMethodDecl method = createHashCode(typeNode, nodesForEquality, callSuper); injectMethod(typeNode, method); @@ -173,13 +173,13 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd break; default: case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { errorNode.addWarning("Not generating hashCode(): A method with that name already exists"); } break; } - switch ( methodExists("equals", typeNode) ) { + switch (methodExists("equals", typeNode)) { case NOT_EXISTS: JCMethodDecl method = createEquals(typeNode, nodesForEquality, callSuper); injectMethod(typeNode, method); @@ -188,7 +188,7 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd break; default: case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { errorNode.addWarning("Not generating equals(Object other): A method with that name already exists"); } break; @@ -197,7 +197,7 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd return true; } - private JCMethodDecl createHashCode(Node typeNode, List<Node> fields, boolean callSuper) { + private JCMethodDecl createHashCode(JavacNode typeNode, List<JavacNode> fields, boolean callSuper) { TreeMaker maker = typeNode.getTreeMaker(); JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); @@ -208,9 +208,9 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd Name primeName = typeNode.toName("PRIME"); Name resultName = typeNode.toName("result"); /* final int PRIME = 31; */ { - if ( !fields.isEmpty() || callSuper ) { - statements = statements.append( - maker.VarDef(maker.Modifiers(Flags.FINAL), primeName, maker.TypeIdent(TypeTags.INT), maker.Literal(31))); + if (!fields.isEmpty() || callSuper) { + statements = statements.append(maker.VarDef(maker.Modifiers(Flags.FINAL), + primeName, maker.TypeIdent(TypeTags.INT), maker.Literal(31))); } } @@ -220,7 +220,7 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd List<JCExpression> intoResult = List.nil(); - if ( callSuper ) { + if (callSuper) { JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("hashCode")), List.<JCExpression>nil()); @@ -228,13 +228,13 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd } int tempCounter = 0; - for ( Node fieldNode : fields ) { + for (JavacNode fieldNode : fields) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); JCExpression fType = field.vartype; JCExpression thisDotField = maker.Select(maker.Ident(typeNode.toName("this")), field.name); JCExpression thisDotFieldClone = maker.Select(maker.Ident(typeNode.toName("this")), field.name); - if ( fType instanceof JCPrimitiveTypeTree ) { - switch ( ((JCPrimitiveTypeTree)fType).getPrimitiveTypeKind() ) { + if (fType instanceof JCPrimitiveTypeTree) { + switch (((JCPrimitiveTypeTree)fType).getPrimitiveTypeKind()) { case BOOLEAN: /* this.fieldName ? 1231 : 1237 */ intoResult = intoResult.append(maker.Conditional(thisDotField, maker.Literal(1231), maker.Literal(1237))); @@ -269,7 +269,7 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd intoResult = intoResult.append(thisDotField); break; } - } else if ( fType instanceof JCArrayTypeTree ) { + } else if (fType instanceof JCArrayTypeTree) { /* java.util.Arrays.deepHashCode(this.fieldName) //use just hashCode() for primitive arrays. */ boolean multiDim = ((JCArrayTypeTree)fType).elemtype instanceof JCArrayTypeTree; boolean primitiveArray = ((JCArrayTypeTree)fType).elemtype instanceof JCPrimitiveTypeTree; @@ -290,7 +290,7 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd /* fold each intoResult entry into: result = result * PRIME + (item); */ - for ( JCExpression expr : intoResult ) { + for (JCExpression expr : intoResult) { JCExpression mult = maker.Binary(JCTree.MUL, maker.Ident(resultName), maker.Ident(primeName)); JCExpression add = maker.Binary(JCTree.PLUS, mult, expr); statements = statements.append(maker.Exec(maker.Assign(maker.Ident(resultName), add))); @@ -313,7 +313,7 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd return maker.TypeCast(maker.TypeIdent(TypeTags.INT), xorBits); } - private JCMethodDecl createEquals(Node typeNode, List<Node> fields, boolean callSuper) { + private JCMethodDecl createEquals(JavacNode typeNode, List<JavacNode> fields, boolean callSuper) { TreeMaker maker = typeNode.getTreeMaker(); JCClassDecl type = (JCClassDecl) typeNode.get(); @@ -329,17 +329,17 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd List<JCStatement> statements = List.nil(); List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(Flags.FINAL), oName, objectType, null)); - /* if ( o == this ) return true; */ { - statements = statements.append( - maker.If(maker.Binary(JCTree.EQ, maker.Ident(oName), maker.Ident(thisName)), returnBool(maker, true), null)); + /* if (o == this) return true; */ { + statements = statements.append(maker.If(maker.Binary(JCTree.EQ, maker.Ident(oName), + maker.Ident(thisName)), returnBool(maker, true), null)); } - /* if ( o == null ) return false; */ { - statements = statements.append( - maker.If(maker.Binary(JCTree.EQ, maker.Ident(oName), maker.Literal(TypeTags.BOT, null)), returnBool(maker, false), null)); + /* if (o == null) return false; */ { + statements = statements.append(maker.If(maker.Binary(JCTree.EQ, maker.Ident(oName), + maker.Literal(TypeTags.BOT, null)), returnBool(maker, false), null)); } - /* if ( o.getClass() != this.getClass() ) return false; */ { + /* if (o.getClass() != this.getClass()) return false; */ { Name getClass = typeNode.toName("getClass"); List<JCExpression> exprNil = List.nil(); JCExpression oGetClass = maker.Apply(exprNil, maker.Select(maker.Ident(oName), getClass), exprNil); @@ -348,8 +348,8 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd maker.If(maker.Binary(JCTree.NE, oGetClass, thisGetClass), returnBool(maker, false), null)); } - /* if ( !super.equals(o) ) return false; */ - if ( callSuper ) { + /* if (!super.equals(o)) return false; */ + if (callSuper) { JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("equals")), List.<JCExpression>of(maker.Ident(oName))); @@ -361,12 +361,12 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd final JCExpression selfType1, selfType2; List<JCExpression> wildcards1 = List.nil(); List<JCExpression> wildcards2 = List.nil(); - for ( int i = 0 ; i < type.typarams.length() ; i++ ) { + for (int i = 0 ; i < type.typarams.length() ; i++) { wildcards1 = wildcards1.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); wildcards2 = wildcards2.append(maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null)); } - if ( type.typarams.isEmpty() ) { + if (type.typarams.isEmpty()) { selfType1 = maker.Ident(type.name); selfType2 = maker.Ident(type.name); } else { @@ -378,29 +378,29 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd maker.VarDef(maker.Modifiers(Flags.FINAL), otherName, selfType1, maker.TypeCast(selfType2, maker.Ident(oName)))); } - for ( Node fieldNode : fields ) { + for (JavacNode fieldNode : fields) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); JCExpression fType = field.vartype; JCExpression thisDotField = maker.Select(maker.Ident(thisName), field.name); JCExpression otherDotField = maker.Select(maker.Ident(otherName), field.name); - if ( fType instanceof JCPrimitiveTypeTree ) { - switch ( ((JCPrimitiveTypeTree)fType).getPrimitiveTypeKind() ) { + if (fType instanceof JCPrimitiveTypeTree) { + switch (((JCPrimitiveTypeTree)fType).getPrimitiveTypeKind()) { case FLOAT: - /* if ( Float.compare(this.fieldName, other.fieldName) != 0 ) return false; */ + /* if (Float.compare(this.fieldName, other.fieldName) != 0) return false; */ statements = statements.append(generateCompareFloatOrDouble(thisDotField, otherDotField, maker, typeNode, false)); break; case DOUBLE: - /* if ( Double(this.fieldName, other.fieldName) != 0 ) return false; */ + /* if (Double(this.fieldName, other.fieldName) != 0) return false; */ statements = statements.append(generateCompareFloatOrDouble(thisDotField, otherDotField, maker, typeNode, true)); break; default: - /* if ( this.fieldName != other.fieldName ) return false; */ + /* if (this.fieldName != other.fieldName) return false; */ statements = statements.append( maker.If(maker.Binary(JCTree.NE, thisDotField, otherDotField), returnBool(maker, false), null)); break; } - } else if ( fType instanceof JCArrayTypeTree ) { - /* if ( !java.util.Arrays.deepEquals(this.fieldName, other.fieldName) ) return false; //use equals for primitive arrays. */ + } else if (fType instanceof JCArrayTypeTree) { + /* if (!java.util.Arrays.deepEquals(this.fieldName, other.fieldName)) return false; //use equals for primitive arrays. */ boolean multiDim = ((JCArrayTypeTree)fType).elemtype instanceof JCArrayTypeTree; boolean primitiveArray = ((JCArrayTypeTree)fType).elemtype instanceof JCPrimitiveTypeTree; boolean useDeepEquals = multiDim || !primitiveArray; @@ -410,7 +410,7 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd statements = statements.append(maker.If(maker.Unary(JCTree.NOT, maker.Apply(List.<JCExpression>nil(), eqMethod, args)), returnBool(maker, false), null)); } else /* objects */ { - /* if ( this.fieldName == null ? other.fieldName != null : !this.fieldName.equals(other.fieldName) ) return false; */ + /* if (this.fieldName == null ? other.fieldName != null : !this.fieldName.equals(other.fieldName)) return false; */ JCExpression thisEqualsNull = maker.Binary(JCTree.EQ, thisDotField, maker.Literal(TypeTags.BOT, null)); JCExpression otherNotEqualsNull = maker.Binary(JCTree.NE, otherDotField, maker.Literal(TypeTags.BOT, null)); JCExpression thisEqualsThat = maker.Apply( @@ -428,8 +428,9 @@ public class HandleEqualsAndHashCode implements JavacAnnotationHandler<EqualsAnd return maker.MethodDef(mods, typeNode.toName("equals"), returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null); } - private JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField, TreeMaker maker, Node node, boolean isDouble) { - /* if ( Float.compare(fieldName, other.fieldName) != 0 ) return false; */ + private JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField, + TreeMaker maker, JavacNode node, boolean isDouble) { + /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */ JCExpression clazz = chainDots(maker, node, "java", "lang", isDouble ? "Double" : "Float"); List<JCExpression> args = List.of(thisDotField, otherDotField); JCBinary compareCallEquals0 = maker.Binary(JCTree.NE, maker.Apply( diff --git a/src/lombok/javac/handlers/HandleGetter.java b/src/lombok/javac/handlers/HandleGetter.java index 47cd3095..fd39bda2 100644 --- a/src/lombok/javac/handlers/HandleGetter.java +++ b/src/lombok/javac/handlers/HandleGetter.java @@ -29,7 +29,7 @@ import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; @@ -63,10 +63,10 @@ public class HandleGetter implements JavacAnnotationHandler<Getter> { * If not, the getter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. */ - public void generateGetterForField(Node fieldNode, DiagnosticPosition pos) { - for ( Node child : fieldNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( Javac.annotationTypeMatches(Getter.class, child) ) { + public void generateGetterForField(JavacNode fieldNode, DiagnosticPosition pos) { + for (JavacNode child : fieldNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (Javac.annotationTypeMatches(Getter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -76,16 +76,17 @@ public class HandleGetter implements JavacAnnotationHandler<Getter> { createGetterForField(AccessLevel.PUBLIC, fieldNode, fieldNode, pos, false); } - @Override public boolean handle(AnnotationValues<Getter> annotation, JCAnnotation ast, Node annotationNode) { - Node fieldNode = annotationNode.up(); + @Override public boolean handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacNode annotationNode) { + JavacNode fieldNode = annotationNode.up(); AccessLevel level = annotation.getInstance().value(); - if ( level == AccessLevel.NONE ) return true; + if (level == AccessLevel.NONE) return true; return createGetterForField(level, fieldNode, annotationNode, annotationNode.get(), true); } - private boolean createGetterForField(AccessLevel level, Node fieldNode, Node errorNode, DiagnosticPosition pos, boolean whineIfExists) { - if ( fieldNode.getKind() != Kind.FIELD ) { + private boolean createGetterForField(AccessLevel level, + JavacNode fieldNode, JavacNode errorNode, DiagnosticPosition pos, boolean whineIfExists) { + if (fieldNode.getKind() != Kind.FIELD) { errorNode.addError("@Getter is only supported on a field."); return true; } @@ -93,14 +94,14 @@ public class HandleGetter implements JavacAnnotationHandler<Getter> { JCVariableDecl fieldDecl = (JCVariableDecl)fieldNode.get(); String methodName = toGetterName(fieldDecl); - for ( String altName : toAllGetterNames(fieldDecl) ) { - switch ( methodExists(altName, fieldNode) ) { + for (String altName : toAllGetterNames(fieldDecl)) { + switch (methodExists(altName, fieldNode)) { case EXISTS_BY_LOMBOK: return true; case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { String altNameExpl = ""; - if ( !altName.equals(methodName) ) altNameExpl = String.format(" (%s)", altName); + if (!altName.equals(methodName)) altNameExpl = String.format(" (%s)", altName); errorNode.addWarning( String.format("Not generating %s(): A method with that name already exists%s", methodName, altNameExpl)); } @@ -118,7 +119,7 @@ public class HandleGetter implements JavacAnnotationHandler<Getter> { return true; } - private JCMethodDecl createGetter(long access, Node field, TreeMaker treeMaker) { + private JCMethodDecl createGetter(long access, JavacNode field, TreeMaker treeMaker) { JCVariableDecl fieldNode = (JCVariableDecl) field.get(); JCStatement returnStatement = treeMaker.Return(treeMaker.Ident(fieldNode.getName())); diff --git a/src/lombok/javac/handlers/HandlePrintAST.java b/src/lombok/javac/handlers/HandlePrintAST.java index aa7b0ab9..77ecd54f 100644 --- a/src/lombok/javac/handlers/HandlePrintAST.java +++ b/src/lombok/javac/handlers/HandlePrintAST.java @@ -34,19 +34,19 @@ import lombok.core.AnnotationValues; import lombok.core.PrintAST; import lombok.javac.JavacASTVisitor; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; /** * Handles the <code>lombok.core.PrintAST</code> annotation for javac. */ @ProviderFor(JavacAnnotationHandler.class) public class HandlePrintAST implements JavacAnnotationHandler<PrintAST> { - @Override public boolean handle(AnnotationValues<PrintAST> annotation, JCAnnotation ast, Node annotationNode) { + @Override public boolean handle(AnnotationValues<PrintAST> annotation, JCAnnotation ast, JavacNode annotationNode) { PrintStream stream = System.out; String fileName = annotation.getInstance().outfile(); - if ( fileName.length() > 0 ) try { + if (fileName.length() > 0) try { stream = new PrintStream(new File(fileName)); - } catch ( FileNotFoundException e ) { + } catch (FileNotFoundException e) { Lombok.sneakyThrow(e); } diff --git a/src/lombok/javac/handlers/HandleSetter.java b/src/lombok/javac/handlers/HandleSetter.java index 44ad0dca..f7360988 100644 --- a/src/lombok/javac/handlers/HandleSetter.java +++ b/src/lombok/javac/handlers/HandleSetter.java @@ -28,9 +28,8 @@ import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.javac.Javac; -import lombok.javac.JavacAST; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; @@ -66,10 +65,10 @@ public class HandleSetter implements JavacAnnotationHandler<Setter> { * If not, the setter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. */ - public void generateSetterForField(Node fieldNode, DiagnosticPosition pos) { - for ( Node child : fieldNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( Javac.annotationTypeMatches(Setter.class, child) ) { + public void generateSetterForField(JavacNode fieldNode, DiagnosticPosition pos) { + for (JavacNode child : fieldNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (Javac.annotationTypeMatches(Setter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -79,16 +78,17 @@ public class HandleSetter implements JavacAnnotationHandler<Setter> { createSetterForField(AccessLevel.PUBLIC, fieldNode, fieldNode, pos, false); } - @Override public boolean handle(AnnotationValues<Setter> annotation, JCAnnotation ast, Node annotationNode) { - Node fieldNode = annotationNode.up(); + @Override public boolean handle(AnnotationValues<Setter> annotation, JCAnnotation ast, JavacNode annotationNode) { + JavacNode fieldNode = annotationNode.up(); AccessLevel level = annotation.getInstance().value(); - if ( level == AccessLevel.NONE ) return true; + if (level == AccessLevel.NONE) return true; return createSetterForField(level, fieldNode, annotationNode, annotationNode.get(), true); } - private boolean createSetterForField(AccessLevel level, Node fieldNode, Node errorNode, DiagnosticPosition pos, boolean whineIfExists) { - if ( fieldNode.getKind() != Kind.FIELD ) { + private boolean createSetterForField(AccessLevel level, + JavacNode fieldNode, JavacNode errorNode, DiagnosticPosition pos, boolean whineIfExists) { + if (fieldNode.getKind() != Kind.FIELD) { fieldNode.addError("@Setter is only supported on a field."); return true; } @@ -96,11 +96,11 @@ public class HandleSetter implements JavacAnnotationHandler<Setter> { JCVariableDecl fieldDecl = (JCVariableDecl)fieldNode.get(); String methodName = toSetterName(fieldDecl); - switch ( methodExists(methodName, fieldNode) ) { + switch (methodExists(methodName, fieldNode)) { case EXISTS_BY_LOMBOK: return true; case EXISTS_BY_USER: - if ( whineIfExists ) errorNode.addWarning( + if (whineIfExists) errorNode.addWarning( String.format("Not generating %s(%s %s): A method with that name already exists", methodName, fieldDecl.vartype, fieldDecl.name)); return true; @@ -116,7 +116,7 @@ public class HandleSetter implements JavacAnnotationHandler<Setter> { return true; } - private JCMethodDecl createSetter(long access, JavacAST.Node field, TreeMaker treeMaker) { + private JCMethodDecl createSetter(long access, JavacNode field, TreeMaker treeMaker) { JCVariableDecl fieldDecl = (JCVariableDecl) field.get(); JCFieldAccess thisX = treeMaker.Select(treeMaker.Ident(field.toName("this")), fieldDecl.name); diff --git a/src/lombok/javac/handlers/HandleSneakyThrows.java b/src/lombok/javac/handlers/HandleSneakyThrows.java index 4a4ab09b..3cbad7f6 100644 --- a/src/lombok/javac/handlers/HandleSneakyThrows.java +++ b/src/lombok/javac/handlers/HandleSneakyThrows.java @@ -29,7 +29,7 @@ import java.util.Collection; import lombok.SneakyThrows; import lombok.core.AnnotationValues; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; @@ -50,31 +50,31 @@ import com.sun.tools.javac.util.List; */ @ProviderFor(JavacAnnotationHandler.class) public class HandleSneakyThrows implements JavacAnnotationHandler<SneakyThrows> { - @Override public boolean handle(AnnotationValues<SneakyThrows> annotation, JCAnnotation ast, Node annotationNode) { + @Override public boolean handle(AnnotationValues<SneakyThrows> annotation, JCAnnotation ast, JavacNode annotationNode) { Collection<String> exceptionNames = annotation.getRawExpressions("value"); List<JCExpression> memberValuePairs = ast.getArguments(); - if ( memberValuePairs == null || memberValuePairs.size() == 0 ) return false; + if (memberValuePairs == null || memberValuePairs.size() == 0) return false; JCExpression arrayOrSingle = ((JCAssign)memberValuePairs.get(0)).rhs; final List<JCExpression> exceptionNameNodes; - if ( arrayOrSingle instanceof JCNewArray ) { + if (arrayOrSingle instanceof JCNewArray) { exceptionNameNodes = ((JCNewArray)arrayOrSingle).elems; } else exceptionNameNodes = List.of(arrayOrSingle); - if ( exceptionNames.size() != exceptionNameNodes.size() ) { + if (exceptionNames.size() != exceptionNameNodes.size()) { annotationNode.addError( "LOMBOK BUG: The number of exception classes in the annotation isn't the same pre- and post- guessing."); } java.util.List<String> exceptions = new ArrayList<String>(); - for ( String exception : exceptionNames ) { - if ( exception.endsWith(".class") ) exception = exception.substring(0, exception.length() - 6); + for (String exception : exceptionNames) { + if (exception.endsWith(".class")) exception = exception.substring(0, exception.length() - 6); exceptions.add(exception); } - Node owner = annotationNode.up(); - switch ( owner.getKind() ) { + JavacNode owner = annotationNode.up(); + switch (owner.getKind()) { case METHOD: return handleMethod(annotationNode, (JCMethodDecl)owner.get(), exceptions); default: @@ -83,19 +83,19 @@ public class HandleSneakyThrows implements JavacAnnotationHandler<SneakyThrows> } } - private boolean handleMethod(Node annotation, JCMethodDecl method, Collection<String> exceptions) { - Node methodNode = annotation.up(); + private boolean handleMethod(JavacNode annotation, JCMethodDecl method, Collection<String> exceptions) { + JavacNode methodNode = annotation.up(); - if ( (method.mods.flags & Flags.ABSTRACT) != 0 ) { + if ( (method.mods.flags & Flags.ABSTRACT) != 0) { annotation.addError("@SneakyThrows can only be used on concrete methods."); return true; } - if ( method.body == null ) return false; + if (method.body == null) return false; List<JCStatement> contents = method.body.stats; - for ( String exception : exceptions ) { + for (String exception : exceptions) { contents = List.of(buildTryCatchBlock(methodNode, contents, exception)); } @@ -105,7 +105,7 @@ public class HandleSneakyThrows implements JavacAnnotationHandler<SneakyThrows> return true; } - private JCStatement buildTryCatchBlock(Node node, List<JCStatement> contents, String exception) { + private JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception) { TreeMaker maker = node.getTreeMaker(); JCBlock tryBlock = maker.Block(0, contents); diff --git a/src/lombok/javac/handlers/HandleSynchronized.java b/src/lombok/javac/handlers/HandleSynchronized.java index efc6daf0..559c116a 100644 --- a/src/lombok/javac/handlers/HandleSynchronized.java +++ b/src/lombok/javac/handlers/HandleSynchronized.java @@ -40,7 +40,7 @@ import lombok.Synchronized; import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; /** * Handles the <code>lombok.Synchronized</code> annotation for javac. @@ -50,32 +50,32 @@ public class HandleSynchronized implements JavacAnnotationHandler<Synchronized> private static final String INSTANCE_LOCK_NAME = "$lock"; private static final String STATIC_LOCK_NAME = "$LOCK"; - @Override public boolean handle(AnnotationValues<Synchronized> annotation, JCAnnotation ast, Node annotationNode) { - Node methodNode = annotationNode.up(); + @Override public boolean handle(AnnotationValues<Synchronized> annotation, JCAnnotation ast, JavacNode annotationNode) { + JavacNode methodNode = annotationNode.up(); - if ( methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl) ) { + if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl)) { annotationNode.addError("@Synchronized is legal only on methods."); return true; } JCMethodDecl method = (JCMethodDecl)methodNode.get(); - if ( (method.mods.flags & Flags.ABSTRACT) != 0 ) { + if ((method.mods.flags & Flags.ABSTRACT) != 0) { annotationNode.addError("@Synchronized is legal only on concrete methods."); return true; } boolean isStatic = (method.mods.flags & Flags.STATIC) != 0; String lockName = annotation.getInstance().value(); boolean autoMake = false; - if ( lockName.length() == 0 ) { + if (lockName.length() == 0) { autoMake = true; lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME; } TreeMaker maker = methodNode.getTreeMaker(); - if ( fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS ) { - if ( !autoMake ) { + if (fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS) { + if (!autoMake) { annotationNode.addError("The field " + new String(lockName) + " does not exist."); return true; } @@ -89,7 +89,7 @@ public class HandleSynchronized implements JavacAnnotationHandler<Synchronized> injectField(methodNode.up(), fieldDecl); } - if ( method.body == null ) return false; + if (method.body == null) return false; JCExpression lockNode = maker.Ident(methodNode.toName(lockName)); diff --git a/src/lombok/javac/handlers/HandleToString.java b/src/lombok/javac/handlers/HandleToString.java index eb2013c7..4c9b9c89 100644 --- a/src/lombok/javac/handlers/HandleToString.java +++ b/src/lombok/javac/handlers/HandleToString.java @@ -28,7 +28,7 @@ import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import org.mangosdk.spi.ProviderFor; @@ -54,34 +54,34 @@ import com.sun.tools.javac.util.List; */ @ProviderFor(JavacAnnotationHandler.class) public class HandleToString implements JavacAnnotationHandler<ToString> { - private void checkForBogusFieldNames(Node type, AnnotationValues<ToString> annotation) { - if ( annotation.isExplicit("exclude") ) { - for ( int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, false) ) { + private void checkForBogusFieldNames(JavacNode type, AnnotationValues<ToString> annotation) { + if (annotation.isExplicit("exclude")) { + for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().exclude()), type, true, false)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } - if ( annotation.isExplicit("of") ) { - for ( int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false) ) { + if (annotation.isExplicit("of")) { + for (int i : createListOfNonExistentFields(List.from(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } - @Override public boolean handle(AnnotationValues<ToString> annotation, JCAnnotation ast, Node annotationNode) { + @Override public boolean handle(AnnotationValues<ToString> annotation, JCAnnotation ast, JavacNode annotationNode) { ToString ann = annotation.getInstance(); List<String> excludes = List.from(ann.exclude()); List<String> includes = List.from(ann.of()); - Node typeNode = annotationNode.up(); + JavacNode typeNode = annotationNode.up(); checkForBogusFieldNames(typeNode, annotation); Boolean callSuper = ann.callSuper(); - if ( !annotation.isExplicit("callSuper") ) callSuper = null; - if ( !annotation.isExplicit("exclude") ) excludes = null; - if ( !annotation.isExplicit("of") ) includes = null; + if (!annotation.isExplicit("callSuper")) callSuper = null; + if (!annotation.isExplicit("exclude")) excludes = null; + if (!annotation.isExplicit("of")) includes = null; - if ( excludes != null && includes != null ) { + if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } @@ -89,10 +89,10 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { return generateToString(typeNode, annotationNode, excludes, includes, ann.includeFieldNames(), callSuper, true); } - public void generateToStringForType(Node typeNode, Node errorNode) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( Javac.annotationTypeMatches(ToString.class, child) ) { + public void generateToStringForType(JavacNode typeNode, JavacNode errorNode) { + for (JavacNode child : typeNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (Javac.annotationTypeMatches(ToString.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -102,51 +102,51 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { boolean includeFieldNames = true; try { includeFieldNames = ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue(); - } catch ( Exception ignore ) {} + } catch (Exception ignore) {} generateToString(typeNode, errorNode, null, null, includeFieldNames, null, false); } - private boolean generateToString(Node typeNode, Node errorNode, List<String> excludes, List<String> includes, + private boolean generateToString(JavacNode typeNode, JavacNode errorNode, List<String> excludes, List<String> includes, boolean includeFieldNames, Boolean callSuper, boolean whineIfExists) { boolean notAClass = true; - if ( typeNode.get() instanceof JCClassDecl ) { + if (typeNode.get() instanceof JCClassDecl) { long flags = ((JCClassDecl)typeNode.get()).mods.flags; notAClass = (flags & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0; } - if ( callSuper == null ) { + if (callSuper == null) { try { callSuper = ((Boolean)ToString.class.getMethod("callSuper").getDefaultValue()).booleanValue(); - } catch ( Exception ignore ) {} + } catch (Exception ignore) {} } - if ( notAClass ) { + if (notAClass) { errorNode.addError("@ToString is only supported on a class."); return false; } - List<Node> nodesForToString = List.nil(); - if ( includes != null ) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + List<JavacNode> nodesForToString = List.nil(); + if (includes != null) { + for (JavacNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); - if ( includes.contains(fieldDecl.name.toString()) ) nodesForToString = nodesForToString.append(child); + if (includes.contains(fieldDecl.name.toString())) nodesForToString = nodesForToString.append(child); } } else { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + for (JavacNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; JCVariableDecl fieldDecl = (JCVariableDecl) child.get(); //Skip static fields. - if ( (fieldDecl.mods.flags & Flags.STATIC) != 0 ) continue; + if ((fieldDecl.mods.flags & Flags.STATIC) != 0) continue; //Skip excluded fields. - if ( excludes != null && excludes.contains(fieldDecl.name.toString()) ) continue; + if (excludes != null && excludes.contains(fieldDecl.name.toString())) continue; //Skip fields that start with $. - if ( fieldDecl.name.toString().startsWith("$") ) continue; + if (fieldDecl.name.toString().startsWith("$")) continue; nodesForToString = nodesForToString.append(child); } } - switch ( methodExists("toString", typeNode) ) { + switch (methodExists("toString", typeNode)) { case NOT_EXISTS: JCMethodDecl method = createToString(typeNode, nodesForToString, includeFieldNames, callSuper); injectMethod(typeNode, method); @@ -155,7 +155,7 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { return true; default: case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { errorNode.addWarning("Not generating toString(): A method with that name already exists"); } return true; @@ -163,7 +163,7 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { } - private JCMethodDecl createToString(Node typeNode, List<Node> fields, boolean includeFieldNames, boolean callSuper) { + private JCMethodDecl createToString(JavacNode typeNode, List<JavacNode> fields, boolean includeFieldNames, boolean callSuper) { TreeMaker maker = typeNode.getTreeMaker(); JCAnnotation overrideAnnotation = maker.Annotation(chainDots(maker, typeNode, "java", "lang", "Override"), List.<JCExpression>nil()); @@ -176,11 +176,11 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { String infix = ", "; String suffix = ")"; String prefix; - if ( callSuper ) { + if (callSuper) { prefix = typeName + "(super="; - } else if ( fields.isEmpty() ) { + } else if (fields.isEmpty()) { prefix = typeName + "()"; - } else if ( includeFieldNames ) { + } else if (includeFieldNames) { prefix = typeName + "(" + ((JCVariableDecl)fields.iterator().next().get()).name.toString() + "="; } else { prefix = typeName + "("; @@ -188,7 +188,7 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { JCExpression current = maker.Literal(prefix); - if ( callSuper ) { + if (callSuper) { JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")), List.<JCExpression>nil()); @@ -196,11 +196,11 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { first = false; } - for ( Node fieldNode : fields ) { + for (JavacNode fieldNode : fields) { JCVariableDecl field = (JCVariableDecl) fieldNode.get(); JCExpression expr; - if ( field.vartype instanceof JCArrayTypeTree ) { + if (field.vartype instanceof JCArrayTypeTree) { boolean multiDim = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCArrayTypeTree; boolean primitiveArray = ((JCArrayTypeTree)field.vartype).elemtype instanceof JCPrimitiveTypeTree; boolean useDeepTS = multiDim || !primitiveArray; @@ -209,13 +209,13 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { expr = maker.Apply(List.<JCExpression>nil(), hcMethod, List.<JCExpression>of(maker.Ident(field.name))); } else expr = maker.Ident(field.name); - if ( first ) { + if (first) { current = maker.Binary(JCTree.PLUS, current, expr); first = false; continue; } - if ( includeFieldNames ) { + if (includeFieldNames) { current = maker.Binary(JCTree.PLUS, current, maker.Literal(infix + fieldNode.getName() + "=")); } else { current = maker.Binary(JCTree.PLUS, current, maker.Literal(infix)); @@ -224,7 +224,7 @@ public class HandleToString implements JavacAnnotationHandler<ToString> { current = maker.Binary(JCTree.PLUS, current, expr); } - if ( !first ) current = maker.Binary(JCTree.PLUS, current, maker.Literal(suffix)); + if (!first) current = maker.Binary(JCTree.PLUS, current, maker.Literal(suffix)); JCStatement returnStatement = maker.Return(current); diff --git a/src/lombok/javac/handlers/PKG.java b/src/lombok/javac/handlers/PKG.java index 0563f33c..e2fceb08 100644 --- a/src/lombok/javac/handlers/PKG.java +++ b/src/lombok/javac/handlers/PKG.java @@ -27,8 +27,7 @@ import java.util.regex.Pattern; import lombok.AccessLevel; import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; -import lombok.javac.JavacAST; -import lombok.javac.JavacAST.Node; +import lombok.javac.JavacNode; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.TypeTags; @@ -95,17 +94,17 @@ class PKG { * @param fieldName the field name to check for. * @param node Any node that represents the Type (JCClassDecl) to check for, or any child node thereof. */ - static MemberExistsResult fieldExists(String fieldName, JavacAST.Node node) { - while ( node != null && !(node.get() instanceof JCClassDecl) ) { + static MemberExistsResult fieldExists(String fieldName, JavacNode node) { + while (node != null && !(node.get() instanceof JCClassDecl)) { node = node.up(); } - if ( node != null && node.get() instanceof JCClassDecl ) { - for ( JCTree def : ((JCClassDecl)node.get()).defs ) { - if ( def instanceof JCVariableDecl ) { - if ( ((JCVariableDecl)def).name.contentEquals(fieldName) ) { - JavacAST.Node existing = node.getNodeFor(def); - if ( existing == null || !existing.isHandled() ) return MemberExistsResult.EXISTS_BY_USER; + if (node != null && node.get() instanceof JCClassDecl) { + for (JCTree def : ((JCClassDecl)node.get()).defs) { + if (def instanceof JCVariableDecl) { + if (((JCVariableDecl)def).name.contentEquals(fieldName)) { + JavacNode existing = node.getNodeFor(def); + if (existing == null || !existing.isHandled()) return MemberExistsResult.EXISTS_BY_USER; return MemberExistsResult.EXISTS_BY_LOMBOK; } } @@ -122,17 +121,17 @@ class PKG { * @param methodName the method name to check for. * @param node Any node that represents the Type (JCClassDecl) to check for, or any child node thereof. */ - static MemberExistsResult methodExists(String methodName, JavacAST.Node node) { - while ( node != null && !(node.get() instanceof JCClassDecl) ) { + static MemberExistsResult methodExists(String methodName, JavacNode node) { + while (node != null && !(node.get() instanceof JCClassDecl)) { node = node.up(); } - if ( node != null && node.get() instanceof JCClassDecl ) { - for ( JCTree def : ((JCClassDecl)node.get()).defs ) { - if ( def instanceof JCMethodDecl ) { - if ( ((JCMethodDecl)def).name.contentEquals(methodName) ) { - JavacAST.Node existing = node.getNodeFor(def); - if ( existing == null || !existing.isHandled() ) return MemberExistsResult.EXISTS_BY_USER; + if (node != null && node.get() instanceof JCClassDecl) { + for (JCTree def : ((JCClassDecl)node.get()).defs) { + if (def instanceof JCMethodDecl) { + if (((JCMethodDecl)def).name.contentEquals(methodName)) { + JavacNode existing = node.getNodeFor(def); + if (existing == null || !existing.isHandled()) return MemberExistsResult.EXISTS_BY_USER; return MemberExistsResult.EXISTS_BY_LOMBOK; } } @@ -148,18 +147,18 @@ class PKG { * * @param node Any node that represents the Type (JCClassDecl) to check for, or any child node thereof. */ - static MemberExistsResult constructorExists(JavacAST.Node node) { - while ( node != null && !(node.get() instanceof JCClassDecl) ) { + static MemberExistsResult constructorExists(JavacNode node) { + while (node != null && !(node.get() instanceof JCClassDecl)) { node = node.up(); } - if ( node != null && node.get() instanceof JCClassDecl ) { - for ( JCTree def : ((JCClassDecl)node.get()).defs ) { - if ( def instanceof JCMethodDecl ) { - if ( ((JCMethodDecl)def).name.contentEquals("<init>") ) { - if ( (((JCMethodDecl)def).mods.flags & Flags.GENERATEDCONSTR) != 0 ) continue; - JavacAST.Node existing = node.getNodeFor(def); - if ( existing == null || !existing.isHandled() ) return MemberExistsResult.EXISTS_BY_USER; + if (node != null && node.get() instanceof JCClassDecl) { + for (JCTree def : ((JCClassDecl)node.get()).defs) { + if (def instanceof JCMethodDecl) { + if (((JCMethodDecl)def).name.contentEquals("<init>")) { + if ((((JCMethodDecl)def).mods.flags & Flags.GENERATEDCONSTR) != 0) continue; + JavacNode existing = node.getNodeFor(def); + if (existing == null || !existing.isHandled()) return MemberExistsResult.EXISTS_BY_USER; return MemberExistsResult.EXISTS_BY_LOMBOK; } } @@ -175,7 +174,7 @@ class PKG { * @see java.lang.Modifier */ static int toJavacModifier(AccessLevel accessLevel) { - switch ( accessLevel ) { + switch (accessLevel) { case MODULE: case PACKAGE: return 0; @@ -194,7 +193,7 @@ class PKG { * * Also takes care of updating the JavacAST. */ - static void injectField(JavacAST.Node typeNode, JCVariableDecl field) { + static void injectField(JavacNode typeNode, JCVariableDecl field) { JCClassDecl type = (JCClassDecl) typeNode.get(); type.defs = type.defs.append(field); @@ -208,17 +207,17 @@ class PKG { * * Also takes care of updating the JavacAST. */ - static void injectMethod(JavacAST.Node typeNode, JCMethodDecl method) { + static void injectMethod(JavacNode typeNode, JCMethodDecl method) { JCClassDecl type = (JCClassDecl) typeNode.get(); - if ( method.getName().contentEquals("<init>") ) { + if (method.getName().contentEquals("<init>")) { //Scan for default constructor, and remove it. int idx = 0; - for ( JCTree def : type.defs ) { - if ( def instanceof JCMethodDecl ) { - if ( (((JCMethodDecl)def).mods.flags & Flags.GENERATEDCONSTR) != 0 ) { - JavacAST.Node tossMe = typeNode.getNodeFor(def); - if ( tossMe != null ) tossMe.up().removeChild(tossMe); + for (JCTree def : type.defs) { + if (def instanceof JCMethodDecl) { + if ((((JCMethodDecl)def).mods.flags & Flags.GENERATEDCONSTR) != 0) { + JavacNode tossMe = typeNode.getNodeFor(def); + if (tossMe != null) tossMe.up().removeChild(tossMe); type.defs = addAllButOne(type.defs, idx); break; } @@ -235,8 +234,8 @@ class PKG { private static List<JCTree> addAllButOne(List<JCTree> defs, int idx) { List<JCTree> out = List.nil(); int i = 0; - for ( JCTree def : defs ) { - if ( i++ != idx ) out = out.append(def); + for (JCTree def : defs) { + if (i++ != idx) out = out.append(def); } return out; } @@ -251,22 +250,22 @@ class PKG { * @see com.sun.tools.javac.tree.JCTree.JCIdent * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess */ - static JCExpression chainDots(TreeMaker maker, JavacAST.Node node, String... elems) { + static JCExpression chainDots(TreeMaker maker, JavacNode node, String... elems) { assert elems != null; assert elems.length > 0; JCExpression e = maker.Ident(node.toName(elems[0])); - for ( int i = 1 ; i < elems.length ; i++ ) { + for (int i = 1 ; i < elems.length ; i++) { e = maker.Select(e, node.toName(elems[i])); } return e; } - static List<JCAnnotation> findAnnotations(Node fieldNode, Pattern namePattern) { + static List<JCAnnotation> findAnnotations(JavacNode fieldNode, Pattern namePattern) { List<JCAnnotation> result = List.nil(); - for ( Node child : fieldNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { + for (JavacNode child : fieldNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { JCAnnotation annotation = (JCAnnotation) child.get(); String name = annotation.annotationType.toString(); int idx = name.lastIndexOf("."); @@ -279,7 +278,7 @@ class PKG { return result; } - static JCStatement generateNullCheck(TreeMaker treeMaker, JavacAST.Node variable) { + static JCStatement generateNullCheck(TreeMaker treeMaker, JavacNode variable) { JCVariableDecl varDecl = (JCVariableDecl) variable.get(); if (isPrimitive(varDecl.vartype)) return null; Name fieldName = varDecl.name; @@ -289,29 +288,28 @@ class PKG { return treeMaker.If(treeMaker.Binary(JCTree.EQ, treeMaker.Ident(fieldName), treeMaker.Literal(TypeTags.BOT, null)), throwStatement, null); } - static List<Integer> createListOfNonExistentFields(List<String> list, Node type, boolean excludeStandard, boolean excludeTransient) { + static List<Integer> createListOfNonExistentFields(List<String> list, JavacNode type, boolean excludeStandard, boolean excludeTransient) { boolean[] matched = new boolean[list.size()]; - for ( Node child : type.down() ) { - if ( list.isEmpty() ) break; - if ( child.getKind() != Kind.FIELD ) continue; + for (JavacNode child : type.down()) { + if (list.isEmpty()) break; + if (child.getKind() != Kind.FIELD) continue; JCVariableDecl field = (JCVariableDecl)child.get(); - if ( excludeStandard ) { - if ( (field.mods.flags & Flags.STATIC) != 0 ) continue; - if ( field.name.toString().startsWith("$") ) continue; + if (excludeStandard) { + if ((field.mods.flags & Flags.STATIC) != 0) continue; + if (field.name.toString().startsWith("$")) continue; } - if ( excludeTransient && (field.mods.flags & Flags.TRANSIENT) != 0 ) continue; - + if (excludeTransient && (field.mods.flags & Flags.TRANSIENT) != 0) continue; + int idx = list.indexOf(child.getName()); - if ( idx > -1 ) matched[idx] = true; + if (idx > -1) matched[idx] = true; } List<Integer> problematic = List.nil(); - for ( int i = 0 ; i < list.size() ; i++ ) { - if ( !matched[i] ) problematic = problematic.append(i); + for (int i = 0 ; i < list.size() ; i++) { + if (!matched[i]) problematic = problematic.append(i); } return problematic; } - } |