From e2af5ed0c7786e01bec861f21f2e5ec3bc5ea33f Mon Sep 17 00:00:00 2001 From: Reinier Zwitserloot Date: Fri, 26 Jul 2013 07:15:07 +0200 Subject: experiment: Can we wrap TreeMaker and remove a heck of a lot of opportunity to program handlers that are not cross javac6-8 compatible? --- src/utils/lombok/javac/JavacTreeMaker.java | 662 +++++++++++++++++++++++++++++ 1 file changed, 662 insertions(+) create mode 100644 src/utils/lombok/javac/JavacTreeMaker.java (limited to 'src/utils/lombok/javac/JavacTreeMaker.java') diff --git a/src/utils/lombok/javac/JavacTreeMaker.java b/src/utils/lombok/javac/JavacTreeMaker.java new file mode 100644 index 00000000..916c8735 --- /dev/null +++ b/src/utils/lombok/javac/JavacTreeMaker.java @@ -0,0 +1,662 @@ +/* + * Copyright (C) 2013 The Project Lombok Authors. + * + * 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.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import com.sun.tools.javac.code.Attribute; +import com.sun.tools.javac.code.BoundKind; +import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCArrayAccess; +import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; +import com.sun.tools.javac.tree.JCTree.JCAssert; +import com.sun.tools.javac.tree.JCTree.JCAssign; +import com.sun.tools.javac.tree.JCTree.JCAssignOp; +import com.sun.tools.javac.tree.JCTree.JCBinary; +import com.sun.tools.javac.tree.JCTree.JCBlock; +import com.sun.tools.javac.tree.JCTree.JCBreak; +import com.sun.tools.javac.tree.JCTree.JCCase; +import com.sun.tools.javac.tree.JCTree.JCCatch; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCConditional; +import com.sun.tools.javac.tree.JCTree.JCContinue; +import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop; +import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; +import com.sun.tools.javac.tree.JCTree.JCErroneous; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; +import com.sun.tools.javac.tree.JCTree.JCFieldAccess; +import com.sun.tools.javac.tree.JCTree.JCForLoop; +import com.sun.tools.javac.tree.JCTree.JCIdent; +import com.sun.tools.javac.tree.JCTree.JCIf; +import com.sun.tools.javac.tree.JCTree.JCImport; +import com.sun.tools.javac.tree.JCTree.JCInstanceOf; +import com.sun.tools.javac.tree.JCTree.JCLabeledStatement; +import com.sun.tools.javac.tree.JCTree.JCLiteral; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; +import com.sun.tools.javac.tree.JCTree.JCModifiers; +import com.sun.tools.javac.tree.JCTree.JCNewArray; +import com.sun.tools.javac.tree.JCTree.JCNewClass; +import com.sun.tools.javac.tree.JCTree.JCParens; +import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; +import com.sun.tools.javac.tree.JCTree.JCReturn; +import com.sun.tools.javac.tree.JCTree.JCSkip; +import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCSwitch; +import com.sun.tools.javac.tree.JCTree.JCSynchronized; +import com.sun.tools.javac.tree.JCTree.JCThrow; +import com.sun.tools.javac.tree.JCTree.JCTry; +import com.sun.tools.javac.tree.JCTree.JCTypeApply; +import com.sun.tools.javac.tree.JCTree.JCTypeCast; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCUnary; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.tree.JCTree.JCWhileLoop; +import com.sun.tools.javac.tree.JCTree.JCWildcard; +import com.sun.tools.javac.tree.JCTree.LetExpr; +import com.sun.tools.javac.tree.JCTree.TypeBoundKind; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.Name; + +public class JavacTreeMaker { + private final TreeMaker tm; + + public JavacTreeMaker(TreeMaker tm) { + this.tm = tm; + } + + public JavacTreeMaker at(int pos) { + tm.at(pos); + return this; + } + + private static class MethodId { + private final String name; + private final Class returnType; + private final Class[] paramTypes; + + MethodId(String name, Class returnType, Class... types) { + this.name = name; + this.paramTypes = types; + this.returnType = returnType; + } + + } + + private static Object getFieldCached(ConcurrentMap cache, String className, String fieldName) { + Object value = cache.get(fieldName); + if (value != null) return value; + try { + value = Class.forName(className).getField(fieldName).get(null); + } catch (NoSuchFieldException e) { + throw Javac.sneakyThrow(e); + } catch (IllegalAccessException e) { + throw Javac.sneakyThrow(e); + } catch (ClassNotFoundException e) { + throw Javac.sneakyThrow(e); + } + + cache.putIfAbsent(fieldName, value); + return value; + } + + private static interface SchroedingerType {} + + public static class TypeTag implements SchroedingerType { + private static final ConcurrentMap TYPE_TAG_CACHE = new ConcurrentHashMap(); + public final Object value; + + private TypeTag(Object value) { + this.value = value; + } + + public static TypeTag typeTag(String identifier) { + return new TypeTag(getFieldCached(TYPE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.code.TypeTags" : "com.sun.tools.javac.code.TypeTag", identifier)); + } + } + + public static class TreeTag implements SchroedingerType { + private static final ConcurrentMap TREE_TAG_CACHE = new ConcurrentHashMap(); + public final Object value; + + private TreeTag(Object value) { + this.value = value; + } + + public static TreeTag treeTag(String identifier) { + return new TreeTag(getFieldCached(TREE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.tree.JCTree" : "com.sun.tools.javac.tree.JCTree$Tag", identifier)); + } + } + + /** + * Creates a new method ID based on the name of the method to invoke, the return type of that method, and the types of the parameters. + * + * A method matches if the return type matches, and for each parameter the following holds: + * + * Either (A) the type listed here is the same as, or a subtype of, the type of the method in javac's TreeMaker, or + * (B) the type listed here is a subtype of SchroedingerType. + */ + static MethodId MethodId(String name, Class returnType, Class... types) { + return new MethodId(name, returnType, types); + } + + /** + * Creates a new method ID based on the name of a method in this class, assuming the name of the method to invoke in TreeMaker has the same name, + * the same return type, and the same parameters (under the same rules as the other MethodId method). + */ + static MethodId MethodId(String name) { + for (Method m : JavacTreeMaker.class.getDeclaredMethods()) { + if (m.getName().equals(name)) { + @SuppressWarnings("unchecked") Class r = (Class) m.getReturnType(); + Class[] p = m.getParameterTypes(); + return new MethodId(name, r, p); + } + } + + throw new InternalError("Not found: " + name); + } + + private static final ConcurrentHashMap, Method> METHOD_CACHE = new ConcurrentHashMap, Method>(); + private J invoke(MethodId m, Object... args) { + Method method = METHOD_CACHE.get(m); + if (method == null) method = addToCache(m); + try { + return m.returnType.cast(method.invoke(tm, args)); + } catch (InvocationTargetException e) { + throw Javac.sneakyThrow(e.getCause()); + } catch (IllegalAccessException e) { + throw Javac.sneakyThrow(e); + } + } + + private static Method addToCache(MethodId m) { + Method found = null; + + outer: + for (Method method : TreeMaker.class.getDeclaredMethods()) { + if (!m.name.equals(method.getName())) continue; + Class[] t = method.getParameterTypes(); + if (t.length != m.paramTypes.length) continue; + for (int i = 0; i < t.length; i++) { + if (Symbol.class.isAssignableFrom(t[i])) continue outer; + if (!SchroedingerType.class.isAssignableFrom(m.paramTypes[i])) { + if (t[i].isPrimitive()) { + if (t[i] != m.paramTypes[i]) continue outer; + } else { + if (t[i].isAssignableFrom(m.paramTypes[i])) continue outer; + } + } + } + if (found == null) found = method; + else throw new IllegalStateException("Lombok TreeMaker frontend issue: multiple matches when looking for method: " + m); + } + if (found == null) throw new IllegalStateException("Lombok TreeMaker frontedn issue: no match when looking for method: " + m); + found.setAccessible(true); + Object marker = METHOD_CACHE.putIfAbsent(m, found); + if (marker == null) return found; + return METHOD_CACHE.get(m); + } + + //javac versions: 6-8 + private static final MethodId TopLevel = MethodId("TopLevel"); + public JCCompilationUnit TopLevel(List packageAnnotations, JCExpression pid, List defs) { + return invoke(TopLevel, packageAnnotations, pid, defs); + } + + //javac versions: 6-8 + private static final MethodId Import = MethodId("Import"); + public JCImport Import(JCTree qualid, boolean staticImport) { + return invoke(Import, qualid, staticImport); + } + + //javac versions: 6-8 + private static final MethodId ClassDef = MethodId("ClassDef"); + public JCClassDecl ClassDef(JCModifiers mods, Name name, List typarams, JCExpression extending, List implementing, List defs) { + return invoke(ClassDef, mods, name, typarams, extending, implementing, defs); + } + + //javac versions: 6-8 + private static final MethodId MethodDef = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, List.class, List.class, JCBlock.class, JCExpression.class); + public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List typarams, List params, List thrown, JCBlock body, JCExpression defaultValue) { + return invoke(MethodDef, mods, name, resType, typarams, params, thrown, body, defaultValue); + } + + //javac versions: 8 + private static final MethodId MethodDefWithRecvParam = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, JCVariableDecl.class, List.class, List.class, JCBlock.class, JCExpression.class); + public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List typarams, JCVariableDecl recvparam, List params, List thrown, JCBlock body, JCExpression defaultValue) { + return invoke(MethodDefWithRecvParam, mods, name, resType, recvparam, typarams, params, thrown, body, defaultValue); + } + + //javac versions: 6-8 + private static final MethodId VarDef = MethodId("VarDef"); + public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init) { + return invoke(VarDef, mods, name, vartype, init); + } + + //javac versions: 8 + private static final MethodId ReceiverVarDef = MethodId("ReceiverVarDef"); + public JCVariableDecl ReceiverVarDef(JCModifiers mods, JCExpression name, JCExpression vartype) { + return invoke(ReceiverVarDef, mods, name, vartype); + } + + //javac versions: 6-8 + private static final MethodId Skip = MethodId("Skip"); + public JCSkip Skip() { + return invoke(Skip); + } + + //javac versions: 6-8 + private static final MethodId Block = MethodId("Block"); + public JCBlock Block(long flags, List stats) { + return invoke(Block, flags, stats); + } + + //javac versions: 6-8 + private static final MethodId DoLoop = MethodId("DoLoop"); + public JCDoWhileLoop DoLoop(JCStatement body, JCExpression cond) { + return invoke(DoLoop, body, cond); + } + + //javac versions: 6-8 + private static final MethodId WhileLoop = MethodId("WhileLoop"); + public JCWhileLoop WhileLoop(JCExpression cond, JCStatement body) { + return invoke(WhileLoop, cond, body); + } + + //javac versions: 6-8 + private static final MethodId ForLoop = MethodId("ForLoop"); + public JCForLoop ForLoop(List init, JCExpression cond, List step, JCStatement body) { + return invoke(ForLoop, init, cond, step, body); + } + + //javac versions: 6-8 + private static final MethodId ForeachLoop = MethodId("ForeachLoop"); + public JCEnhancedForLoop ForeachLoop(JCVariableDecl var, JCExpression expr, JCStatement body) { + return invoke(ForeachLoop, var, expr, body); + } + + //javac versions: 6-8 + private static final MethodId Labelled = MethodId("Labelled"); + public JCLabeledStatement Labelled(Name label, JCStatement body) { + return invoke(Labelled, label, body); + } + + //javac versions: 6-8 + private static final MethodId Switch = MethodId("Switch"); + public JCSwitch Switch(JCExpression selector, List cases) { + return invoke(Switch, selector, cases); + } + + //javac versions: 6-8 + private static final MethodId Case = MethodId("Case"); + public JCCase Case(JCExpression pat, List stats) { + return invoke(Case, pat, stats); + } + + //javac versions: 6-8 + private static final MethodId Synchronized = MethodId("Synchronized"); + public JCSynchronized Synchronized(JCExpression lock, JCBlock body) { + return invoke(Synchronized, lock, body); + } + + //javac versions: 6-8 + private static final MethodId Try = MethodId("Try", JCTry.class, JCBlock.class, List.class, JCBlock.class); + public JCTry Try(JCBlock body, List catchers, JCBlock finalizer) { + return invoke(Try, body, catchers, finalizer); + } + + //javac versions: 7-8 + private static final MethodId TryWithResources = MethodId("Try", JCTry.class, List.class, JCBlock.class, List.class, JCBlock.class); + public JCTry Try(List resources, JCBlock body, List catchers, JCBlock finalizer) { + return invoke(TryWithResources, resources, body, catchers, finalizer); + } + + //javac versions: 6-8 + private static final MethodId Catch = MethodId("Catch"); + public JCCatch Catch(JCVariableDecl param, JCBlock body) { + return invoke(Catch, param, body); + } + + //javac versions: 6-8 + private static final MethodId Conditional = MethodId("Conditional"); + public JCConditional Conditional(JCExpression cond, JCExpression thenpart, JCExpression elsepart) { + return invoke(Conditional, cond, thenpart, elsepart); + } + + //javac versions: 6-8 + private static final MethodId If = MethodId("If"); + public JCIf If(JCExpression cond, JCStatement thenpart, JCStatement elsepart) { + return invoke(If, cond, thenpart, elsepart); + } + + //javac versions: 6-8 + private static final MethodId Exec = MethodId("Exec"); + public JCExpressionStatement Exec(JCExpression expr) { + return invoke(Exec, expr); + } + + //javac versions: 6-8 + private static final MethodId Break = MethodId("Break"); + public JCBreak Break(Name label) { + return invoke(Break, label); + } + + //javac versions: 6-8 + private static final MethodId Continue = MethodId("Continue"); + public JCContinue Continue(Name label) { + return invoke(Continue, label); + } + + //javac versions: 6-8 + private static final MethodId Return = MethodId("Return"); + public JCReturn Return(JCExpression expr) { + return invoke(Return, expr); + } + + //javac versions: 6-8 + private static final MethodId Throw = MethodId("Throw"); + public JCThrow Throw(JCTree expr) { + return invoke(Throw, expr); + } + + //javac versions: 6-8 + private static final MethodId Assert = MethodId("Assert"); + public JCAssert Assert(JCExpression cond, JCExpression detail) { + return invoke(Assert, cond, detail); + } + + //javac versions: 6-8 + private static final MethodId Apply = MethodId("Apply"); + public JCMethodInvocation Apply(List typeargs, JCExpression fn, List args) { + return invoke(Apply, typeargs, fn, args); + } + + //javac versions: 6-8 + private static final MethodId NewClass = MethodId("NewClass"); + public JCNewClass NewClass(JCExpression encl, List typeargs, JCExpression clazz, List args, JCClassDecl def) { + return invoke(NewClass, encl, typeargs, clazz, args, def); + } + + //javac versions: 6-8 + private static final MethodId NewArray = MethodId("NewArray"); + public JCNewArray NewArray(JCExpression elemtype, List dims, List elems) { + return invoke(NewArray, elemtype, dims, elems); + } + + //javac versions: 8 +// private static final MethodId Lambda = MethodId("Lambda"); +// public JCLambda Lambda(List params, JCTree body) { +// return invoke(Lambda, params, body); +// } + + //javac versions: 6-8 + private static final MethodId Parens = MethodId("Parens"); + public JCParens Parens(JCExpression expr) { + return invoke(Parens, expr); + } + + //javac versions: 6-8 + private static final MethodId Assign = MethodId("Assign"); + public JCAssign Assign(JCExpression lhs, JCExpression rhs) { + return invoke(Assign, lhs, rhs); + } + + //javac versions: 6-8 + //opcode = [6-7] int [8] JCTree.Tag + private static final MethodId Assignop = MethodId("Assignop"); + public JCAssignOp Assignop(TreeTag opcode, JCTree lhs, JCTree rhs) { + return invoke(Assignop, opcode.value, lhs, rhs); + } + + //javac versions: 6-8 + //opcode = [6-7] int [8] JCTree.Tag + private static final MethodId Unary = MethodId("Unary"); + public JCUnary Unary(TreeTag opcode, JCExpression arg) { + return invoke(Unary, opcode.value, arg); + } + + //javac versions: 6-8 + //opcode = [6-7] int [8] JCTree.Tag + private static final MethodId Binary = MethodId("Binary"); + public JCBinary Binary(TreeTag opcode, JCExpression lhs, JCExpression rhs) { + return invoke(Binary, opcode.value, lhs, rhs); + } + + //javac versions: 6-8 + private static final MethodId TypeCast = MethodId("TypeCast"); + public JCTypeCast TypeCast(JCTree expr, JCExpression type) { + return invoke(TypeCast, expr, type); + } + + //javac versions: 6-8 + private static final MethodId TypeTest = MethodId("TypeTest"); + public JCInstanceOf TypeTest(JCExpression expr, JCTree clazz) { + return invoke(TypeTest, expr, clazz); + } + + //javac versions: 6-8 + private static final MethodId Indexed = MethodId("Indexed"); + public JCArrayAccess Indexed(JCExpression indexed, JCExpression index) { + return invoke(Indexed, indexed, index); + } + + //javac versions: 6-8 + private static final MethodId Select = MethodId("Select"); + public JCFieldAccess Select(JCExpression selected, Name selector) { + return invoke(Select, selected, selector); + } + + //javac versions: 8 +// private static final MethodId Reference = MethodId("Reference"); +// public JCMemberReference Reference(JCMemberReference.ReferenceMode mode, Name name, JCExpression expr, List typeargs) { +// return invoke(Reference, mode, name, expr, typeargs); +// } + + //javac versions: 6-8 + private static final MethodId Ident = MethodId("Ident", JCIdent.class, Name.class); + public JCIdent Ident(Name idname) { + return invoke(Ident, idname); + } + + //javac versions: 6-8 + //tag = [6-7] int [8] TypeTag + private static final MethodId Literal = MethodId("Literal", JCLiteral.class, TypeTag.class, Object.class); + public JCLiteral Literal(TypeTag tag, Object value) { + return invoke(Literal, tag.value, value); + } + + //javac versions: 6-8 + //typetag = [6-7] int [8] TypeTag + private static final MethodId TypeIdent = MethodId("TypeIdent"); + public JCPrimitiveTypeTree TypeIdent(TypeTag typetag) { + return invoke(TypeIdent, typetag.value); + } + //javac versions: 6-8 + private static final MethodId TypeArray = MethodId("TypeArray"); + public JCArrayTypeTree TypeArray(JCExpression elemtype) { + return invoke(TypeArray, elemtype); + } + + //javac versions: 6-8 + private static final MethodId TypeApply = MethodId("TypeApply"); + public JCTypeApply TypeApply(JCExpression clazz, List arguments) { + return invoke(TypeApply, clazz, arguments); + } + + //javac versions: 7-8 +// private static final MethodId TypeUnion = MethodId("TypeUnion"); +// public JCTypeUnion TypeUnion(List components) { +// return invoke(TypeUnion, compoonents); +// } + + //javac versions: 8 +// private static final MethodId TypeIntersection = MethodId("TypeIntersection"); +// public JCTypeIntersection TypeIntersection(List components) { +// return invoke(TypeIntersection, components); +// } + + //javac versions: 6-8 + private static final MethodId TypeParameter = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class); + public JCTypeParameter TypeParameter(Name name, List bounds) { + return invoke(TypeParameter, name, bounds); + } + + //javac versions: 8 + private static final MethodId TypeParameterWithAnnos = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class, List.class); + public JCTypeParameter TypeParameter(Name name, List bounds, List annos) { + return invoke(TypeParameterWithAnnos, name, bounds, annos); + } + + //javac versions: 6-8 + private static final MethodId Wildcard = MethodId("Wildcard"); + public JCWildcard Wildcard(TypeBoundKind kind, JCTree type) { + return invoke(Wildcard, kind, type); + } + + //javac versions: 6-8 + private static final MethodId TypeBoundKind = MethodId("TypeBoundKind"); + public TypeBoundKind TypeBoundKind(BoundKind kind) { + return invoke(TypeBoundKind, kind); + } + + //javac versions: 6-8 + private static final MethodId Annotation = MethodId("Annotation", JCAnnotation.class, JCTree.class, List.class); + public JCAnnotation Annotation(JCTree annotationType, List args) { + return invoke(Annotation, annotationType, args); + } + + //javac versions: 8 + private static final MethodId TypeAnnotation = MethodId("TypeAnnotation", JCAnnotation.class, JCTree.class, List.class); + public JCAnnotation TypeAnnotation(JCTree annotationType, List args) { + return invoke(TypeAnnotation, annotationType, args); + } + + //javac versions: 6-8 + private static final MethodId ModifiersWithAnnotations = MethodId("Modifiers", JCModifiers.class, long.class, List.class); + public JCModifiers Modifiers(long flags, List annotations) { + return invoke(ModifiersWithAnnotations, flags, annotations); + } + + //javac versions: 6-8 + private static final MethodId Modifiers = MethodId("Modifiers", JCModifiers.class, long.class); + public JCModifiers Modifiers(long flags) { + return invoke(Modifiers, flags); + } + + //javac versions: 8 +// private static final MethodId AnnotatedType = MethodId("AnnotatedType"); +// public JCAnnotatedType AnnotatedType(List annotations, JCExpression underlyingType) { +// return invoke(AnnotatedType, annotations, underlyingType); +// } + + //javac versions: 6-8 + private static final MethodId Erroneous = MethodId("Erroneous", JCErroneous.class); + public JCErroneous Erroneous() { + return invoke(Erroneous); + } + + //javac versions: 6-8 + private static final MethodId ErroneousWithErrs = MethodId("Erroneous", JCErroneous.class, List.class); + public JCErroneous Erroneous(List errs) { + return invoke(ErroneousWithErrs, errs); + } + + //javac versions: 6-8 + private static final MethodId LetExpr = MethodId("LetExpr", LetExpr.class, List.class, JCTree.class); + public LetExpr LetExpr(List defs, JCTree expr) { + return invoke(LetExpr, defs, expr); + } + + //javac versions: 6-8 + private static final MethodId AnonymousClassDef = MethodId("AnonymousClassDef"); + public JCClassDecl AnonymousClassDef(JCModifiers mods, List defs) { + return invoke(AnonymousClassDef, mods, defs); + } + + //javac versions: 6-8 + private static final MethodId LetExprSingle = MethodId("LetExpr", LetExpr.class, JCVariableDecl.class, JCTree.class); + public LetExpr LetExpr(JCVariableDecl def, JCTree expr) { + return invoke(LetExprSingle, def, expr); + } + + //javac versions: 6-8 + private static final MethodId IdentVarDecl = MethodId("Ident", JCIdent.class, JCVariableDecl.class); + public JCExpression Ident(JCVariableDecl param) { + return invoke(IdentVarDecl, param); + } + + //javac versions: 6-8 + private static final MethodId> Idents = MethodId("Idents"); + public List Idents(List params) { + return invoke(Idents, params); + } + + //javac versions: 6-8 + private static final MethodId App2 = MethodId("App", JCMethodInvocation.class, JCExpression.class, List.class); + public JCMethodInvocation App(JCExpression meth, List args) { + return invoke(App2, meth, args); + } + + //javac versions: 6-8 + private static final MethodId App1 = MethodId("App", JCMethodInvocation.class, JCExpression.class); + public JCMethodInvocation App(JCExpression meth) { + return invoke(App1, meth); + } + + //javac versions: 6-8 + private static final MethodId> Annotations = MethodId("Annotations"); + public List Annotations(List attributes) { + return invoke(Annotations, attributes); + } + + //javac versions: 6-8 + private static final MethodId LiteralWithValue = MethodId("Literal", JCLiteral.class, Object.class); + public JCLiteral Literal(Object value) { + return invoke(LiteralWithValue, value); + } + + //javac versions: 6-8 + private static final MethodId AnnotationWithAttributeOnly = MethodId("Annotation", JCAnnotation.class, Attribute.class); + public JCAnnotation Annotation(Attribute a) { + return invoke(AnnotationWithAttributeOnly, a); + } + + //javac versions: 8 + private static final MethodId TypeAnnotationWithAttributeOnly = MethodId("TypeAnnotation", JCAnnotation.class, Attribute.class); + public JCAnnotation TypeAnnotation(Attribute a) { + return invoke(TypeAnnotationWithAttributeOnly, a); + } + + //javac versions: 6-8 + private static final MethodId Call = MethodId("Call"); + public JCStatement Call(JCExpression apply) { + return invoke(Call, apply); + } +} \ No newline at end of file -- cgit From 4dbe3802fda3b317bb82bca80d7c69f58b239cfd Mon Sep 17 00:00:00 2001 From: Reinier Zwitserloot Date: Sun, 28 Jul 2013 03:10:34 +0200 Subject: more progress. This one is less JDK8 compatible, but it has major refactorings to make JDK6-8 support possibly with much prettier code. --- build.xml | 24 +- src/core/lombok/javac/JavacResolution.java | 35 +-- src/core/lombok/javac/handlers/HandleBuilder.java | 6 +- src/core/lombok/javac/handlers/HandleGetter.java | 9 +- .../lombok/javac/handlers/JavacHandlerUtil.java | 24 +- src/core/lombok/javac/handlers/NonNullHandler.java | 7 +- .../lombok/delombok/PrettyCommentsPrinter.java | 242 +++++++-------------- src/utils/lombok/javac/Javac.java | 86 +------- src/utils/lombok/javac/JavacTreeMaker.java | 178 ++++++++++++--- src/utils/lombok/javac/TreeMirrorMaker.java | 5 +- 10 files changed, 295 insertions(+), 321 deletions(-) (limited to 'src/utils/lombok/javac/JavacTreeMaker.java') diff --git a/build.xml b/build.xml index 2ed0ba71..b44d6673 100644 --- a/build.xml +++ b/build.xml @@ -332,7 +332,7 @@ the common tasks and can be called on to run the main aspects of all the sub-scr - + @@ -345,7 +345,7 @@ the common tasks and can be called on to run the main aspects of all the sub-scr - + @@ -360,9 +360,11 @@ the common tasks and can be called on to run the main aspects of all the sub-scr + + - - + + Tests will now run against Oracle JDK7 @@ -371,11 +373,11 @@ the common tasks and can be called on to run the main aspects of all the sub-scr - - + + - - + + Tests will now run against Oracle JDK8 @@ -390,8 +392,10 @@ Eventually, this environment concept will be extended to also include an ecj and You can let this ant script set them up for you: -* ant setupJava6TestEnvironment -* ant setupJava7TestEnvironment +* ant setupJavaOpenJDK6TestEnvironment +* ant setupJavaOpenJDK7TestEnvironment +* ant setupJavaOracle7TestEnvironment +* ant setupJavaOracle8TestEnvironment These will set up test environments based on OpenJDK6 and OpenJDK7, and download all required files automatically. This will be a relatively large download. You can switch by running this command again; the downloads are cached so switching is fast. diff --git a/src/core/lombok/javac/JavacResolution.java b/src/core/lombok/javac/JavacResolution.java index 42299572..7d4bdabd 100644 --- a/src/core/lombok/javac/JavacResolution.java +++ b/src/core/lombok/javac/JavacResolution.java @@ -35,6 +35,8 @@ import java.util.Queue; import javax.lang.model.type.TypeKind; import javax.tools.DiagnosticListener; +import static lombok.javac.JavacTreeMaker.TypeTag.typeTag; + import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Symtab; @@ -56,7 +58,6 @@ import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; -import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; @@ -389,7 +390,7 @@ public class JavacResolution { } public static JCExpression createJavaLangObject(JavacAST ast) { - TreeMaker maker = ast.getTreeMaker(); + JavacTreeMaker maker = ast.getTreeMaker(); JCExpression out = maker.Ident(ast.toName("java")); out = maker.Select(out, ast.toName("lang")); out = maker.Select(out, ast.toName("Object")); @@ -416,10 +417,10 @@ public class JavacResolution { // NB: There's such a thing as maker.Type(type), but this doesn't work very well; it screws up anonymous classes, captures, and adds an extra prefix dot for some reason too. // -- so we write our own take on that here. - TreeMaker maker = ast.getTreeMaker(); + JavacTreeMaker maker = ast.getTreeMaker(); - if (Javac.compareCTC(type.tag, CTC_BOT)) return createJavaLangObject(ast); - if (Javac.compareCTC(type.tag, CTC_VOID)) return allowVoid ? primitiveToJCTree(type.getKind(), maker) : createJavaLangObject(ast); + if (CTC_BOT.equals(typeTag(type))) return createJavaLangObject(ast); + if (CTC_VOID.equals(typeTag(type))) return allowVoid ? primitiveToJCTree(type.getKind(), maker) : createJavaLangObject(ast); if (type.isPrimitive()) return primitiveToJCTree(type.getKind(), maker); if (type.isErroneous()) throw new TypeNotConvertibleException("Type cannot be resolved"); @@ -453,7 +454,7 @@ public class JavacResolution { upper = type.getUpperBound(); } if (allowCompound) { - if (lower == null || Javac.compareCTC(lower.tag, CTC_BOT)) { + if (lower == null || CTC_BOT.equals(typeTag(lower))) { if (upper == null || upper.toString().equals("java.lang.Object")) { return maker.Wildcard(maker.TypeBoundKind(BoundKind.UNBOUND), null); } @@ -478,7 +479,7 @@ public class JavacResolution { String qName; if (symbol.isLocal()) { qName = symbol.getSimpleName().toString(); - } else if (symbol.type != null && symbol.type.getEnclosingType() != null && Javac.compareCTC(symbol.type.getEnclosingType().tag, Javac.getTypeTag("CLASS"))) { + } else if (symbol.type != null && symbol.type.getEnclosingType() != null && typeTag(symbol.type.getEnclosingType()).equals(typeTag("CLASS"))) { replacement = typeToJCTree0(type.getEnclosingType(), ast, false, false); qName = symbol.getSimpleName().toString(); } else { @@ -511,26 +512,26 @@ public class JavacResolution { return rawTypeNode; } - private static JCExpression primitiveToJCTree(TypeKind kind, TreeMaker maker) throws TypeNotConvertibleException { + private static JCExpression primitiveToJCTree(TypeKind kind, JavacTreeMaker maker) throws TypeNotConvertibleException { switch (kind) { case BYTE: - return Javac.makeTypeIdent(maker, CTC_BYTE); + return maker.TypeIdent(CTC_BYTE); case CHAR: - return Javac.makeTypeIdent(maker, CTC_CHAR); + return maker.TypeIdent( CTC_CHAR); case SHORT: - return Javac.makeTypeIdent(maker, CTC_SHORT); + return maker.TypeIdent(CTC_SHORT); case INT: - return Javac.makeTypeIdent(maker, CTC_INT); + return maker.TypeIdent(CTC_INT); case LONG: - return Javac.makeTypeIdent(maker, CTC_LONG); + return maker.TypeIdent(CTC_LONG); case FLOAT: - return Javac.makeTypeIdent(maker, CTC_FLOAT); + return maker.TypeIdent(CTC_FLOAT); case DOUBLE: - return Javac.makeTypeIdent(maker, CTC_DOUBLE); + return maker.TypeIdent(CTC_DOUBLE); case BOOLEAN: - return Javac.makeTypeIdent(maker, CTC_BOOLEAN); + return maker.TypeIdent(CTC_BOOLEAN); case VOID: - return Javac.makeTypeIdent(maker, CTC_VOID); + return maker.TypeIdent(CTC_VOID); case NULL: case NONE: case OTHER: diff --git a/src/core/lombok/javac/handlers/HandleBuilder.java b/src/core/lombok/javac/handlers/HandleBuilder.java index 1c0f2ec0..4f48b69f 100644 --- a/src/core/lombok/javac/handlers/HandleBuilder.java +++ b/src/core/lombok/javac/handlers/HandleBuilder.java @@ -41,7 +41,6 @@ import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; -import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; @@ -53,13 +52,14 @@ import lombok.core.HandlerPriority; import lombok.core.TransformationsUtil; import lombok.experimental.Builder; import lombok.experimental.NonFinal; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; import lombok.javac.handlers.HandleConstructor.SkipIfConstructorExists; import static lombok.core.handlers.HandlerUtil.*; import static lombok.javac.handlers.JavacHandlerUtil.*; +import static lombok.javac.Javac.*; +import static lombok.javac.JavacTreeMaker.TypeTag.*; @ProviderFor(JavacAnnotationHandler.class) @HandlerPriority(-1024) //-2^10; to ensure we've picked up @FieldDefault's changes (-2048) but @Value hasn't removed itself yet (-512), so that we can error on presence of it on the builder classes. @@ -240,7 +240,7 @@ public class HandleBuilder extends JavacAnnotationHandler { JCExpression fn = maker.Select(maker.Ident(((JCClassDecl) type.up().get()).name), staticName); call = maker.Apply(typeParams.toList(), fn, args.toList()); - if (returnType instanceof JCPrimitiveTypeTree && compareCTC(Javac.getTypeTag((JCPrimitiveTypeTree) returnType), CTC_VOID)) { + if (returnType instanceof JCPrimitiveTypeTree && CTC_VOID.equals(typeTag(returnType))) { statement = maker.Exec(call); } else { statement = maker.Return(call); diff --git a/src/core/lombok/javac/handlers/HandleGetter.java b/src/core/lombok/javac/handlers/HandleGetter.java index f5bf2b6c..f6c14add 100644 --- a/src/core/lombok/javac/handlers/HandleGetter.java +++ b/src/core/lombok/javac/handlers/HandleGetter.java @@ -22,6 +22,7 @@ package lombok.javac.handlers; import static lombok.javac.Javac.*; +import static lombok.javac.JavacTreeMaker.TypeTag.*; import static lombok.javac.handlers.JavacHandlerUtil.*; import java.util.Collection; @@ -35,10 +36,10 @@ import lombok.Getter; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.core.TransformationsUtil; -import lombok.javac.Javac; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; import lombok.javac.JavacTreeMaker; +import lombok.javac.JavacTreeMaker.TypeTag; import lombok.javac.handlers.JavacHandlerUtil.FieldAccess; import org.mangosdk.spi.ProviderFor; @@ -289,9 +290,9 @@ public class HandleGetter extends JavacAnnotationHandler { private static final String JLO = "java.lang.Object"; private static final List NIL_EXPRESSION = List.nil(); - private static final java.util.Map TYPE_MAP; + private static final java.util.Map TYPE_MAP; static { - Map m = new HashMap(); + Map m = new HashMap(); m.put(CTC_INT, "java.lang.Integer"); m.put(CTC_DOUBLE, "java.lang.Double"); m.put(CTC_FLOAT, "java.lang.Float"); @@ -335,7 +336,7 @@ public class HandleGetter extends JavacAnnotationHandler { field.type = null; boolean isPrimitive = false; if (field.vartype instanceof JCPrimitiveTypeTree) { - String boxed = TYPE_MAP.get(((JCPrimitiveTypeTree)field.vartype).typetag); + String boxed = TYPE_MAP.get(typeTag(field.vartype)); if (boxed != null) { isPrimitive = true; field.vartype = chainDotsString(fieldNode, boxed); diff --git a/src/core/lombok/javac/handlers/JavacHandlerUtil.java b/src/core/lombok/javac/handlers/JavacHandlerUtil.java index 630cc31a..d0673c57 100644 --- a/src/core/lombok/javac/handlers/JavacHandlerUtil.java +++ b/src/core/lombok/javac/handlers/JavacHandlerUtil.java @@ -1277,17 +1277,17 @@ public class JavacHandlerUtil { */ public static void copyJavadoc(JavacNode from, JCTree to, CopyJavadoc copyMode) { if (copyMode == null) copyMode = CopyJavadoc.VERBATIM; -// try { -// JCCompilationUnit cu = ((JCCompilationUnit) from.top().get()); -// if (cu.docComments != null) { -// String javadoc = cu.docComments.get(from.get()); -// -// if (javadoc != null) { -// String[] filtered = copyMode.split(javadoc); -// cu.docComments.put(to, filtered[0]); -// cu.docComments.put(from.get(), filtered[1]); -// } -// } -// } catch (Exception ignore) {} + try { + JCCompilationUnit cu = ((JCCompilationUnit) from.top().get()); + if (cu.docComments != null) { + String javadoc = cu.docComments.get(from.get()); + + if (javadoc != null) { + String[] filtered = copyMode.split(javadoc); + cu.docComments.put(to, filtered[0]); + cu.docComments.put(from.get(), filtered[1]); + } + } + } catch (Exception ignore) {} } } diff --git a/src/core/lombok/javac/handlers/NonNullHandler.java b/src/core/lombok/javac/handlers/NonNullHandler.java index d74fb55d..3cf76f26 100644 --- a/src/core/lombok/javac/handlers/NonNullHandler.java +++ b/src/core/lombok/javac/handlers/NonNullHandler.java @@ -46,6 +46,9 @@ import lombok.core.AST.Kind; import lombok.javac.JavacAnnotationHandler; import lombok.javac.JavacNode; +import static lombok.javac.JavacTreeMaker.TypeTag.*; +import static lombok.javac.JavacTreeMaker.TreeTag.*; + @ProviderFor(JavacAnnotationHandler.class) public class NonNullHandler extends JavacAnnotationHandler { @Override public void handle(AnnotationValues annotation, JCAnnotation ast, JavacNode annotationNode) { @@ -138,10 +141,10 @@ public class NonNullHandler extends JavacAnnotationHandler { while (cond instanceof JCParens) cond = ((JCParens) cond).expr; if (!(cond instanceof JCBinary)) return null; JCBinary bin = (JCBinary) cond; - if (compareCTC(getTag(bin), CTC_EQUAL)) return null; + if (!CTC_EQUAL.equals(treeTag(bin))) return null; if (!(bin.lhs instanceof JCIdent)) return null; if (!(bin.rhs instanceof JCLiteral)) return null; - if (compareCTC(getTypeTag((JCLiteral) bin.rhs), CTC_BOT)) return null; + if (!CTC_BOT.equals(typeTag(bin.rhs))) return null; return ((JCIdent) bin.lhs).name.toString(); } } diff --git a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java index 481380f7..fd0b0f0d 100644 --- a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java +++ b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java @@ -45,9 +45,13 @@ import java.util.HashMap; import java.util.Map; import lombok.javac.CommentInfo; -import lombok.javac.Javac; import lombok.javac.CommentInfo.EndConnection; import lombok.javac.CommentInfo.StartConnection; +import lombok.javac.JavacTreeMaker.TreeTag; +import lombok.javac.JavacTreeMaker.TypeTag; +import static lombok.javac.Javac.*; +import static lombok.javac.JavacTreeMaker.TreeTag.treeTag; +import static lombok.javac.JavacTreeMaker.TypeTag.typeTag; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.BoundKind; @@ -123,88 +127,48 @@ import com.sun.tools.javac.util.Position; */ @SuppressWarnings("all") // Mainly sun code that has other warning settings public class PrettyCommentsPrinter extends JCTree.Visitor { + private static final TreeTag PARENS = treeTag("PARENS"); + private static final TreeTag IMPORT = treeTag("IMPORT"); + private static final TreeTag VARDEF = treeTag("VARDEF"); + private static final TreeTag SELECT = treeTag("SELECT"); - private static final Method GET_TAG_METHOD; - private static final Field TAG_FIELD; - - private static final Object PARENS = Javac.getTreeTag("PARENS"); - private static final Object IMPORT = Javac.getTreeTag("IMPORT"); - private static final Object VARDEF = Javac.getTreeTag("VARDEF"); - private static final Object SELECT = Javac.getTreeTag("SELECT"); - - private static final Map OPERATORS; + private static final Map OPERATORS; static { - Method m = null; - Field f = null; - try { - m = JCTree.class.getDeclaredMethod("getTag"); - } - catch (NoSuchMethodException e) { - try { - f = JCTree.class.getDeclaredField("tag"); - } - catch (NoSuchFieldException e1) { - e1.printStackTrace(); - } - } - GET_TAG_METHOD = m; - TAG_FIELD = f; - - Map map = new HashMap(); + Map map = new HashMap(); - map.put(Javac.getTreeTag("POS"), "+"); - map.put(Javac.getTreeTag("NEG"), "-"); - map.put(Javac.getTreeTag("NOT"), "!"); - map.put(Javac.getTreeTag("COMPL"), "~"); - map.put(Javac.getTreeTag("PREINC"), "++"); - map.put(Javac.getTreeTag("PREDEC"), "--"); - map.put(Javac.getTreeTag("POSTINC"), "++"); - map.put(Javac.getTreeTag("POSTDEC"), "--"); - map.put(Javac.getTreeTag("NULLCHK"), "<*nullchk*>"); - map.put(Javac.getTreeTag("OR"), "||"); - map.put(Javac.getTreeTag("AND"), "&&"); - map.put(Javac.getTreeTag("EQ"), "=="); - map.put(Javac.getTreeTag("NE"), "!="); - map.put(Javac.getTreeTag("LT"), "<"); - map.put(Javac.getTreeTag("GT"), ">"); - map.put(Javac.getTreeTag("LE"), "<="); - map.put(Javac.getTreeTag("GE"), ">="); - map.put(Javac.getTreeTag("BITOR"), "|"); - map.put(Javac.getTreeTag("BITXOR"), "^"); - map.put(Javac.getTreeTag("BITAND"), "&"); - map.put(Javac.getTreeTag("SL"), "<<"); - map.put(Javac.getTreeTag("SR"), ">>"); - map.put(Javac.getTreeTag("USR"), ">>>"); - map.put(Javac.getTreeTag("PLUS"), "+"); - map.put(Javac.getTreeTag("MINUS"), "-"); - map.put(Javac.getTreeTag("MUL"), "*"); - map.put(Javac.getTreeTag("DIV"), "/"); - map.put(Javac.getTreeTag("MOD"), "%"); + map.put(treeTag("POS"), "+"); + map.put(treeTag("NEG"), "-"); + map.put(treeTag("NOT"), "!"); + map.put(treeTag("COMPL"), "~"); + map.put(treeTag("PREINC"), "++"); + map.put(treeTag("PREDEC"), "--"); + map.put(treeTag("POSTINC"), "++"); + map.put(treeTag("POSTDEC"), "--"); + map.put(treeTag("NULLCHK"), "<*nullchk*>"); + map.put(treeTag("OR"), "||"); + map.put(treeTag("AND"), "&&"); + map.put(treeTag("EQ"), "=="); + map.put(treeTag("NE"), "!="); + map.put(treeTag("LT"), "<"); + map.put(treeTag("GT"), ">"); + map.put(treeTag("LE"), "<="); + map.put(treeTag("GE"), ">="); + map.put(treeTag("BITOR"), "|"); + map.put(treeTag("BITXOR"), "^"); + map.put(treeTag("BITAND"), "&"); + map.put(treeTag("SL"), "<<"); + map.put(treeTag("SR"), ">>"); + map.put(treeTag("USR"), ">>>"); + map.put(treeTag("PLUS"), "+"); + map.put(treeTag("MINUS"), "-"); + map.put(treeTag("MUL"), "*"); + map.put(treeTag("DIV"), "/"); + map.put(treeTag("MOD"), "%"); OPERATORS = map; } - static Object getTag(JCTree tree) { - if (GET_TAG_METHOD != null) { - try { - return GET_TAG_METHOD.invoke(tree); - } - catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - catch (InvocationTargetException e) { - throw new RuntimeException(e.getCause()); - } - } - try { - return TAG_FIELD.get(tree); - } - catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - private List comments; private final JCCompilationUnit cu; private boolean onNewLine = true; @@ -634,7 +598,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { /** Is the given tree an enumerator definition? */ boolean isEnumerator(JCTree t) { - return Javac.compareCTC(getTag(t), VARDEF) && (((JCVariableDecl) t).mods.flags & ENUM) != 0; + return VARDEF.equals(treeTag(t)) && (((JCVariableDecl) t).mods.flags & ENUM) != 0; } /** Print unit consisting of package clause and import statements in toplevel, @@ -645,7 +609,8 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { * toplevel tree. */ public void printUnit(JCCompilationUnit tree, JCClassDecl cdef) throws IOException { - docComments = tree.docComments; + Object dc = getDocComments(tree); + if (dc instanceof Map) this.docComments = (Map) dc; printDocComment(tree); if (tree.pid != null) { consumeComments(tree.pos, tree); @@ -656,9 +621,9 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { } boolean firstImport = true; for (List l = tree.defs; - l.nonEmpty() && (cdef == null || getTag(l.head) == IMPORT); + l.nonEmpty() && (cdef == null || IMPORT.equals(treeTag(l.head))); l = l.tail) { - if (Javac.compareCTC(getTag(l.head), IMPORT)) { + if (IMPORT.equals(treeTag(l.head))) { JCImport imp = (JCImport)l.head; Name name = TreeInfo.name(imp.qualid); if (name == name.table.fromChars(new char[] {'*'}, 0, 1) || @@ -742,9 +707,9 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { else print("class " + tree.name); printTypeParameters(tree.typarams); - if (Javac.getExtendsClause(tree) != null) { + if (getExtendsClause(tree) != null) { print(" extends "); - printExpr(Javac.getExtendsClause(tree)); + printExpr(getExtendsClause(tree)); } if (tree.implementing.nonEmpty()) { print(" implements "); @@ -877,7 +842,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { printStat(tree.body); align(); print(" while "); - if (Javac.compareCTC(getTag(tree.cond), PARENS)) { + if (PARENS.equals(treeTag(tree.cond))) { printExpr(tree.cond); } else { print("("); @@ -893,7 +858,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitWhileLoop(JCWhileLoop tree) { try { print("while "); - if (Javac.compareCTC(getTag(tree.cond), PARENS)) { + if (PARENS.equals(treeTag(tree.cond))) { printExpr(tree.cond); } else { print("("); @@ -911,7 +876,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { try { print("for ("); if (tree.init.nonEmpty()) { - if (Javac.compareCTC(getTag(tree.init.head), VARDEF)) { + if (VARDEF.equals(treeTag(tree.init.head))) { printExpr(tree.init.head); for (List l = tree.init.tail; l.nonEmpty(); l = l.tail) { JCVariableDecl vdef = (JCVariableDecl)l.head; @@ -958,7 +923,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitSwitch(JCSwitch tree) { try { print("switch "); - if (Javac.compareCTC(getTag(tree.selector), PARENS)) { + if (PARENS.equals(treeTag(tree.selector))) { printExpr(tree.selector); } else { print("("); @@ -997,7 +962,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitSynchronized(JCSynchronized tree) { try { print("synchronized "); - if (Javac.compareCTC(getTag(tree.lock), PARENS)) { + if (PARENS.equals(treeTag(tree.lock))) { printExpr(tree.lock); } else { print("("); @@ -1078,7 +1043,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitIf(JCIf tree) { try { print("if "); - if (Javac.compareCTC(getTag(tree.cond), PARENS)) { + if (PARENS.equals(treeTag(tree.cond))) { printExpr(tree.cond); } else { print("("); @@ -1174,7 +1139,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitApply(JCMethodInvocation tree) { try { if (!tree.typeargs.isEmpty()) { - if (Javac.compareCTC(getTag(tree.meth), SELECT)) { + if (SELECT.equals(treeTag(tree.meth))) { JCFieldAccess left = (JCFieldAccess)tree.meth; printExpr(left.selected); print(".<"); @@ -1278,7 +1243,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { } } - public String operatorName(Object tag) { + public String operatorName(TreeTag tag) { String result = OPERATORS.get(tag); if (result == null) throw new Error(); return result; @@ -1300,9 +1265,9 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { public void visitUnary(JCUnary tree) { try { int ownprec = isOwnPrec(tree); - String opname = operatorName(getTag(tree)); + String opname = operatorName(treeTag(tree)); open(prec, ownprec); - if (isPostUnary(tree)) { + if (isPrefixUnary(tree)) { print(opname); printExpr(tree.arg, ownprec); } else { @@ -1315,63 +1280,18 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { } } - private String assignOpName(JCExpression tree) { - try { - Object tag = getTag(tree); - if (JavaCompiler.version().startsWith("1.8")) { - return operatorName(tag.getClass().getMethod("noAssignOp").invoke(tree)); - } else { - return operatorName((Integer)((Integer)tag - (Integer)JCTree.class.getField("ASGOffset").get(null))); - } - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (Exception e) { - if (e instanceof RuntimeException) throw (RuntimeException) e; - throw new RuntimeException(e); - } + private int isOwnPrec(JCExpression tree) { + return treeTag(tree).getOperatorPrecedenceLevel(); } - private int isOwnPrec(JCExpression tree) { - try { - if (JavaCompiler.version().startsWith("1.8")) { - return (Integer)TreeInfo.class.getMethod("opPrec", Class.forName("com.sun.tools.javac.code.TypeTag")).invoke(null, getTag(tree)); - } else { - return (Integer)TreeInfo.class.getMethod("opPrec", Integer.TYPE).invoke(null, getTag(tree)); - } - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (Exception e) { - if (e instanceof RuntimeException) throw (RuntimeException) e; - throw new RuntimeException(e); - } + private boolean isPrefixUnary(JCUnary tree) { + return treeTag(tree).isPrefixUnaryOp(); } - private boolean isPostUnary(JCUnary tree) { - try { - Object tag = getTag(tree); - if (JavaCompiler.version().startsWith("1.8")) { - return (Boolean) tag.getClass().getMethod("isPostUnaryOp").invoke(tree); - } else { - return ((Integer) tag) <= ((Integer) Javac.getTreeTag("PREDEC")); - } - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (Exception e) { - if (e instanceof RuntimeException) throw (RuntimeException) e; - throw new RuntimeException(e); - } - } - public void visitBinary(JCBinary tree) { try { int ownprec = isOwnPrec(tree); - String opname = operatorName(getTag(tree)); + String opname = operatorName(treeTag(tree)); open(prec, ownprec); printExpr(tree.lhs, ownprec); print(" " + opname + " "); @@ -1436,19 +1356,17 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { } public void visitLiteral(JCLiteral tree) { + TypeTag typeTag = typeTag(tree); try { - if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_INT)) print(tree.value.toString()); - else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_LONG)) print(tree.value + "L"); - else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_FLOAT)) print(tree.value + "F"); - else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_DOUBLE)) print(tree.value.toString()); - else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_CHAR)) { - print("\'" + - Convert.quote( - String.valueOf((char)((Number)tree.value).intValue()))+ - "\'"); + if (CTC_INT.equals(typeTag)) print(tree.value.toString()); + else if (CTC_LONG.equals(typeTag)) print(tree.value + "L"); + else if (CTC_FLOAT.equals(typeTag)) print(tree.value + "F"); + else if (CTC_DOUBLE.equals(typeTag)) print(tree.value.toString()); + else if (CTC_CHAR.equals(typeTag)) { + print("\'" + Convert.quote(String.valueOf((char)((Number)tree.value).intValue())) + "\'"); } - else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_BOOLEAN)) print(((Number)tree.value).intValue() == 1 ? "true" : "false"); - else if (Javac.compareCTC(Javac.getTreeTypeTag(tree), Javac.CTC_BOT)) print("null"); + else if (CTC_BOOLEAN.equals(typeTag)) print(((Number)tree.value).intValue() == 1 ? "true" : "false"); + else if (CTC_BOT.equals(typeTag)) print("null"); else print("\"" + Convert.quote(tree.value.toString()) + "\""); } catch (IOException e) { throw new UncheckedIOException(e); @@ -1456,17 +1374,17 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { } public void visitTypeIdent(JCPrimitiveTypeTree tree) { - Object typetag = Javac.getTreeTypeTag(tree); + TypeTag typetag = typeTag(tree); try { - if (Javac.compareCTC(typetag, Javac.CTC_BYTE)) print("byte"); - else if (Javac.compareCTC(typetag, Javac.CTC_CHAR)) print("char"); - else if (Javac.compareCTC(typetag, Javac.CTC_SHORT)) print("short"); - else if (Javac.compareCTC(typetag, Javac.CTC_INT)) print("int"); - else if (Javac.compareCTC(typetag, Javac.CTC_LONG)) print("long"); - else if (Javac.compareCTC(typetag, Javac.CTC_FLOAT)) print("float"); - else if (Javac.compareCTC(typetag, Javac.CTC_DOUBLE)) print("double"); - else if (Javac.compareCTC(typetag, Javac.CTC_BOOLEAN)) print("boolean"); - else if (Javac.compareCTC(typetag, Javac.CTC_VOID)) print("void"); + if (CTC_BYTE.equals(typetag)) print ("byte"); + else if (CTC_CHAR.equals(typetag)) print ("char"); + else if (CTC_SHORT.equals(typetag)) print ("short"); + else if (CTC_INT.equals(typetag)) print ("int"); + else if (CTC_LONG.equals(typetag)) print ("long"); + else if (CTC_FLOAT.equals(typetag)) print ("float"); + else if (CTC_DOUBLE.equals(typetag)) print ("double"); + else if (CTC_BOOLEAN.equals(typetag)) print ("boolean"); + else if (CTC_VOID.equals(typetag)) print ("void"); else print("error"); } catch (IOException e) { throw new UncheckedIOException(e); diff --git a/src/utils/lombok/javac/Javac.java b/src/utils/lombok/javac/Javac.java index b0540997..014007d4 100644 --- a/src/utils/lombok/javac/Javac.java +++ b/src/utils/lombok/javac/Javac.java @@ -47,7 +47,6 @@ 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.JCPrimitiveTypeTree; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** @@ -133,34 +132,17 @@ public class Javac { public static final TypeTag CTC_CLASS = typeTag("CLASS"); public static final TreeTag CTC_NOT_EQUAL = treeTag("NE"); + public static final TreeTag CTC_POS = treeTag("POS"); + public static final TreeTag CTC_NEG = treeTag("NEG"); public static final TreeTag CTC_NOT = treeTag("NOT"); + public static final TreeTag CTC_COMPL = treeTag("COMPL"); public static final TreeTag CTC_BITXOR = treeTag("BITXOR"); public static final TreeTag CTC_UNSIGNED_SHIFT_RIGHT = treeTag("USR"); public static final TreeTag CTC_MUL = treeTag("MUL"); public static final TreeTag CTC_PLUS = treeTag("PLUS"); public static final TreeTag CTC_EQUAL = treeTag("EQ"); - - public static boolean compareCTC(TreeTag ctc1, TreeTag ctc2) { - boolean ctc1IsNull = ctc1 == null || ctc1.value == null; - boolean ctc2IsNull = ctc2 == null || ctc2.value == null; - if (ctc1IsNull || ctc2IsNull) return ctc1IsNull && ctc2IsNull; - return ctc1.value.equals(ctc2.value); - } - - public static boolean compareCTC(TypeTag ctc1, TypeTag ctc2) { - boolean ctc1IsNull = ctc1 == null || ctc1.value == null; - boolean ctc2IsNull = ctc2 == null || ctc2.value == null; - if (ctc1IsNull || ctc2IsNull) return ctc1IsNull && ctc2IsNull; - return ctc1.value.equals(ctc2.value); - } - - public static Object getTreeTypeTag(JCPrimitiveTypeTree tree) { - return tree.typetag; - } - - public static Object getTreeTypeTag(JCLiteral tree) { - return tree.typetag; - } + public static final TreeTag CTC_PREINC = treeTag("PREINC"); + public static final TreeTag CTC_PREDEC = treeTag("PREDEC"); private static final Method getExtendsClause, getEndPosition; @@ -245,7 +227,7 @@ public class Javac { return new JCNoType(((Integer) tag.value).intValue()); } else { try { - if (compareCTC(tag, CTC_VOID)) { + if (CTC_VOID.equals(tag)) { return (Type) JC_VOID_TYPE.newInstance(); } else { return (Type) JC_NO_TYPE.newInstance(); @@ -276,28 +258,9 @@ public class Javac { } } - private static final Field JCTREE_TAG, JCLITERAL_TYPETAG, JCPRIMITIVETYPETREE_TYPETAG, JCCOMPILATIONUNIT_ENDPOSITIONS, JCCOMPILATIONUNIT_DOCCOMMENTS; - private static final Method JCTREE_GETTAG; + private static final Field JCCOMPILATIONUNIT_ENDPOSITIONS, JCCOMPILATIONUNIT_DOCCOMMENTS; static { Field f = null; - try { - f = JCTree.class.getDeclaredField("tag"); - } catch (NoSuchFieldException e) {} - JCTREE_TAG = f; - - f = null; - try { - f = JCLiteral.class.getDeclaredField("typetag"); - } catch (NoSuchFieldException e) {} - JCLITERAL_TYPETAG = f; - - f = null; - try { - f = JCPrimitiveTypeTree.class.getDeclaredField("typetag"); - } catch (NoSuchFieldException e) {} - JCPRIMITIVETYPETREE_TYPETAG = f; - - f = null; try { f = JCCompilationUnit.class.getDeclaredField("endPositions"); } catch (NoSuchFieldException e) {} @@ -308,41 +271,6 @@ public class Javac { f = JCCompilationUnit.class.getDeclaredField("docComments"); } catch (NoSuchFieldException e) {} JCCOMPILATIONUNIT_DOCCOMMENTS = f; - - Method m = null; - try { - m = JCTree.class.getDeclaredMethod("getTag"); - } catch (NoSuchMethodException e) {} - JCTREE_GETTAG = m; - } - - public static Object getTag(JCTree node) { - if (JCTREE_GETTAG != null) { - try { - return JCTREE_GETTAG.invoke(node); - } catch (Exception e) {} - } - try { - return JCTREE_TAG.get(node); - } catch (Exception e) { - throw new IllegalStateException("Can't get node tag"); - } - } - - public static Object getTypeTag(JCLiteral node) { - try { - return JCLITERAL_TYPETAG.get(node); - } catch (Exception e) { - throw new IllegalStateException("Can't get JCLiteral typetag"); - } - } - - public static Object getTypeTag(JCPrimitiveTypeTree node) { - try { - return JCPRIMITIVETYPETREE_TYPETAG.get(node); - } catch (Exception e) { - throw new IllegalStateException("Can't get JCPrimitiveTypeTree typetag"); - } } static RuntimeException sneakyThrow(Throwable t) { diff --git a/src/utils/lombok/javac/JavacTreeMaker.java b/src/utils/lombok/javac/JavacTreeMaker.java index 916c8735..edbf55af 100644 --- a/src/utils/lombok/javac/JavacTreeMaker.java +++ b/src/utils/lombok/javac/JavacTreeMaker.java @@ -21,6 +21,7 @@ */ package lombok.javac; +import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; @@ -29,6 +30,7 @@ import java.util.concurrent.ConcurrentMap; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayAccess; @@ -81,6 +83,7 @@ import com.sun.tools.javac.tree.JCTree.JCWhileLoop; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.tree.JCTree.LetExpr; import com.sun.tools.javac.tree.JCTree.TypeBoundKind; +import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; @@ -92,49 +95,101 @@ public class JavacTreeMaker { this.tm = tm; } + public TreeMaker getUnderlyingTreeMaker() { + return tm; + } + public JavacTreeMaker at(int pos) { tm.at(pos); return this; } private static class MethodId { + private final Class owner; private final String name; private final Class returnType; private final Class[] paramTypes; - MethodId(String name, Class returnType, Class... types) { + MethodId(Class owner, String name, Class returnType, Class... types) { + this.owner = owner; this.name = name; this.paramTypes = types; this.returnType = returnType; } - } - private static Object getFieldCached(ConcurrentMap cache, String className, String fieldName) { - Object value = cache.get(fieldName); - if (value != null) return value; - try { - value = Class.forName(className).getField(fieldName).get(null); - } catch (NoSuchFieldException e) { - throw Javac.sneakyThrow(e); - } catch (IllegalAccessException e) { - throw Javac.sneakyThrow(e); - } catch (ClassNotFoundException e) { - throw Javac.sneakyThrow(e); + private static class SchroedingerType { + final Object value; + + private SchroedingerType(Object value) { + this.value = value; + } + + @Override public int hashCode() { + return value == null ? -1 : value.hashCode(); } - cache.putIfAbsent(fieldName, value); - return value; + @Override public boolean equals(Object obj) { + if (obj instanceof SchroedingerType) { + Object other = ((SchroedingerType) obj).value; + return value == null ? other == null : value.equals(other); + } + return false; + } + + static Object getFieldCached(ConcurrentMap cache, String className, String fieldName) { + Object value = cache.get(fieldName); + if (value != null) return value; + try { + value = Class.forName(className).getField(fieldName).get(null); + } catch (NoSuchFieldException e) { + throw Javac.sneakyThrow(e); + } catch (IllegalAccessException e) { + throw Javac.sneakyThrow(e); + } catch (ClassNotFoundException e) { + throw Javac.sneakyThrow(e); + } + + cache.putIfAbsent(fieldName, value); + return value; + } + + static Object getFieldCached(ConcurrentMap, Field> cache, Object ref, String fieldName) { + Class c = ref.getClass(); + Field field = cache.get(c); + if (field == null) { + try { + field = c.getField(fieldName); + } catch (NoSuchFieldException e) { + throw Javac.sneakyThrow(e); + } + field.setAccessible(true); + Field old = cache.putIfAbsent(c, field); + if (old != null) field = old; + } + + try { + return field.get(ref); + } catch (IllegalAccessException e) { + throw Javac.sneakyThrow(e); + } + } } - private static interface SchroedingerType {} - - public static class TypeTag implements SchroedingerType { + public static class TypeTag extends SchroedingerType { private static final ConcurrentMap TYPE_TAG_CACHE = new ConcurrentHashMap(); - public final Object value; + private static final ConcurrentMap, Field> FIELD_CACHE = new ConcurrentHashMap, Field>(); private TypeTag(Object value) { - this.value = value; + super(value); + } + + public static TypeTag typeTag(JCTree o) { + return new TypeTag(getFieldCached(FIELD_CACHE, o, "typetag")); + } + + public static TypeTag typeTag(Type t) { + return new TypeTag(getFieldCached(FIELD_CACHE, t, "tag")); } public static TypeTag typeTag(String identifier) { @@ -142,17 +197,63 @@ public class JavacTreeMaker { } } - public static class TreeTag implements SchroedingerType { + public static class TreeTag extends SchroedingerType { private static final ConcurrentMap TREE_TAG_CACHE = new ConcurrentHashMap(); - public final Object value; + private static final Field TAG_FIELD; + private static final Method TAG_METHOD; + private static final MethodId OP_PREC = MethodId(TreeInfo.class, "opPrec", int.class, TreeTag.class); + + static { + Method m = null; + try { + m = JCTree.class.getDeclaredMethod("getTag"); + m.setAccessible(true); + } catch (NoSuchMethodException e) {} + + if (m != null) { + TAG_FIELD = null; + TAG_METHOD = m; + } else { + Field f = null; + try { + f = JCTree.class.getDeclaredField("tag"); + f.setAccessible(true); + } catch (NoSuchFieldException e) {} + TAG_FIELD = f; + TAG_METHOD = null; + } + } private TreeTag(Object value) { - this.value = value; + super(value); + } + + public static TreeTag treeTag(JCTree o) { + try { + if (TAG_METHOD != null) return new TreeTag(TAG_METHOD.invoke(o)); + else return new TreeTag(TAG_FIELD.get(o)); + } catch (InvocationTargetException e) { + throw Javac.sneakyThrow(e.getCause()); + } catch (IllegalAccessException e) { + throw Javac.sneakyThrow(e); + } } public static TreeTag treeTag(String identifier) { return new TreeTag(getFieldCached(TREE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.tree.JCTree" : "com.sun.tools.javac.tree.JCTree$Tag", identifier)); } + + public int getOperatorPrecedenceLevel() { + return invokeAny(null, OP_PREC, value); + } + + public boolean isPrefixUnaryOp() { + return Javac.CTC_NEG.equals(this) || Javac.CTC_POS.equals(this) || Javac.CTC_NOT.equals(this) || Javac.CTC_COMPL.equals(this) || Javac.CTC_PREDEC.equals(this) || Javac.CTC_PREINC.equals(this); + } + } + + static MethodId MethodId(Class owner, String name, Class returnType, Class... types) { + return new MethodId(owner, name, returnType, types); } /** @@ -163,8 +264,8 @@ public class JavacTreeMaker { * Either (A) the type listed here is the same as, or a subtype of, the type of the method in javac's TreeMaker, or * (B) the type listed here is a subtype of SchroedingerType. */ - static MethodId MethodId(String name, Class returnType, Class... types) { - return new MethodId(name, returnType, types); + static MethodId MethodId(String name, Class returnType, Class... types) { + return new MethodId(TreeMaker.class, name, returnType, types); } /** @@ -176,7 +277,7 @@ public class JavacTreeMaker { if (m.getName().equals(name)) { @SuppressWarnings("unchecked") Class r = (Class) m.getReturnType(); Class[] p = m.getParameterTypes(); - return new MethodId(name, r, p); + return new MethodId(TreeMaker.class, name, r, p); } } @@ -185,14 +286,27 @@ public class JavacTreeMaker { private static final ConcurrentHashMap, Method> METHOD_CACHE = new ConcurrentHashMap, Method>(); private J invoke(MethodId m, Object... args) { + return invokeAny(tm, m, args); + } + + @SuppressWarnings("unchecked") private static J invokeAny(Object owner, MethodId m, Object... args) { Method method = METHOD_CACHE.get(m); if (method == null) method = addToCache(m); try { - return m.returnType.cast(method.invoke(tm, args)); + if (m.returnType.isPrimitive()) { + Object res = method.invoke(owner, args); + String sn = res.getClass().getSimpleName().toLowerCase(); + if (!sn.startsWith(m.returnType.getSimpleName())) throw new ClassCastException(res.getClass() + " to " + m.returnType); + return (J) res; + } + return m.returnType.cast(method.invoke(owner, args)); } catch (InvocationTargetException e) { throw Javac.sneakyThrow(e.getCause()); } catch (IllegalAccessException e) { throw Javac.sneakyThrow(e); + } catch (IllegalArgumentException e) { + System.err.println(method); + throw Javac.sneakyThrow(e); } } @@ -200,7 +314,7 @@ public class JavacTreeMaker { Method found = null; outer: - for (Method method : TreeMaker.class.getDeclaredMethods()) { + for (Method method : m.owner.getDeclaredMethods()) { if (!m.name.equals(method.getName())) continue; Class[] t = method.getParameterTypes(); if (t.length != m.paramTypes.length) continue; @@ -210,7 +324,7 @@ public class JavacTreeMaker { if (t[i].isPrimitive()) { if (t[i] != m.paramTypes[i]) continue outer; } else { - if (t[i].isAssignableFrom(m.paramTypes[i])) continue outer; + if (!t[i].isAssignableFrom(m.paramTypes[i])) continue outer; } } } @@ -659,4 +773,10 @@ public class JavacTreeMaker { public JCStatement Call(JCExpression apply) { return invoke(Call, apply); } + + //javac versions: 6-8 + private static final MethodId Type = MethodId("Type"); + public JCExpression Type(Type type) { + return invoke(Type, type); + } } \ No newline at end of file diff --git a/src/utils/lombok/javac/TreeMirrorMaker.java b/src/utils/lombok/javac/TreeMirrorMaker.java index 30915572..23ec2406 100644 --- a/src/utils/lombok/javac/TreeMirrorMaker.java +++ b/src/utils/lombok/javac/TreeMirrorMaker.java @@ -31,7 +31,6 @@ import com.sun.source.tree.VariableTree; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.TreeCopier; -import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.List; /** @@ -47,8 +46,8 @@ import com.sun.tools.javac.util.List; public class TreeMirrorMaker extends TreeCopier { private final IdentityHashMap originalToCopy = new IdentityHashMap(); - public TreeMirrorMaker(TreeMaker maker) { - super(maker); + public TreeMirrorMaker(JavacTreeMaker maker) { + super(maker.getUnderlyingTreeMaker()); } @Override public T copy(T original) { -- cgit From d0d2dd6f5d1b9bd33e9e127f8d66b3387f487271 Mon Sep 17 00:00:00 2001 From: Reinier Zwitserloot Date: Sun, 28 Jul 2013 07:16:12 +0200 Subject: Some work on actually making lombok work on JDK8's javac. --- src/core/lombok/javac/JavacAST.java | 2 +- src/core/lombok/javac/JavacNode.java | 9 + .../lombok/javac/handlers/JavacHandlerUtil.java | 12 +- .../lombok/delombok/PrettyCommentsPrinter.java | 225 +++++++++++---------- src/utils/lombok/javac/JavacTreeMaker.java | 58 +++++- 5 files changed, 184 insertions(+), 122 deletions(-) (limited to 'src/utils/lombok/javac/JavacTreeMaker.java') diff --git a/src/core/lombok/javac/JavacAST.java b/src/core/lombok/javac/JavacAST.java index 1f3b04a4..e49d8ac8 100644 --- a/src/core/lombok/javac/JavacAST.java +++ b/src/core/lombok/javac/JavacAST.java @@ -375,7 +375,7 @@ public class JavacAST extends AST { if (pos == null) pos = astObject.pos(); } if (pos != null && attemptToRemoveErrorsInRange) { - removeFromDeferredDiagnostics(pos.getStartPosition(), pos.getEndPosition(top.endPositions)); + removeFromDeferredDiagnostics(pos.getStartPosition(), node.getEndPosition(pos)); } try { switch (kind) { diff --git a/src/core/lombok/javac/JavacNode.java b/src/core/lombok/javac/JavacNode.java index 30a470a9..6eef36eb 100644 --- a/src/core/lombok/javac/JavacNode.java +++ b/src/core/lombok/javac/JavacNode.java @@ -51,6 +51,15 @@ public class JavacNode extends lombok.core.LombokNode docComments = (Map) dc; + String javadoc = docComments.get(from.get()); if (javadoc != null) { String[] filtered = copyMode.split(javadoc); - cu.docComments.put(to, filtered[0]); - cu.docComments.put(from.get(), filtered[1]); + docComments.put(to, filtered[0]); + docComments.put(from.get(), filtered[1]); } } } catch (Exception ignore) {} diff --git a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java index fd0b0f0d..9978a681 100644 --- a/src/delombok/lombok/delombok/PrettyCommentsPrinter.java +++ b/src/delombok/lombok/delombok/PrettyCommentsPrinter.java @@ -131,12 +131,12 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { private static final TreeTag IMPORT = treeTag("IMPORT"); private static final TreeTag VARDEF = treeTag("VARDEF"); private static final TreeTag SELECT = treeTag("SELECT"); - + private static final Map OPERATORS; static { - Map map = new HashMap(); - + Map map = new HashMap(); + map.put(treeTag("POS"), "+"); map.put(treeTag("NEG"), "-"); map.put(treeTag("NOT"), "!"); @@ -165,132 +165,133 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { map.put(treeTag("MUL"), "*"); map.put(treeTag("DIV"), "/"); map.put(treeTag("MOD"), "%"); - - OPERATORS = map; + + OPERATORS = map; } - private List comments; - private final JCCompilationUnit cu; - private boolean onNewLine = true; - private boolean aligned = false; - private boolean inParams = false; - - private boolean needsSpace = false; - private boolean needsNewLine = false; - private boolean needsAlign = false; - + private List comments; + private final JCCompilationUnit cu; + private boolean onNewLine = true; + private boolean aligned = false; + private boolean inParams = false; + + private boolean needsSpace = false; + private boolean needsNewLine = false; + private boolean needsAlign = false; + public PrettyCommentsPrinter(Writer out, JCCompilationUnit cu, List comments) { this.out = out; - this.comments = comments; - this.cu = cu; + this.comments = comments; + this.cu = cu; + } + + private int endPos(JCTree tree) { + return getEndPosition(tree, cu); + } + + private void consumeComments(int until) throws IOException { + consumeComments(until, null); } - - private int endPos(JCTree tree) { - return tree.getEndPosition(cu.endPositions); - } - private void consumeComments(int until) throws IOException { - consumeComments(until, null); - } private void consumeComments(int until, JCTree tree) throws IOException { - boolean prevNewLine = onNewLine; - boolean found = false; - CommentInfo head = comments.head; - while (comments.nonEmpty() && head.pos < until) { - if (tree != null && docComments != null && docComments.containsKey(tree) && head.isJavadoc() && noFurtherJavadocForthcoming(until)) { - // This is (presumably) the exact same javadoc that has already been associated with the node that we're just about to - // print. These javadoc can be modified by lombok handlers, and as such we should NOT print them from the consumed comments db, - // and instead print the actual javadoc associated with the upcoming node (which the visit method for that node will take care of). - } else { - printComment(head); - } - comments = comments.tail; - head = comments.head; - } - if (!onNewLine && prevNewLine) { - println(); - } - } + boolean prevNewLine = onNewLine; + boolean found = false; + CommentInfo head = comments.head; + while (comments.nonEmpty() && head.pos < until) { + if (tree != null && docComments != null && docComments.containsKey(tree) && head.isJavadoc() && noFurtherJavadocForthcoming(until)) { + // This is (presumably) the exact same javadoc that has already been associated with the node that we're just about to + // print. These javadoc can be modified by lombok handlers, and as such we should NOT print them from the consumed comments db, + // and instead print the actual javadoc associated with the upcoming node (which the visit method for that node will take care of). + } else { + printComment(head); + } + comments = comments.tail; + head = comments.head; + } + if (!onNewLine && prevNewLine) { + println(); + } + } private boolean noFurtherJavadocForthcoming(int until) { - List c = comments; - if (c.nonEmpty()) c = c.tail; - while (c.nonEmpty()) { - if (c.head.pos >= until) return true; - if (c.head.isJavadoc()) return false; - c = c.tail; - } - return true; + List c = comments; + if (c.nonEmpty()) c = c.tail; + while (c.nonEmpty()) { + if (c.head.pos >= until) return true; + if (c.head.isJavadoc()) return false; + c = c.tail; + } + return true; } - + private void consumeTrailingComments(int from) throws IOException { - boolean prevNewLine = onNewLine; - CommentInfo head = comments.head; - boolean stop = false; - while (comments.nonEmpty() && head.prevEndPos == from && !stop && !(head.start == StartConnection.ON_NEXT_LINE || head.start == StartConnection.START_OF_LINE)) { - from = head.endPos; - printComment(head); - stop = (head.end == EndConnection.ON_NEXT_LINE); - comments = comments.tail; - head = comments.head; - } - if (!onNewLine && prevNewLine) { - println(); - } - } - - private void printComment(CommentInfo comment) throws IOException { - prepareComment(comment.start); - print(comment.content); - switch (comment.end) { - case ON_NEXT_LINE: - if (!aligned) { - needsNewLine = true; - needsAlign = true; - } - break; - case AFTER_COMMENT: - needsSpace = true; - break; - case DIRECT_AFTER_COMMENT: - // do nothing - break; - } + boolean prevNewLine = onNewLine; + CommentInfo head = comments.head; + boolean stop = false; + while (comments.nonEmpty() && head.prevEndPos == from && !stop && !(head.start == StartConnection.ON_NEXT_LINE || head.start == StartConnection.START_OF_LINE)) { + from = head.endPos; + printComment(head); + stop = (head.end == EndConnection.ON_NEXT_LINE); + comments = comments.tail; + head = comments.head; + } + if (!onNewLine && prevNewLine) { + println(); + } + } + + private void printComment(CommentInfo comment) throws IOException { + prepareComment(comment.start); + print(comment.content); + switch (comment.end) { + case ON_NEXT_LINE: + if (!aligned) { + needsNewLine = true; + needsAlign = true; + } + break; + case AFTER_COMMENT: + needsSpace = true; + break; + case DIRECT_AFTER_COMMENT: + // do nothing + break; + } + } + + private void prepareComment(StartConnection start) throws IOException { + switch (start) { + case DIRECT_AFTER_PREVIOUS: + needsSpace = false; + break; + case AFTER_PREVIOUS: + needsSpace = true; + break; + case START_OF_LINE: + needsNewLine = true; + needsAlign = false; + break; + case ON_NEXT_LINE: + if (!aligned) { + needsNewLine = true; + needsAlign = true; + } + break; + } } - - private void prepareComment(StartConnection start) throws IOException { - switch (start) { - case DIRECT_AFTER_PREVIOUS: - needsSpace = false; - break; - case AFTER_PREVIOUS: - needsSpace = true; - break; - case START_OF_LINE: - needsNewLine = true; - needsAlign = false; - break; - case ON_NEXT_LINE: - if (!aligned) { - needsNewLine = true; - needsAlign = true; - } - break; - } - } /** The output stream on which trees are printed. */ Writer out; - + /** The current left margin. */ int lmargin = 0; - + /** The enclosing class name. */ Name enclClassName; - + /** A hashtable mapping trees to their documentation comments * (can be null) */ @@ -304,19 +305,19 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { needsAlign = false; for (int i = 0; i < lmargin; i++) out.write("\t"); } - + /** Increase left margin by indentation width. */ void indent() { lmargin++; } - + /** Decrease left margin by indentation width. */ void undent() { lmargin--; } - + /** Enter a new precedence level. Emit a `(' if new precedence level * is less than precedence level so far. * @param contextPrec The precedence level in force so far. @@ -325,7 +326,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { void open(int contextPrec, int ownPrec) throws IOException { if (ownPrec < contextPrec) out.write("("); } - + /** Leave precedence level. Emit a `(' if inner precedence level * is less than precedence level we revert to. * @param contextPrec The precedence level we revert to. @@ -334,7 +335,7 @@ public class PrettyCommentsPrinter extends JCTree.Visitor { void close(int contextPrec, int ownPrec) throws IOException { if (ownPrec < contextPrec) out.write(")"); } - + /** Print string, replacing all non-ascii character with unicode escapes. */ public void print(Object s) throws IOException { diff --git a/src/utils/lombok/javac/JavacTreeMaker.java b/src/utils/lombok/javac/JavacTreeMaker.java index edbf55af..12baf5af 100644 --- a/src/utils/lombok/javac/JavacTreeMaker.java +++ b/src/utils/lombok/javac/JavacTreeMaker.java @@ -116,6 +116,18 @@ public class JavacTreeMaker { this.paramTypes = types; this.returnType = returnType; } + + @Override public String toString() { + StringBuilder out = new StringBuilder(); + out.append(returnType.getName()).append(" ").append(owner.getName()).append(".").append(name).append("("); + boolean f = true; + for (Class p : paramTypes) { + if (f) f = false; + else out.append(", "); + out.append(p.getName()); + } + return out.append(")").toString(); + } } private static class SchroedingerType { @@ -154,13 +166,23 @@ public class JavacTreeMaker { return value; } - static Object getFieldCached(ConcurrentMap, Field> cache, Object ref, String fieldName) { + private static Field NOSUCHFIELDEX_MARKER; + static { + try { + NOSUCHFIELDEX_MARKER = SchroedingerType.class.getDeclaredField("NOSUCHFIELDEX_MARKER"); + } catch (NoSuchFieldException e) { + throw Javac.sneakyThrow(e); + } + } + + static Object getFieldCached(ConcurrentMap, Field> cache, Object ref, String fieldName) throws NoSuchFieldException { Class c = ref.getClass(); Field field = cache.get(c); if (field == null) { try { field = c.getField(fieldName); } catch (NoSuchFieldException e) { + cache.putIfAbsent(c, NOSUCHFIELDEX_MARKER); throw Javac.sneakyThrow(e); } field.setAccessible(true); @@ -168,6 +190,7 @@ public class JavacTreeMaker { if (old != null) field = old; } + if (field == NOSUCHFIELDEX_MARKER) throw new NoSuchFieldException(fieldName); try { return field.get(ref); } catch (IllegalAccessException e) { @@ -179,17 +202,42 @@ public class JavacTreeMaker { public static class TypeTag extends SchroedingerType { private static final ConcurrentMap TYPE_TAG_CACHE = new ConcurrentHashMap(); private static final ConcurrentMap, Field> FIELD_CACHE = new ConcurrentHashMap, Field>(); + private static final Method TYPE_TYPETAG_METHOD; + + static { + Method m = null; + try { + m = Type.class.getDeclaredMethod("getTag"); + m.setAccessible(true); + } catch (NoSuchMethodException e) {} + TYPE_TYPETAG_METHOD = m; + } private TypeTag(Object value) { super(value); } public static TypeTag typeTag(JCTree o) { - return new TypeTag(getFieldCached(FIELD_CACHE, o, "typetag")); + try { + return new TypeTag(getFieldCached(FIELD_CACHE, o, "typetag")); + } catch (NoSuchFieldException e) { + throw Javac.sneakyThrow(e); + } } public static TypeTag typeTag(Type t) { - return new TypeTag(getFieldCached(FIELD_CACHE, t, "tag")); + try { + return new TypeTag(getFieldCached(FIELD_CACHE, t, "tag")); + } catch (NoSuchFieldException e) { + if (TYPE_TYPETAG_METHOD == null) throw new IllegalStateException("Type " + t.getClass() + " has neither 'tag' nor getTag()"); + try { + return new TypeTag(TYPE_TYPETAG_METHOD.invoke(t)); + } catch (IllegalAccessException ex) { + throw Javac.sneakyThrow(ex); + } catch (InvocationTargetException ex) { + throw Javac.sneakyThrow(ex.getCause()); + } + } } public static TypeTag typeTag(String identifier) { @@ -331,7 +379,7 @@ public class JavacTreeMaker { if (found == null) found = method; else throw new IllegalStateException("Lombok TreeMaker frontend issue: multiple matches when looking for method: " + m); } - if (found == null) throw new IllegalStateException("Lombok TreeMaker frontedn issue: no match when looking for method: " + m); + if (found == null) throw new IllegalStateException("Lombok TreeMaker frontend issue: no match when looking for method: " + m); found.setAccessible(true); Object marker = METHOD_CACHE.putIfAbsent(m, found); if (marker == null) return found; @@ -496,7 +544,7 @@ public class JavacTreeMaker { //javac versions: 6-8 private static final MethodId Throw = MethodId("Throw"); - public JCThrow Throw(JCTree expr) { + public JCThrow Throw(JCExpression expr) { return invoke(Throw, expr); } -- cgit