diff options
| author | Reinier Zwitserloot <reinier@tipit.to> | 2009-11-25 07:32:49 +0100 |
|---|---|---|
| committer | Reinier Zwitserloot <reinier@tipit.to> | 2009-11-25 07:32:49 +0100 |
| commit | 1a0e611a9c5e1ee518670647ce1a44beae559b44 (patch) | |
| tree | e5ef8f671bc6688f486e874d4e2e1a7813e4f0b2 /src/lombok/javac | |
| parent | 7fd947ea40c25dad9ee543ebc4b92de9a2e05efc (diff) | |
| download | lombok-1a0e611a9c5e1ee518670647ce1a44beae559b44.tar.gz lombok-1a0e611a9c5e1ee518670647ce1a44beae559b44.tar.bz2 lombok-1a0e611a9c5e1ee518670647ce1a44beae559b44.zip | |
Refactored the source folders.
Diffstat (limited to 'src/lombok/javac')
21 files changed, 0 insertions, 3532 deletions
diff --git a/src/lombok/javac/HandlerLibrary.java b/src/lombok/javac/HandlerLibrary.java deleted file mode 100644 index bbe9dec0..00000000 --- a/src/lombok/javac/HandlerLibrary.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * 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.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.ServiceConfigurationError; -import java.util.ServiceLoader; - -import javax.annotation.processing.Messager; -import javax.tools.Diagnostic; - -import lombok.core.PrintAST; -import lombok.core.SpiLoadUtil; -import lombok.core.TypeLibrary; -import lombok.core.TypeResolver; -import lombok.core.AnnotationValues.AnnotationValueDecodeFail; - -import com.sun.tools.javac.tree.JCTree.JCAnnotation; -import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; - -/** - * This class tracks 'handlers' and knows how to invoke them for any given AST node. - * - * This class can find the handlers (via SPI discovery) and will set up the given AST node, such as - * building an AnnotationValues instance. - */ -public class HandlerLibrary { - private final TypeLibrary typeLibrary = new TypeLibrary(); - private final Map<String, AnnotationHandlerContainer<?>> annotationHandlers = new HashMap<String, AnnotationHandlerContainer<?>>(); - private final Collection<JavacASTVisitor> visitorHandlers = new ArrayList<JavacASTVisitor>(); - private final Messager messager; - private boolean skipPrintAST = true; - - /** - * Creates a new HandlerLibrary that will report any problems or errors to the provided messager. - * You probably want to use {@link #load(Messager)} instead. - */ - public HandlerLibrary(Messager messager) { - this.messager = messager; - } - - private static class AnnotationHandlerContainer<T extends Annotation> { - private JavacAnnotationHandler<T> handler; - private Class<T> annotationClass; - - AnnotationHandlerContainer(JavacAnnotationHandler<T> handler, Class<T> annotationClass) { - this.handler = handler; - this.annotationClass = annotationClass; - } - - public boolean handle(final JavacNode node) { - return handler.handle(Javac.createAnnotation(annotationClass, node), (JCAnnotation)node.get(), node); - } - } - - /** - * Creates a new HandlerLibrary that will report any problems or errors to the provided messager, - * then uses SPI discovery to load all annotation and visitor based handlers so that future calls - * to the handle methods will defer to these handlers. - */ - public static HandlerLibrary load(Messager messager) { - HandlerLibrary library = new HandlerLibrary(messager); - - loadAnnotationHandlers(library); - loadVisitorHandlers(library); - - return library; - } - - /** Uses SPI Discovery to find implementations of {@link JavacAnnotationHandler}. */ - @SuppressWarnings("unchecked") - private static void loadAnnotationHandlers(HandlerLibrary lib) { - //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()) { - 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) { - lib.javacWarning("Duplicate handlers for annotation type: " + container.annotationClass.getName()); - } - lib.typeLibrary.addType(container.annotationClass.getName()); - } catch (ServiceConfigurationError e) { - lib.javacWarning("Can't load Lombok annotation handler for javac", e); - } - } - } - - /** Uses SPI Discovery to find implementations of {@link JavacASTVisitor}. */ - private static void loadVisitorHandlers(HandlerLibrary lib) { - //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()) { - try { - JavacASTVisitor handler = it.next(); - lib.visitorHandlers.add(handler); - } catch (ServiceConfigurationError e) { - lib.javacWarning("Can't load Lombok visitor handler for javac", e); - } - } - } - - /** Generates a warning in the Messager that was used to initialize this HandlerLibrary. */ - public void javacWarning(String message) { - javacWarning(message, null); - } - - /** Generates a warning in the Messager that was used to initialize this HandlerLibrary. */ - public void javacWarning(String message, Throwable t) { - messager.printMessage(Diagnostic.Kind.WARNING, message + (t == null ? "" : (": " + t))); - } - - /** Generates an error in the Messager that was used to initialize this HandlerLibrary. */ - public void javacError(String message) { - javacError(message, null); - } - - /** 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(); - } - - /** - * Handles the provided annotation node by first finding a qualifying instance of - * {@link JavacAnnotationHandler} and if one exists, calling it with a freshly cooked up - * instance of {@link lombok.core.AnnotationValues}. - * - * Note that depending on the printASTOnly flag, the {@link lombok.core.PrintAST} annotation - * will either be silently skipped, or everything that isn't {@code PrintAST} will be skipped. - * - * The HandlerLibrary will attempt to guess if the given annotation node represents a lombok annotation. - * For example, if {@code lombok.*} is in the import list, then this method will guess that - * {@code Getter} refers to {@code lombok.Getter}, presuming that {@link lombok.javac.handlers.HandleGetter} - * has been loaded. - * - * @param unit The Compilation Unit that contains the Annotation AST Node. - * @param node The Lombok AST Node representing the Annotation AST Node. - * @param annotation 'node.get()' - convenience parameter. - */ - 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)) { - boolean isPrintAST = fqn.equals(PrintAST.class.getName()); - if (isPrintAST == skipPrintAST) continue; - AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn); - if (container == null) continue; - - try { - handled |= container.handle(node); - } catch (AnnotationValueDecodeFail fail) { - fail.owner.setError(fail.getMessage(), fail.idx); - } catch (Throwable t) { - String sourceName = "(unknown).java"; - if (unit != null && unit.sourcefile != null) sourceName = unit.sourcefile.getName(); - javacError(String.format("Lombok annotation handler %s failed on " + sourceName, container.handler.getClass()), t); - } - } - - return handled; - } - - /** - * Will call all registered {@link JavacASTVisitor} instances. - */ - public void callASTVisitors(JavacAST ast) { - for (JavacASTVisitor visitor : visitorHandlers) try { - ast.traverse(visitor); - } catch (Throwable t) { - javacError(String.format("Lombok visitor handler %s failed", visitor.getClass()), t); - } - } - - /** - * Lombok does not currently support triggering annotations in a specified order; the order is essentially - * random right now. This lack of order is particularly annoying for the {@code PrintAST} annotation, - * which is almost always intended to run last. Hence, this hack, which lets it in fact run last. - * - * @see #skipAllButPrintAST() - */ - public void skipPrintAST() { - skipPrintAST = true; - } - - /** @see #skipPrintAST() */ - public void skipAllButPrintAST() { - skipPrintAST = false; - } -} diff --git a/src/lombok/javac/Javac.java b/src/lombok/javac/Javac.java deleted file mode 100644 index 58a24207..00000000 --- a/src/lombok/javac/Javac.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import lombok.core.AnnotationValues; -import lombok.core.TypeLibrary; -import lombok.core.TypeResolver; -import lombok.core.AST.Kind; -import lombok.core.AnnotationValues.AnnotationValue; - -import com.sun.tools.javac.tree.JCTree.JCAnnotation; -import com.sun.tools.javac.tree.JCTree.JCAssign; -import com.sun.tools.javac.tree.JCTree.JCExpression; -import com.sun.tools.javac.tree.JCTree.JCFieldAccess; -import com.sun.tools.javac.tree.JCTree.JCIdent; -import com.sun.tools.javac.tree.JCTree.JCLiteral; -import com.sun.tools.javac.tree.JCTree.JCNewArray; -import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; - -/** - * Container for static utility methods relevant to lombok's operation on javac. - */ -public class Javac { - private Javac() { - //prevent instantiation - } - - /** - * Checks if the Annotation AST Node provided is likely to be an instance of the provided annotation type. - * - * @param type An actual annotation type, such as {@code lombok.Getter.class}. - * @param node A Lombok AST node representing an annotation in source code. - */ - 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(); - library.addType(type.getName()); - 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; - } - - return false; - } - - /** - * Creates an instance of {@code AnnotationValues} for the provided AST Node. - * - * @param type An annotation class type, such as {@code lombok.Getter.class}. - * @param node A Lombok AST node representing an annotation in source code. - */ - 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; - 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) { - String mName; - JCExpression rhs; - - if (arg instanceof JCAssign) { - JCAssign assign = (JCAssign) arg; - mName = assign.lhs.toString(); - rhs = assign.rhs; - } else { - rhs = arg; - mName = "value"; - } - - if (!mName.equals(name)) continue; - isExplicit = true; - if (rhs instanceof JCNewArray) { - List<JCExpression> elems = ((JCNewArray)rhs).elems; - for (JCExpression inner : elems) { - raws.add(inner.toString()); - guesses.add(calculateGuess(inner)); - positions.add(inner.pos()); - } - } else { - raws.add(rhs.toString()); - guesses.add(calculateGuess(rhs)); - positions.add(rhs.pos()); - } - } - - values.put(name, new AnnotationValue(node, raws, guesses, isExplicit) { - @Override public void setError(String message, int valueIdx) { - 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); - else node.addWarning(message, positions.get(valueIdx)); - } - }); - } - - return new AnnotationValues<A>(type, values, node); - } - - /** - * Turns an expression into a guessed intended literal. Only works for literals, as you can imagine. - * - * Will for example turn a TrueLiteral into 'Boolean.valueOf(true)'. - */ - private static Object calculateGuess(JCExpression expr) { - if (expr instanceof JCLiteral) { - JCLiteral lit = (JCLiteral)expr; - 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) { - String x = expr.toString(); - if (x.endsWith(".class")) x = x.substring(0, x.length() - 6); - else { - int idx = x.lastIndexOf('.'); - 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 deleted file mode 100644 index f2c83fb8..00000000 --- a/src/lombok/javac/JavacAST.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * 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.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.annotation.processing.Messager; -import javax.tools.Diagnostic; -import javax.tools.JavaFileObject; - -import lombok.core.AST; - -import com.sun.source.util.Trees; -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.JCExpression; -import com.sun.tools.javac.tree.JCTree.JCFieldAccess; -import com.sun.tools.javac.tree.JCTree.JCImport; -import com.sun.tools.javac.tree.JCTree.JCMethodDecl; -import com.sun.tools.javac.tree.JCTree.JCStatement; -import com.sun.tools.javac.tree.JCTree.JCVariableDecl; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.Log; -import com.sun.tools.javac.util.Name; -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<JavacAST, JavacNode, JCTree> { - private final Messager messager; - private final Name.Table nameTable; - private final TreeMaker treeMaker; - private final Symtab symtab; - private final Log log; - private final Context context; - - /** - * Creates a new JavacAST of the provided Compilation Unit. - * - * @param trees The trees instance to use to inspect the compilation unit. Generate via: - * {@code Trees.getInstance(env)} - * @param messager A Messager for warning and error reporting. - * @param context A Context object for interfacing with the compiler. - * @param top The compilation unit, which serves as the top level node in the tree to be built. - */ - public JavacAST(Trees trees, Messager messager, Context context, JCCompilationUnit top) { - super(top.sourcefile == null ? null : top.sourcefile.toString()); - setTop(buildCompilationUnit(top)); - this.context = context; - this.messager = messager; - this.log = Log.instance(context); - this.nameTable = Name.Table.instance(context); - this.treeMaker = TreeMaker.instance(context); - this.symtab = Symtab.instance(context); - } - - public Context getContext() { - return context; - } - - /** {@inheritDoc} */ - @Override public String getPackageDeclaration() { - JCCompilationUnit unit = (JCCompilationUnit)top().get(); - return unit.pid instanceof JCFieldAccess ? unit.pid.toString() : null; - } - - /** {@inheritDoc} */ - @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) { - imports.add(((JCImport)def).qualid.toString()); - } - } - - return imports; - } - - /** - * Runs through the entire AST, starting at the compilation unit, calling the provided visitor's visit methods - * for each node, depth first. - */ - public void traverse(JavacASTVisitor visitor) { - top().traverse(visitor); - } - - void traverseChildren(JavacASTVisitor visitor, JavacNode node) { - for (JavacNode child : new ArrayList<JavacNode>(node.down())) { - child.traverse(visitor); - } - } - - /** @return A Name object generated for the proper name table belonging to this AST. */ - public Name toName(String name) { - return nameTable.fromString(name); - } - - /** @return A TreeMaker instance that you can use to create new AST nodes. */ - public TreeMaker getTreeMaker() { - return treeMaker; - } - - /** @return The symbol table used by this AST for symbols. */ - public Symtab getSymbolTable() { - return symtab; - } - - /** {@inheritDoc} */ - @Override protected JavacNode buildTree(JCTree node, Kind kind) { - switch (kind) { - case COMPILATION_UNIT: - return buildCompilationUnit((JCCompilationUnit) node); - case TYPE: - return buildType((JCClassDecl) node); - case FIELD: - return buildField((JCVariableDecl) node); - case INITIALIZER: - return buildInitializer((JCBlock) node); - case METHOD: - return buildMethod((JCMethodDecl) node); - case ARGUMENT: - return buildLocalVar((JCVariableDecl) node, kind); - case LOCAL: - return buildLocalVar((JCVariableDecl) node, kind); - case STATEMENT: - return buildStatementOrExpression(node); - case ANNOTATION: - return buildAnnotation((JCAnnotation) node); - default: - throw new AssertionError("Did not expect: " + kind); - } - } - - 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 JavacNode(this, top, childNodes, Kind.COMPILATION_UNIT); - } - - 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)); - /* 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)); - } - - return putInMap(new JavacNode(this, type, childNodes, Kind.TYPE)); - } - - 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 JavacNode(this, field, childNodes, Kind.FIELD)); - } - - 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 JavacNode(this, local, childNodes, kind)); - } - - 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 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 JavacNode buildAnnotation(JCAnnotation annotation) { - if (setAndGetAsHandled(annotation)) return null; - return putInMap(new JavacNode(this, annotation, null, Kind.ANNOTATION)); - } - - private JavacNode buildExpression(JCExpression expression) { - return buildStatementOrExpression(expression); - } - - private JavacNode buildStatement(JCStatement statement) { - return buildStatementOrExpression(statement); - } - - 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; - - return drill(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. */ - @Override - protected Collection<Class<? extends JCTree>> getStatementTypes() { - Collection<Class<? extends JCTree>> collection = new ArrayList<Class<? extends JCTree>>(2); - collection.add(JCStatement.class); - collection.add(JCExpression.class); - return collection; - } - - 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) */ - void printMessage(Diagnostic.Kind kind, String message, JavacNode node, DiagnosticPosition pos) { - JavaFileObject oldSource = null; - JavaFileObject newSource = null; - JCTree astObject = node == null ? null : node.get(); - JCCompilationUnit top = (JCCompilationUnit) top().get(); - newSource = top.sourcefile; - if (newSource != null) { - oldSource = log.useSource(newSource); - if (pos == null) pos = astObject.pos(); - } - try { - switch (kind) { - case ERROR: - increaseErrorCount(messager); - boolean prev = log.multipleErrors; - log.multipleErrors = true; - try { - log.error(pos, "proc.messager", message); - } finally { - log.multipleErrors = prev; - } - break; - default: - case WARNING: - log.warning(pos, "proc.messager", message); - break; - } - } finally { - if (oldSource != null) log.useSource(oldSource); - } - } - - /** {@inheritDoc} */ - @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); - 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; - List<Collection<?>> reducedChain = new ArrayList<Collection<?>>(chain); - Collection<?> newCurrent = reducedChain.remove(reducedChain.size() -1); - return setElementInConsList(reducedChain, newCurrent, oldL, newL); - } - - 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) { - a[i] = newO; - repl = true; - } - } - - if (repl) return com.sun.tools.javac.util.List.<Object>from(a); - return oldL; - } - - private void increaseErrorCount(Messager m) { - try { - Field f = m.getClass().getDeclaredField("errorCount"); - f.setAccessible(true); - if (f.getType() == int.class) { - int val = ((Number)f.get(m)).intValue(); - f.set(m, val +1); - } - } 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 deleted file mode 100644 index 41bc46d3..00000000 --- a/src/lombok/javac/JavacASTAdapter.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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 com.sun.tools.javac.tree.JCTree; -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; - -/ |
