From b5c8b725655d2ad8a715cfb1fbbdf25dbdcd4ceb Mon Sep 17 00:00:00 2001 From: Reinier Zwitserloot Date: Fri, 16 Oct 2009 09:32:36 +0200 Subject: Fixed issue #24 by refactoring the AST.Node class - taken it out, and in the process fixed a lot of type annoyance by adding more generics. Also changed coding style from for/while/if/switch/catch/do ( expr ) {} to for (expr) {}, hence the changes _everywhere_. --- src/lombok/javac/HandlerLibrary.java | 32 +- src/lombok/javac/Javac.java | 39 ++- src/lombok/javac/JavacAST.java | 345 +++++---------------- src/lombok/javac/JavacASTAdapter.java | 44 ++- src/lombok/javac/JavacASTVisitor.java | 118 ++++--- src/lombok/javac/JavacAnnotationHandler.java | 2 +- src/lombok/javac/JavacNode.java | 200 ++++++++++++ src/lombok/javac/apt/Processor.java | 49 ++- src/lombok/javac/handlers/HandleCleanup.java | 58 ++-- src/lombok/javac/handlers/HandleData.java | 52 ++-- .../javac/handlers/HandleEqualsAndHashCode.java | 145 ++++----- src/lombok/javac/handlers/HandleGetter.java | 31 +- src/lombok/javac/handlers/HandlePrintAST.java | 8 +- src/lombok/javac/handlers/HandleSetter.java | 28 +- src/lombok/javac/handlers/HandleSneakyThrows.java | 30 +- src/lombok/javac/handlers/HandleSynchronized.java | 18 +- src/lombok/javac/handlers/HandleToString.java | 88 +++--- src/lombok/javac/handlers/PKG.java | 112 ++++--- 18 files changed, 699 insertions(+), 700 deletions(-) create mode 100644 src/lombok/javac/JavacNode.java (limited to 'src/lombok/javac') 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 it = ServiceLoader.load(JavacAnnotationHandler.class, JavacAnnotationHandler.class.getClassLoader()).iterator(); - while ( it.hasNext() ) { + while (it.hasNext()) { try { JavacAnnotationHandler handler = it.next(); Class 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 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 lombok.Getter.class. * @param node A Lombok AST node representing an annotation in source code. */ - public static boolean annotationTypeMatches(Class type, Node node) { - if ( node.getKind() != Kind.ANNOTATION ) return false; + public static boolean annotationTypeMatches(Class 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 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 lombok.Getter.class. * @param node A Lombok AST node representing an annotation in source code. */ - public static AnnotationValues createAnnotation(Class type, final Node node) { + public static AnnotationValues createAnnotation(Class type, final JavacNode node) { Map values = new HashMap(); JCAnnotation anno = (JCAnnotation) node.get(); List 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 raws = new ArrayList(); List guesses = new ArrayList(); final List positions = new ArrayList(); 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 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 { +public class JavacAST extends AST { private final Messager messager; private final Name.Table nameTable; private final TreeMaker treeMaker; @@ -90,8 +90,8 @@ public class JavacAST extends AST { @Override public Collection getImportStatements() { List imports = new ArrayList(); 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 { top().traverse(visitor); } - private void traverseChildren(JavacASTVisitor visitor, Node node) { - for ( Node child : new ArrayList(node.down()) ) { + void traverseChildren(JavacASTVisitor visitor, JavacNode node) { + for (JavacNode child : new ArrayList(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 { } /** {@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 { } } - private Node buildCompilationUnit(JCCompilationUnit top) { - List childNodes = new ArrayList(); - for ( JCTree s : top.defs ) { - if ( s instanceof JCClassDecl ) { + private JavacNode buildCompilationUnit(JCCompilationUnit top) { + List childNodes = new ArrayList(); + 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 childNodes = new ArrayList(); + private JavacNode buildType(JCClassDecl type) { + if (setAndGetAsHandled(type)) return null; + List childNodes = new ArrayList(); - 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 childNodes = new ArrayList(); - for ( JCAnnotation annotation : field.mods.annotations ) addIfNotNull(childNodes, buildAnnotation(annotation)); + private JavacNode buildField(JCVariableDecl field) { + if (setAndGetAsHandled(field)) return null; + List childNodes = new ArrayList(); + 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 childNodes = new ArrayList(); - for ( JCAnnotation annotation : local.mods.annotations ) addIfNotNull(childNodes, buildAnnotation(annotation)); + private JavacNode buildLocalVar(JCVariableDecl local, Kind kind) { + if (setAndGetAsHandled(local)) return null; + List childNodes = new ArrayList(); + 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 childNodes = new ArrayList(); - 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 childNodes = new ArrayList(); + 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 childNodes = new ArrayList(); - 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 childNodes = new ArrayList(); + 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 childNodes = new ArrayList(); - 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 childNodes = new ArrayList(); + 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 { return collection; } - private static void addIfNotNull(Collection nodes, Node node) { - if ( node != null ) nodes.add(node); - } - - /** - * Javac specific version of the AST.Node class. - */ - public class Node extends AST.Node { - /** - * See the {@link AST.Node} constructor for information. - */ - public Node(JCTree node, List 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 down() { - return (Collection) 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 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 { 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 { 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> 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> 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> reducedChain = new ArrayList>(chain); Collection newCurrent = reducedChain.remove(reducedChain.size() -1); @@ -514,14 +315,14 @@ public class JavacAST extends AST { 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.from(a); + if (repl) return com.sun.tools.javac.util.List.from(a); else return oldL; } @@ -529,11 +330,11 @@ public class JavacAST extends AST { 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("", Node.getFileName()); + print("", LombokNode.getFileName()); indent++; } - @Override public void endVisitCompilationUnit(Node node, JCCompilationUnit unit) { + @Override public void endVisitCompilationUnit(JavacNode node, JCCompilationUnit unit) { indent--; print(""); } - @Override public void visitType(Node node, JCClassDecl type) { + @Override public void visitType(JavacNode node, JCClassDecl type) { print("", 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); } - @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.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("", initializer.isStatic() ? "static" : "instance"); } - @Override public void visitField(Node node, JCVariableDecl field) { + @Override public void visitField(JavacNode node, JCVariableDecl field) { print("", 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); } - @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.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("") ) { - if ( (method.mods.flags & Flags.GENERATEDCONSTR) != 0 ) { + if (method.name.contentEquals("")) { + 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); } - @Override public void endVisitMethod(Node node, JCMethodDecl method) { - if ( printContent ) disablePrinting--; + @Override public void endVisitMethod(JavacNode node, JCMethodDecl method) { + if (printContent) disablePrinting--; indent--; print("", "XMETHOD", method.name); } - @Override public void visitMethodArgument(Node node, JCVariableDecl arg, JCMethodDecl method) { + @Override public void visitMethodArgument(JavacNode node, JCVariableDecl arg, JCMethodDecl method) { print("", 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); } - @Override public void endVisitMethodArgument(Node node, JCVariableDecl arg, JCMethodDecl method) { + @Override public void endVisitMethodArgument(JavacNode node, JCVariableDecl arg, JCMethodDecl method) { indent--; print("", arg.vartype, arg.name); } - @Override public void visitLocal(Node node, JCVariableDecl local) { + @Override public void visitLocal(JavacNode node, JCVariableDecl local) { print("", 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); } - @Override public void endVisitLocal(Node node, JCVariableDecl local) { + @Override public void endVisitLocal(JavacNode node, JCVariableDecl local) { indent--; print("", 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("", 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 { * @return true if you don't want to be called again about this annotation during this * compile session (you've handled it), or false to indicate you aren't done yet. */ - boolean handle(AnnotationValues annotation, JCAnnotation ast, JavacAST.Node annotationNode); + boolean handle(AnnotationValues 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 { + /** {@inheritDoc} */ + public JavacNode(JavacAST ast, JCTree node, List 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 annotations, RoundEnvironment roundEnv) { - if ( processingEnv == null ) return false; - + if (processingEnv == null) return false; IdentityHashMap units = new IdentityHashMap(); - 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 asts = new ArrayList(); - 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 { - @Override public boolean handle(AnnotationValues annotation, JCAnnotation ast, Node annotationNode) { + @Override public boolean handle(AnnotationValues 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 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 { boolean seenDeclaration = false; List tryBlock = List.nil(); List 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 = ne