src/share/classes/com/sun/tools/javac/comp/TransTypes.java

Mon, 29 Oct 2012 10:39:49 -0700

author
rfield
date
Mon, 29 Oct 2012 10:39:49 -0700
changeset 1380
a65971893c50
parent 1374
c002fdee76fd
child 1415
01c9d4161882
permissions
-rw-r--r--

8000694: Add generation of lambda implementation code: invokedynamic call, lambda method, adaptor methods
Summary: Add lambda implementation code with calling/supporting code elsewhere in the compiler
Reviewed-by: mcimadamore, jjg

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    30 import com.sun.tools.javac.code.*;
    31 import com.sun.tools.javac.code.Symbol.*;
    32 import com.sun.tools.javac.tree.*;
    33 import com.sun.tools.javac.tree.JCTree.*;
    34 import com.sun.tools.javac.util.*;
    35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    36 import com.sun.tools.javac.util.List;
    38 import static com.sun.tools.javac.code.Flags.*;
    39 import static com.sun.tools.javac.code.Kinds.*;
    40 import static com.sun.tools.javac.code.TypeTag.CLASS;
    41 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
    42 import static com.sun.tools.javac.code.TypeTag.VOID;
    44 /** This pass translates Generic Java to conventional Java.
    45  *
    46  *  <p><b>This is NOT part of any supported API.
    47  *  If you write code that depends on this, you do so at your own risk.
    48  *  This code and its internal interfaces are subject to change or
    49  *  deletion without notice.</b>
    50  */
    51 public class TransTypes extends TreeTranslator {
    52     /** The context key for the TransTypes phase. */
    53     protected static final Context.Key<TransTypes> transTypesKey =
    54         new Context.Key<TransTypes>();
    56     /** Get the instance for this context. */
    57     public static TransTypes instance(Context context) {
    58         TransTypes instance = context.get(transTypesKey);
    59         if (instance == null)
    60             instance = new TransTypes(context);
    61         return instance;
    62     }
    64     private Names names;
    65     private Log log;
    66     private Symtab syms;
    67     private TreeMaker make;
    68     private Enter enter;
    69     private boolean allowEnums;
    70     private Types types;
    71     private final Resolve resolve;
    73     /**
    74      * Flag to indicate whether or not to generate bridge methods.
    75      * For pre-Tiger source there is no need for bridge methods, so it
    76      * can be skipped to get better performance for -source 1.4 etc.
    77      */
    78     private final boolean addBridges;
    80     protected TransTypes(Context context) {
    81         context.put(transTypesKey, this);
    82         names = Names.instance(context);
    83         log = Log.instance(context);
    84         syms = Symtab.instance(context);
    85         enter = Enter.instance(context);
    86         overridden = new HashMap<MethodSymbol,MethodSymbol>();
    87         Source source = Source.instance(context);
    88         allowEnums = source.allowEnums();
    89         addBridges = source.addBridges();
    90         types = Types.instance(context);
    91         make = TreeMaker.instance(context);
    92         resolve = Resolve.instance(context);
    93     }
    95     /** A hashtable mapping bridge methods to the methods they override after
    96      *  type erasure.
    97      */
    98     Map<MethodSymbol,MethodSymbol> overridden;
   100     /** Construct an attributed tree for a cast of expression to target type,
   101      *  unless it already has precisely that type.
   102      *  @param tree    The expression tree.
   103      *  @param target  The target type.
   104      */
   105     JCExpression cast(JCExpression tree, Type target) {
   106         int oldpos = make.pos;
   107         make.at(tree.pos);
   108         if (!types.isSameType(tree.type, target)) {
   109             if (!resolve.isAccessible(env, target.tsym))
   110                 resolve.logAccessErrorInternal(env, tree, target);
   111             tree = make.TypeCast(make.Type(target), tree).setType(target);
   112         }
   113         make.pos = oldpos;
   114         return tree;
   115     }
   117     /** Construct an attributed tree to coerce an expression to some erased
   118      *  target type, unless the expression is already assignable to that type.
   119      *  If target type is a constant type, use its base type instead.
   120      *  @param tree    The expression tree.
   121      *  @param target  The target type.
   122      */
   123     public JCExpression coerce(Env<AttrContext> env, JCExpression tree, Type target) {
   124         Env<AttrContext> prevEnv = this.env;
   125         try {
   126             this.env = env;
   127             return coerce(tree, target);
   128         }
   129         finally {
   130             this.env = prevEnv;
   131         }
   132     }
   133     JCExpression coerce(JCExpression tree, Type target) {
   134         Type btarget = target.baseType();
   135         if (tree.type.isPrimitive() == target.isPrimitive()) {
   136             return types.isAssignable(tree.type, btarget, Warner.noWarnings)
   137                 ? tree
   138                 : cast(tree, btarget);
   139         }
   140         return tree;
   141     }
   143     /** Given an erased reference type, assume this type as the tree's type.
   144      *  Then, coerce to some given target type unless target type is null.
   145      *  This operation is used in situations like the following:
   146      *
   147      *  <pre>{@code
   148      *  class Cell<A> { A value; }
   149      *  ...
   150      *  Cell<Integer> cell;
   151      *  Integer x = cell.value;
   152      *  }</pre>
   153      *
   154      *  Since the erasure of Cell.value is Object, but the type
   155      *  of cell.value in the assignment is Integer, we need to
   156      *  adjust the original type of cell.value to Object, and insert
   157      *  a cast to Integer. That is, the last assignment becomes:
   158      *
   159      *  <pre>{@code
   160      *  Integer x = (Integer)cell.value;
   161      *  }</pre>
   162      *
   163      *  @param tree       The expression tree whose type might need adjustment.
   164      *  @param erasedType The expression's type after erasure.
   165      *  @param target     The target type, which is usually the erasure of the
   166      *                    expression's original type.
   167      */
   168     JCExpression retype(JCExpression tree, Type erasedType, Type target) {
   169 //      System.err.println("retype " + tree + " to " + erasedType);//DEBUG
   170         if (!erasedType.isPrimitive()) {
   171             if (target != null && target.isPrimitive())
   172                 target = erasure(tree.type);
   173             tree.type = erasedType;
   174             if (target != null) return coerce(tree, target);
   175         }
   176         return tree;
   177     }
   179     /** Translate method argument list, casting each argument
   180      *  to its corresponding type in a list of target types.
   181      *  @param _args            The method argument list.
   182      *  @param parameters       The list of target types.
   183      *  @param varargsElement   The erasure of the varargs element type,
   184      *  or null if translating a non-varargs invocation
   185      */
   186     <T extends JCTree> List<T> translateArgs(List<T> _args,
   187                                            List<Type> parameters,
   188                                            Type varargsElement) {
   189         if (parameters.isEmpty()) return _args;
   190         List<T> args = _args;
   191         while (parameters.tail.nonEmpty()) {
   192             args.head = translate(args.head, parameters.head);
   193             args = args.tail;
   194             parameters = parameters.tail;
   195         }
   196         Type parameter = parameters.head;
   197         Assert.check(varargsElement != null || args.length() == 1);
   198         if (varargsElement != null) {
   199             while (args.nonEmpty()) {
   200                 args.head = translate(args.head, varargsElement);
   201                 args = args.tail;
   202             }
   203         } else {
   204             args.head = translate(args.head, parameter);
   205         }
   206         return _args;
   207     }
   209     public <T extends JCTree> List<T> translateArgs(List<T> _args,
   210                                            List<Type> parameters,
   211                                            Type varargsElement,
   212                                            Env<AttrContext> localEnv) {
   213         Env<AttrContext> prevEnv = env;
   214         try {
   215             env = localEnv;
   216             return translateArgs(_args, parameters, varargsElement);
   217         }
   218         finally {
   219             env = prevEnv;
   220         }
   221     }
   223     /** Add a bridge definition and enter corresponding method symbol in
   224      *  local scope of origin.
   225      *
   226      *  @param pos     The source code position to be used for the definition.
   227      *  @param meth    The method for which a bridge needs to be added
   228      *  @param impl    That method's implementation (possibly the method itself)
   229      *  @param origin  The class to which the bridge will be added
   230      *  @param hypothetical
   231      *                 True if the bridge method is not strictly necessary in the
   232      *                 binary, but is represented in the symbol table to detect
   233      *                 erasure clashes.
   234      *  @param bridges The list buffer to which the bridge will be added
   235      */
   236     void addBridge(DiagnosticPosition pos,
   237                    MethodSymbol meth,
   238                    MethodSymbol impl,
   239                    ClassSymbol origin,
   240                    boolean hypothetical,
   241                    ListBuffer<JCTree> bridges) {
   242         make.at(pos);
   243         Type origType = types.memberType(origin.type, meth);
   244         Type origErasure = erasure(origType);
   246         // Create a bridge method symbol and a bridge definition without a body.
   247         Type bridgeType = meth.erasure(types);
   248         long flags = impl.flags() & AccessFlags | SYNTHETIC | BRIDGE;
   249         if (hypothetical) flags |= HYPOTHETICAL;
   250         MethodSymbol bridge = new MethodSymbol(flags,
   251                                                meth.name,
   252                                                bridgeType,
   253                                                origin);
   254         if (!hypothetical) {
   255             JCMethodDecl md = make.MethodDef(bridge, null);
   257             // The bridge calls this.impl(..), if we have an implementation
   258             // in the current class, super.impl(...) otherwise.
   259             JCExpression receiver = (impl.owner == origin)
   260                 ? make.This(origin.erasure(types))
   261                 : make.Super(types.supertype(origin.type).tsym.erasure(types), origin);
   263             // The type returned from the original method.
   264             Type calltype = erasure(impl.type.getReturnType());
   266             // Construct a call of  this.impl(params), or super.impl(params),
   267             // casting params and possibly results as needed.
   268             JCExpression call =
   269                 make.Apply(
   270                            null,
   271                            make.Select(receiver, impl).setType(calltype),
   272                            translateArgs(make.Idents(md.params), origErasure.getParameterTypes(), null))
   273                 .setType(calltype);
   274             JCStatement stat = (origErasure.getReturnType().hasTag(VOID))
   275                 ? make.Exec(call)
   276                 : make.Return(coerce(call, bridgeType.getReturnType()));
   277             md.body = make.Block(0, List.of(stat));
   279             // Add bridge to `bridges' buffer
   280             bridges.append(md);
   281         }
   283         // Add bridge to scope of enclosing class and `overridden' table.
   284         origin.members().enter(bridge);
   285         overridden.put(bridge, meth);
   286     }
   288     /** Add bridge if given symbol is a non-private, non-static member
   289      *  of the given class, which is either defined in the class or non-final
   290      *  inherited, and one of the two following conditions holds:
   291      *  1. The method's type changes in the given class, as compared to the
   292      *     class where the symbol was defined, (in this case
   293      *     we have extended a parameterized class with non-trivial parameters).
   294      *  2. The method has an implementation with a different erased return type.
   295      *     (in this case we have used co-variant returns).
   296      *  If a bridge already exists in some other class, no new bridge is added.
   297      *  Instead, it is checked that the bridge symbol overrides the method symbol.
   298      *  (Spec ???).
   299      *  todo: what about bridges for privates???
   300      *
   301      *  @param pos     The source code position to be used for the definition.
   302      *  @param sym     The symbol for which a bridge might have to be added.
   303      *  @param origin  The class in which the bridge would go.
   304      *  @param bridges The list buffer to which the bridge would be added.
   305      */
   306     void addBridgeIfNeeded(DiagnosticPosition pos,
   307                            Symbol sym,
   308                            ClassSymbol origin,
   309                            ListBuffer<JCTree> bridges) {
   310         if (sym.kind == MTH &&
   311             sym.name != names.init &&
   312             (sym.flags() & (PRIVATE | STATIC)) == 0 &&
   313             (sym.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC &&
   314             sym.isMemberOf(origin, types))
   315         {
   316             MethodSymbol meth = (MethodSymbol)sym;
   317             MethodSymbol bridge = meth.binaryImplementation(origin, types);
   318             MethodSymbol impl = meth.implementation(origin, types, true, overrideBridgeFilter);
   319             if (bridge == null ||
   320                 bridge == meth ||
   321                 (impl != null && !bridge.owner.isSubClass(impl.owner, types))) {
   322                 // No bridge was added yet.
   323                 if (impl != null && isBridgeNeeded(meth, impl, origin.type)) {
   324                     addBridge(pos, meth, impl, origin, bridge==impl, bridges);
   325                 } else if (impl == meth
   326                            && impl.owner != origin
   327                            && (impl.flags() & FINAL) == 0
   328                            && (meth.flags() & (ABSTRACT|PUBLIC)) == PUBLIC
   329                            && (origin.flags() & PUBLIC) > (impl.owner.flags() & PUBLIC)) {
   330                     // this is to work around a horrible but permanent
   331                     // reflection design error.
   332                     addBridge(pos, meth, impl, origin, false, bridges);
   333                 }
   334             } else if ((bridge.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) == SYNTHETIC) {
   335                 MethodSymbol other = overridden.get(bridge);
   336                 if (other != null && other != meth) {
   337                     if (impl == null || !impl.overrides(other, origin, types, true)) {
   338                         // Bridge for other symbol pair was added
   339                         log.error(pos, "name.clash.same.erasure.no.override",
   340                                   other, other.location(origin.type, types),
   341                                   meth,  meth.location(origin.type, types));
   342                     }
   343                 }
   344             } else if (!bridge.overrides(meth, origin, types, true)) {
   345                 // Accidental binary override without source override.
   346                 if (bridge.owner == origin ||
   347                     types.asSuper(bridge.owner.type, meth.owner) == null)
   348                     // Don't diagnose the problem if it would already
   349                     // have been reported in the superclass
   350                     log.error(pos, "name.clash.same.erasure.no.override",
   351                               bridge, bridge.location(origin.type, types),
   352                               meth,  meth.location(origin.type, types));
   353             }
   354         }
   355     }
   356     // where
   357         Filter<Symbol> overrideBridgeFilter = new Filter<Symbol>() {
   358             public boolean accepts(Symbol s) {
   359                 return (s.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC;
   360             }
   361         };
   362         /**
   363          * @param method The symbol for which a bridge might have to be added
   364          * @param impl The implementation of method
   365          * @param dest The type in which the bridge would go
   366          */
   367         private boolean isBridgeNeeded(MethodSymbol method,
   368                                        MethodSymbol impl,
   369                                        Type dest) {
   370             if (impl != method) {
   371                 // If either method or impl have different erasures as
   372                 // members of dest, a bridge is needed.
   373                 Type method_erasure = method.erasure(types);
   374                 if (!isSameMemberWhenErased(dest, method, method_erasure))
   375                     return true;
   376                 Type impl_erasure = impl.erasure(types);
   377                 if (!isSameMemberWhenErased(dest, impl, impl_erasure))
   378                     return true;
   380                 // If the erasure of the return type is different, a
   381                 // bridge is needed.
   382                 return !types.isSameType(impl_erasure.getReturnType(),
   383                                          method_erasure.getReturnType());
   384             } else {
   385                // method and impl are the same...
   386                 if ((method.flags() & ABSTRACT) != 0) {
   387                     // ...and abstract so a bridge is not needed.
   388                     // Concrete subclasses will bridge as needed.
   389                     return false;
   390                 }
   392                 // The erasure of the return type is always the same
   393                 // for the same symbol.  Reducing the three tests in
   394                 // the other branch to just one:
   395                 return !isSameMemberWhenErased(dest, method, method.erasure(types));
   396             }
   397         }
   398         /**
   399          * Lookup the method as a member of the type.  Compare the
   400          * erasures.
   401          * @param type the class where to look for the method
   402          * @param method the method to look for in class
   403          * @param erasure the erasure of method
   404          */
   405         private boolean isSameMemberWhenErased(Type type,
   406                                                MethodSymbol method,
   407                                                Type erasure) {
   408             return types.isSameType(erasure(types.memberType(type, method)),
   409                                     erasure);
   410         }
   412     void addBridges(DiagnosticPosition pos,
   413                     TypeSymbol i,
   414                     ClassSymbol origin,
   415                     ListBuffer<JCTree> bridges) {
   416         for (Scope.Entry e = i.members().elems; e != null; e = e.sibling)
   417             addBridgeIfNeeded(pos, e.sym, origin, bridges);
   418         for (List<Type> l = types.interfaces(i.type); l.nonEmpty(); l = l.tail)
   419             addBridges(pos, l.head.tsym, origin, bridges);
   420     }
   422     /** Add all necessary bridges to some class appending them to list buffer.
   423      *  @param pos     The source code position to be used for the bridges.
   424      *  @param origin  The class in which the bridges go.
   425      *  @param bridges The list buffer to which the bridges are added.
   426      */
   427     void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
   428         Type st = types.supertype(origin.type);
   429         while (st.hasTag(CLASS)) {
   430 //          if (isSpecialization(st))
   431             addBridges(pos, st.tsym, origin, bridges);
   432             st = types.supertype(st);
   433         }
   434         for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
   435 //          if (isSpecialization(l.head))
   436             addBridges(pos, l.head.tsym, origin, bridges);
   437     }
   439 /* ************************************************************************
   440  * Visitor methods
   441  *************************************************************************/
   443     /** Visitor argument: proto-type.
   444      */
   445     private Type pt;
   447     /** Visitor method: perform a type translation on tree.
   448      */
   449     public <T extends JCTree> T translate(T tree, Type pt) {
   450         Type prevPt = this.pt;
   451         try {
   452             this.pt = pt;
   453             return translate(tree);
   454         } finally {
   455             this.pt = prevPt;
   456         }
   457     }
   459     /** Visitor method: perform a type translation on list of trees.
   460      */
   461     public <T extends JCTree> List<T> translate(List<T> trees, Type pt) {
   462         Type prevPt = this.pt;
   463         List<T> res;
   464         try {
   465             this.pt = pt;
   466             res = translate(trees);
   467         } finally {
   468             this.pt = prevPt;
   469         }
   470         return res;
   471     }
   473     public void visitClassDef(JCClassDecl tree) {
   474         translateClass(tree.sym);
   475         result = tree;
   476     }
   478     JCTree currentMethod = null;
   479     public void visitMethodDef(JCMethodDecl tree) {
   480         JCTree previousMethod = currentMethod;
   481         try {
   482             currentMethod = tree;
   483             tree.restype = translate(tree.restype, null);
   484             tree.typarams = List.nil();
   485             tree.params = translateVarDefs(tree.params);
   486             tree.thrown = translate(tree.thrown, null);
   487             tree.body = translate(tree.body, tree.sym.erasure(types).getReturnType());
   488             tree.type = erasure(tree.type);
   489             result = tree;
   490         } finally {
   491             currentMethod = previousMethod;
   492         }
   494         // Check that we do not introduce a name clash by erasing types.
   495         for (Scope.Entry e = tree.sym.owner.members().lookup(tree.name);
   496              e.sym != null;
   497              e = e.next()) {
   498             if (e.sym != tree.sym &&
   499                 types.isSameType(erasure(e.sym.type), tree.type)) {
   500                 log.error(tree.pos(),
   501                           "name.clash.same.erasure", tree.sym,
   502                           e.sym);
   503                 return;
   504             }
   505         }
   506     }
   508     public void visitVarDef(JCVariableDecl tree) {
   509         tree.vartype = translate(tree.vartype, null);
   510         tree.init = translate(tree.init, tree.sym.erasure(types));
   511         tree.type = erasure(tree.type);
   512         result = tree;
   513     }
   515     public void visitDoLoop(JCDoWhileLoop tree) {
   516         tree.body = translate(tree.body);
   517         tree.cond = translate(tree.cond, syms.booleanType);
   518         result = tree;
   519     }
   521     public void visitWhileLoop(JCWhileLoop tree) {
   522         tree.cond = translate(tree.cond, syms.booleanType);
   523         tree.body = translate(tree.body);
   524         result = tree;
   525     }
   527     public void visitForLoop(JCForLoop tree) {
   528         tree.init = translate(tree.init, null);
   529         if (tree.cond != null)
   530             tree.cond = translate(tree.cond, syms.booleanType);
   531         tree.step = translate(tree.step, null);
   532         tree.body = translate(tree.body);
   533         result = tree;
   534     }
   536     public void visitForeachLoop(JCEnhancedForLoop tree) {
   537         tree.var = translate(tree.var, null);
   538         Type iterableType = tree.expr.type;
   539         tree.expr = translate(tree.expr, erasure(tree.expr.type));
   540         if (types.elemtype(tree.expr.type) == null)
   541             tree.expr.type = iterableType; // preserve type for Lower
   542         tree.body = translate(tree.body);
   543         result = tree;
   544     }
   546     public void visitLambda(JCLambda tree) {
   547         JCTree prevMethod = currentMethod;
   548         try {
   549             currentMethod = null;
   550             tree.params = translate(tree.params);
   551             tree.body = translate(tree.body, null);
   552             //save non-erased target
   553             tree.targetType = tree.type;
   554             tree.type = erasure(tree.type);
   555             result = tree;
   556         }
   557         finally {
   558             currentMethod = prevMethod;
   559         }
   560     }
   562     public void visitSwitch(JCSwitch tree) {
   563         Type selsuper = types.supertype(tree.selector.type);
   564         boolean enumSwitch = selsuper != null &&
   565             selsuper.tsym == syms.enumSym;
   566         Type target = enumSwitch ? erasure(tree.selector.type) : syms.intType;
   567         tree.selector = translate(tree.selector, target);
   568         tree.cases = translateCases(tree.cases);
   569         result = tree;
   570     }
   572     public void visitCase(JCCase tree) {
   573         tree.pat = translate(tree.pat, null);
   574         tree.stats = translate(tree.stats);
   575         result = tree;
   576     }
   578     public void visitSynchronized(JCSynchronized tree) {
   579         tree.lock = translate(tree.lock, erasure(tree.lock.type));
   580         tree.body = translate(tree.body);
   581         result = tree;
   582     }
   584     public void visitTry(JCTry tree) {
   585         tree.resources = translate(tree.resources, syms.autoCloseableType);
   586         tree.body = translate(tree.body);
   587         tree.catchers = translateCatchers(tree.catchers);
   588         tree.finalizer = translate(tree.finalizer);
   589         result = tree;
   590     }
   592     public void visitConditional(JCConditional tree) {
   593         tree.cond = translate(tree.cond, syms.booleanType);
   594         tree.truepart = translate(tree.truepart, erasure(tree.type));
   595         tree.falsepart = translate(tree.falsepart, erasure(tree.type));
   596         tree.type = erasure(tree.type);
   597         result = retype(tree, tree.type, pt);
   598     }
   600    public void visitIf(JCIf tree) {
   601         tree.cond = translate(tree.cond, syms.booleanType);
   602         tree.thenpart = translate(tree.thenpart);
   603         tree.elsepart = translate(tree.elsepart);
   604         result = tree;
   605     }
   607     public void visitExec(JCExpressionStatement tree) {
   608         tree.expr = translate(tree.expr, null);
   609         result = tree;
   610     }
   612     public void visitReturn(JCReturn tree) {
   613         tree.expr = translate(tree.expr, currentMethod != null ? types.erasure(currentMethod.type).getReturnType() : null);
   614         result = tree;
   615     }
   617     public void visitThrow(JCThrow tree) {
   618         tree.expr = translate(tree.expr, erasure(tree.expr.type));
   619         result = tree;
   620     }
   622     public void visitAssert(JCAssert tree) {
   623         tree.cond = translate(tree.cond, syms.booleanType);
   624         if (tree.detail != null)
   625             tree.detail = translate(tree.detail, erasure(tree.detail.type));
   626         result = tree;
   627     }
   629     public void visitApply(JCMethodInvocation tree) {
   630         tree.meth = translate(tree.meth, null);
   631         Symbol meth = TreeInfo.symbol(tree.meth);
   632         Type mt = meth.erasure(types);
   633         List<Type> argtypes = mt.getParameterTypes();
   634         if (allowEnums &&
   635             meth.name==names.init &&
   636             meth.owner == syms.enumSym)
   637             argtypes = argtypes.tail.tail;
   638         if (tree.varargsElement != null)
   639             tree.varargsElement = types.erasure(tree.varargsElement);
   640         else
   641             Assert.check(tree.args.length() == argtypes.length());
   642         tree.args = translateArgs(tree.args, argtypes, tree.varargsElement);
   644         tree.type = types.erasure(tree.type);
   645         // Insert casts of method invocation results as needed.
   646         result = retype(tree, mt.getReturnType(), pt);
   647     }
   649     public void visitNewClass(JCNewClass tree) {
   650         if (tree.encl != null)
   651             tree.encl = translate(tree.encl, erasure(tree.encl.type));
   652         tree.clazz = translate(tree.clazz, null);
   653         if (tree.varargsElement != null)
   654             tree.varargsElement = types.erasure(tree.varargsElement);
   655         tree.args = translateArgs(
   656             tree.args, tree.constructor.erasure(types).getParameterTypes(), tree.varargsElement);
   657         tree.def = translate(tree.def, null);
   658         if (tree.constructorType != null)
   659             tree.constructorType = erasure(tree.constructorType);
   660         tree.type = erasure(tree.type);
   661         result = tree;
   662     }
   664     public void visitNewArray(JCNewArray tree) {
   665         tree.elemtype = translate(tree.elemtype, null);
   666         translate(tree.dims, syms.intType);
   667         if (tree.type != null) {
   668             tree.elems = translate(tree.elems, erasure(types.elemtype(tree.type)));
   669             tree.type = erasure(tree.type);
   670         } else {
   671             tree.elems = translate(tree.elems, null);
   672         }
   674         result = tree;
   675     }
   677     public void visitParens(JCParens tree) {
   678         tree.expr = translate(tree.expr, pt);
   679         tree.type = erasure(tree.type);
   680         result = tree;
   681     }
   683     public void visitAssign(JCAssign tree) {
   684         tree.lhs = translate(tree.lhs, null);
   685         tree.rhs = translate(tree.rhs, erasure(tree.lhs.type));
   686         tree.type = erasure(tree.type);
   687         result = tree;
   688     }
   690     public void visitAssignop(JCAssignOp tree) {
   691         tree.lhs = translate(tree.lhs, null);
   692         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
   693         tree.type = erasure(tree.type);
   694         result = tree;
   695     }
   697     public void visitUnary(JCUnary tree) {
   698         tree.arg = translate(tree.arg, tree.operator.type.getParameterTypes().head);
   699         result = tree;
   700     }
   702     public void visitBinary(JCBinary tree) {
   703         tree.lhs = translate(tree.lhs, tree.operator.type.getParameterTypes().head);
   704         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
   705         result = tree;
   706     }
   708     public void visitTypeCast(JCTypeCast tree) {
   709         tree.clazz = translate(tree.clazz, null);
   710         tree.type = erasure(tree.type);
   711         tree.expr = translate(tree.expr, tree.type);
   712         result = tree;
   713     }
   715     public void visitTypeTest(JCInstanceOf tree) {
   716         tree.expr = translate(tree.expr, null);
   717         tree.clazz = translate(tree.clazz, null);
   718         result = tree;
   719     }
   721     public void visitIndexed(JCArrayAccess tree) {
   722         tree.indexed = translate(tree.indexed, erasure(tree.indexed.type));
   723         tree.index = translate(tree.index, syms.intType);
   725         // Insert casts of indexed expressions as needed.
   726         result = retype(tree, types.elemtype(tree.indexed.type), pt);
   727     }
   729     // There ought to be nothing to rewrite here;
   730     // we don't generate code.
   731     public void visitAnnotation(JCAnnotation tree) {
   732         result = tree;
   733     }
   735     public void visitIdent(JCIdent tree) {
   736         Type et = tree.sym.erasure(types);
   738         // Map type variables to their bounds.
   739         if (tree.sym.kind == TYP && tree.sym.type.hasTag(TYPEVAR)) {
   740             result = make.at(tree.pos).Type(et);
   741         } else
   742         // Map constants expressions to themselves.
   743         if (tree.type.constValue() != null) {
   744             result = tree;
   745         }
   746         // Insert casts of variable uses as needed.
   747         else if (tree.sym.kind == VAR) {
   748             result = retype(tree, et, pt);
   749         }
   750         else {
   751             tree.type = erasure(tree.type);
   752             result = tree;
   753         }
   754     }
   756     public void visitSelect(JCFieldAccess tree) {
   757         Type t = tree.selected.type;
   758         while (t.hasTag(TYPEVAR))
   759             t = t.getUpperBound();
   760         if (t.isCompound()) {
   761             if ((tree.sym.flags() & IPROXY) != 0) {
   762                 tree.sym = ((MethodSymbol)tree.sym).
   763                     implemented((TypeSymbol)tree.sym.owner, types);
   764             }
   765             tree.selected = coerce(
   766                 translate(tree.selected, erasure(tree.selected.type)),
   767                 erasure(tree.sym.owner.type));
   768         } else
   769             tree.selected = translate(tree.selected, erasure(t));
   771         // Map constants expressions to themselves.
   772         if (tree.type.constValue() != null) {
   773             result = tree;
   774         }
   775         // Insert casts of variable uses as needed.
   776         else if (tree.sym.kind == VAR) {
   777             result = retype(tree, tree.sym.erasure(types), pt);
   778         }
   779         else {
   780             tree.type = erasure(tree.type);
   781             result = tree;
   782         }
   783     }
   785     public void visitReference(JCMemberReference tree) {
   786         tree.expr = translate(tree.expr, null);
   787         //save non-erased target
   788         tree.targetType = tree.type;
   789         tree.type = erasure(tree.type);
   790         result = tree;
   791     }
   793     public void visitTypeArray(JCArrayTypeTree tree) {
   794         tree.elemtype = translate(tree.elemtype, null);
   795         tree.type = erasure(tree.type);
   796         result = tree;
   797     }
   799     /** Visitor method for parameterized types.
   800      */
   801     public void visitTypeApply(JCTypeApply tree) {
   802         JCTree clazz = translate(tree.clazz, null);
   803         result = clazz;
   804     }
   806 /**************************************************************************
   807  * utility methods
   808  *************************************************************************/
   810     private Type erasure(Type t) {
   811         return types.erasure(t);
   812     }
   814     private boolean boundsRestricted(ClassSymbol c) {
   815         Type st = types.supertype(c.type);
   816         if (st.isParameterized()) {
   817             List<Type> actuals = st.allparams();
   818             List<Type> formals = st.tsym.type.allparams();
   819             while (!actuals.isEmpty() && !formals.isEmpty()) {
   820                 Type actual = actuals.head;
   821                 Type formal = formals.head;
   823                 if (!types.isSameType(types.erasure(actual),
   824                         types.erasure(formal)))
   825                     return true;
   827                 actuals = actuals.tail;
   828                 formals = formals.tail;
   829             }
   830         }
   831         return false;
   832     }
   834     private List<JCTree> addOverrideBridgesIfNeeded(DiagnosticPosition pos,
   835                                     final ClassSymbol c) {
   836         ListBuffer<JCTree> buf = ListBuffer.lb();
   837         if (c.isInterface() || !boundsRestricted(c))
   838             return buf.toList();
   839         Type t = types.supertype(c.type);
   840             Scope s = t.tsym.members();
   841             if (s.elems != null) {
   842                 for (Symbol sym : s.getElements(new NeedsOverridBridgeFilter(c))) {
   844                     MethodSymbol m = (MethodSymbol)sym;
   845                     MethodSymbol member = (MethodSymbol)m.asMemberOf(c.type, types);
   846                     MethodSymbol impl = m.implementation(c, types, false);
   848                     if ((impl == null || impl.owner != c) &&
   849                             !types.isSameType(member.erasure(types), m.erasure(types))) {
   850                         addOverrideBridges(pos, m, member, c, buf);
   851                     }
   852                 }
   853             }
   854         return buf.toList();
   855     }
   856     // where
   857         class NeedsOverridBridgeFilter implements Filter<Symbol> {
   859             ClassSymbol c;
   861             NeedsOverridBridgeFilter(ClassSymbol c) {
   862                 this.c = c;
   863             }
   864             public boolean accepts(Symbol s) {
   865                 return s.kind == MTH &&
   866                             !s.isConstructor() &&
   867                             s.isInheritedIn(c, types) &&
   868                             (s.flags() & FINAL) == 0 &&
   869                             (s.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC;
   870             }
   871         }
   873     private void addOverrideBridges(DiagnosticPosition pos,
   874                                     MethodSymbol impl,
   875                                     MethodSymbol member,
   876                                     ClassSymbol c,
   877                                     ListBuffer<JCTree> bridges) {
   878         Type implErasure = impl.erasure(types);
   879         long flags = (impl.flags() & AccessFlags) | SYNTHETIC | BRIDGE | OVERRIDE_BRIDGE;
   880         member = new MethodSymbol(flags, member.name, member.type, c);
   881         JCMethodDecl md = make.MethodDef(member, null);
   882         JCExpression receiver = make.Super(types.supertype(c.type).tsym.erasure(types), c);
   883         Type calltype = erasure(impl.type.getReturnType());
   884         JCExpression call =
   885             make.Apply(null,
   886                        make.Select(receiver, impl).setType(calltype),
   887                        translateArgs(make.Idents(md.params),
   888                                      implErasure.getParameterTypes(), null))
   889             .setType(calltype);
   890         JCStatement stat = (member.getReturnType().hasTag(VOID))
   891             ? make.Exec(call)
   892             : make.Return(coerce(call, member.erasure(types).getReturnType()));
   893         md.body = make.Block(0, List.of(stat));
   894         c.members().enter(member);
   895         bridges.append(md);
   896     }
   898 /**************************************************************************
   899  * main method
   900  *************************************************************************/
   902     private Env<AttrContext> env;
   904     void translateClass(ClassSymbol c) {
   905         Type st = types.supertype(c.type);
   907         // process superclass before derived
   908         if (st.hasTag(CLASS))
   909             translateClass((ClassSymbol)st.tsym);
   911         Env<AttrContext> myEnv = enter.typeEnvs.remove(c);
   912         if (myEnv == null)
   913             return;
   914         Env<AttrContext> oldEnv = env;
   915         try {
   916             env = myEnv;
   917             // class has not been translated yet
   919             TreeMaker savedMake = make;
   920             Type savedPt = pt;
   921             make = make.forToplevel(env.toplevel);
   922             pt = null;
   923             try {
   924                 JCClassDecl tree = (JCClassDecl) env.tree;
   925                 tree.typarams = List.nil();
   926                 super.visitClassDef(tree);
   927                 make.at(tree.pos);
   928                 if (addBridges) {
   929                     ListBuffer<JCTree> bridges = new ListBuffer<JCTree>();
   930                     if (false) //see CR: 6996415
   931                         bridges.appendList(addOverrideBridgesIfNeeded(tree, c));
   932                     if ((tree.sym.flags() & INTERFACE) == 0)
   933                         addBridges(tree.pos(), tree.sym, bridges);
   934                     tree.defs = bridges.toList().prependList(tree.defs);
   935                 }
   936                 tree.type = erasure(tree.type);
   937             } finally {
   938                 make = savedMake;
   939                 pt = savedPt;
   940             }
   941         } finally {
   942             env = oldEnv;
   943         }
   944     }
   946     /** Translate a toplevel class definition.
   947      *  @param cdef    The definition to be translated.
   948      */
   949     public JCTree translateTopLevelClass(JCTree cdef, TreeMaker make) {
   950         // note that this method does NOT support recursion.
   951         this.make = make;
   952         pt = null;
   953         return translate(cdef, null);
   954     }
   955 }

mercurial