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

Tue, 09 Oct 2012 19:10:00 -0700

author
jjg
date
Tue, 09 Oct 2012 19:10:00 -0700
changeset 1357
c75be5bc5283
parent 1352
d4b3cb1ece84
child 1358
fc123bdeddb8
permissions
-rw-r--r--

8000663: clean up langtools imports
Reviewed-by: darcy

     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.TypeTags.*;
    42 /** This pass translates Generic Java to conventional Java.
    43  *
    44  *  <p><b>This is NOT part of any supported API.
    45  *  If you write code that depends on this, you do so at your own risk.
    46  *  This code and its internal interfaces are subject to change or
    47  *  deletion without notice.</b>
    48  */
    49 public class TransTypes extends TreeTranslator {
    50     /** The context key for the TransTypes phase. */
    51     protected static final Context.Key<TransTypes> transTypesKey =
    52         new Context.Key<TransTypes>();
    54     /** Get the instance for this context. */
    55     public static TransTypes instance(Context context) {
    56         TransTypes instance = context.get(transTypesKey);
    57         if (instance == null)
    58             instance = new TransTypes(context);
    59         return instance;
    60     }
    62     private Names names;
    63     private Log log;
    64     private Symtab syms;
    65     private TreeMaker make;
    66     private Enter enter;
    67     private boolean allowEnums;
    68     private Types types;
    69     private final Resolve resolve;
    71     /**
    72      * Flag to indicate whether or not to generate bridge methods.
    73      * For pre-Tiger source there is no need for bridge methods, so it
    74      * can be skipped to get better performance for -source 1.4 etc.
    75      */
    76     private final boolean addBridges;
    78     protected TransTypes(Context context) {
    79         context.put(transTypesKey, this);
    80         names = Names.instance(context);
    81         log = Log.instance(context);
    82         syms = Symtab.instance(context);
    83         enter = Enter.instance(context);
    84         overridden = new HashMap<MethodSymbol,MethodSymbol>();
    85         Source source = Source.instance(context);
    86         allowEnums = source.allowEnums();
    87         addBridges = source.addBridges();
    88         types = Types.instance(context);
    89         make = TreeMaker.instance(context);
    90         resolve = Resolve.instance(context);
    91     }
    93     /** A hashtable mapping bridge methods to the methods they override after
    94      *  type erasure.
    95      */
    96     Map<MethodSymbol,MethodSymbol> overridden;
    98     /** Construct an attributed tree for a cast of expression to target type,
    99      *  unless it already has precisely that type.
   100      *  @param tree    The expression tree.
   101      *  @param target  The target type.
   102      */
   103     JCExpression cast(JCExpression tree, Type target) {
   104         int oldpos = make.pos;
   105         make.at(tree.pos);
   106         if (!types.isSameType(tree.type, target)) {
   107             if (!resolve.isAccessible(env, target.tsym))
   108                 resolve.logAccessErrorInternal(env, tree, target);
   109             tree = make.TypeCast(make.Type(target), tree).setType(target);
   110         }
   111         make.pos = oldpos;
   112         return tree;
   113     }
   115     /** Construct an attributed tree to coerce an expression to some erased
   116      *  target type, unless the expression is already assignable to that type.
   117      *  If target type is a constant type, use its base type instead.
   118      *  @param tree    The expression tree.
   119      *  @param target  The target type.
   120      */
   121     JCExpression coerce(JCExpression tree, Type target) {
   122         Type btarget = target.baseType();
   123         if (tree.type.isPrimitive() == target.isPrimitive()) {
   124             return types.isAssignable(tree.type, btarget, Warner.noWarnings)
   125                 ? tree
   126                 : cast(tree, btarget);
   127         }
   128         return tree;
   129     }
   131     /** Given an erased reference type, assume this type as the tree's type.
   132      *  Then, coerce to some given target type unless target type is null.
   133      *  This operation is used in situations like the following:
   134      *
   135      *  class Cell<A> { A value; }
   136      *  ...
   137      *  Cell<Integer> cell;
   138      *  Integer x = cell.value;
   139      *
   140      *  Since the erasure of Cell.value is Object, but the type
   141      *  of cell.value in the assignment is Integer, we need to
   142      *  adjust the original type of cell.value to Object, and insert
   143      *  a cast to Integer. That is, the last assignment becomes:
   144      *
   145      *  Integer x = (Integer)cell.value;
   146      *
   147      *  @param tree       The expression tree whose type might need adjustment.
   148      *  @param erasedType The expression's type after erasure.
   149      *  @param target     The target type, which is usually the erasure of the
   150      *                    expression's original type.
   151      */
   152     JCExpression retype(JCExpression tree, Type erasedType, Type target) {
   153 //      System.err.println("retype " + tree + " to " + erasedType);//DEBUG
   154         if (erasedType.tag > lastBaseTag) {
   155             if (target != null && target.isPrimitive())
   156                 target = erasure(tree.type);
   157             tree.type = erasedType;
   158             if (target != null) return coerce(tree, target);
   159         }
   160         return tree;
   161     }
   163     /** Translate method argument list, casting each argument
   164      *  to its corresponding type in a list of target types.
   165      *  @param _args            The method argument list.
   166      *  @param parameters       The list of target types.
   167      *  @param varargsElement   The erasure of the varargs element type,
   168      *  or null if translating a non-varargs invocation
   169      */
   170     <T extends JCTree> List<T> translateArgs(List<T> _args,
   171                                            List<Type> parameters,
   172                                            Type varargsElement) {
   173         if (parameters.isEmpty()) return _args;
   174         List<T> args = _args;
   175         while (parameters.tail.nonEmpty()) {
   176             args.head = translate(args.head, parameters.head);
   177             args = args.tail;
   178             parameters = parameters.tail;
   179         }
   180         Type parameter = parameters.head;
   181         Assert.check(varargsElement != null || args.length() == 1);
   182         if (varargsElement != null) {
   183             while (args.nonEmpty()) {
   184                 args.head = translate(args.head, varargsElement);
   185                 args = args.tail;
   186             }
   187         } else {
   188             args.head = translate(args.head, parameter);
   189         }
   190         return _args;
   191     }
   193     /** Add a bridge definition and enter corresponding method symbol in
   194      *  local scope of origin.
   195      *
   196      *  @param pos     The source code position to be used for the definition.
   197      *  @param meth    The method for which a bridge needs to be added
   198      *  @param impl    That method's implementation (possibly the method itself)
   199      *  @param origin  The class to which the bridge will be added
   200      *  @param hypothetical
   201      *                 True if the bridge method is not strictly necessary in the
   202      *                 binary, but is represented in the symbol table to detect
   203      *                 erasure clashes.
   204      *  @param bridges The list buffer to which the bridge will be added
   205      */
   206     void addBridge(DiagnosticPosition pos,
   207                    MethodSymbol meth,
   208                    MethodSymbol impl,
   209                    ClassSymbol origin,
   210                    boolean hypothetical,
   211                    ListBuffer<JCTree> bridges) {
   212         make.at(pos);
   213         Type origType = types.memberType(origin.type, meth);
   214         Type origErasure = erasure(origType);
   216         // Create a bridge method symbol and a bridge definition without a body.
   217         Type bridgeType = meth.erasure(types);
   218         long flags = impl.flags() & AccessFlags | SYNTHETIC | BRIDGE;
   219         if (hypothetical) flags |= HYPOTHETICAL;
   220         MethodSymbol bridge = new MethodSymbol(flags,
   221                                                meth.name,
   222                                                bridgeType,
   223                                                origin);
   224         if (!hypothetical) {
   225             JCMethodDecl md = make.MethodDef(bridge, null);
   227             // The bridge calls this.impl(..), if we have an implementation
   228             // in the current class, super.impl(...) otherwise.
   229             JCExpression receiver = (impl.owner == origin)
   230                 ? make.This(origin.erasure(types))
   231                 : make.Super(types.supertype(origin.type).tsym.erasure(types), origin);
   233             // The type returned from the original method.
   234             Type calltype = erasure(impl.type.getReturnType());
   236             // Construct a call of  this.impl(params), or super.impl(params),
   237             // casting params and possibly results as needed.
   238             JCExpression call =
   239                 make.Apply(
   240                            null,
   241                            make.Select(receiver, impl).setType(calltype),
   242                            translateArgs(make.Idents(md.params), origErasure.getParameterTypes(), null))
   243                 .setType(calltype);
   244             JCStatement stat = (origErasure.getReturnType().tag == VOID)
   245                 ? make.Exec(call)
   246                 : make.Return(coerce(call, bridgeType.getReturnType()));
   247             md.body = make.Block(0, List.of(stat));
   249             // Add bridge to `bridges' buffer
   250             bridges.append(md);
   251         }
   253         // Add bridge to scope of enclosing class and `overridden' table.
   254         origin.members().enter(bridge);
   255         overridden.put(bridge, meth);
   256     }
   258     /** Add bridge if given symbol is a non-private, non-static member
   259      *  of the given class, which is either defined in the class or non-final
   260      *  inherited, and one of the two following conditions holds:
   261      *  1. The method's type changes in the given class, as compared to the
   262      *     class where the symbol was defined, (in this case
   263      *     we have extended a parameterized class with non-trivial parameters).
   264      *  2. The method has an implementation with a different erased return type.
   265      *     (in this case we have used co-variant returns).
   266      *  If a bridge already exists in some other class, no new bridge is added.
   267      *  Instead, it is checked that the bridge symbol overrides the method symbol.
   268      *  (Spec ???).
   269      *  todo: what about bridges for privates???
   270      *
   271      *  @param pos     The source code position to be used for the definition.
   272      *  @param sym     The symbol for which a bridge might have to be added.
   273      *  @param origin  The class in which the bridge would go.
   274      *  @param bridges The list buffer to which the bridge would be added.
   275      */
   276     void addBridgeIfNeeded(DiagnosticPosition pos,
   277                            Symbol sym,
   278                            ClassSymbol origin,
   279                            ListBuffer<JCTree> bridges) {
   280         if (sym.kind == MTH &&
   281             sym.name != names.init &&
   282             (sym.flags() & (PRIVATE | STATIC)) == 0 &&
   283             (sym.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC &&
   284             sym.isMemberOf(origin, types))
   285         {
   286             MethodSymbol meth = (MethodSymbol)sym;
   287             MethodSymbol bridge = meth.binaryImplementation(origin, types);
   288             MethodSymbol impl = meth.implementation(origin, types, true, overrideBridgeFilter);
   289             if (bridge == null ||
   290                 bridge == meth ||
   291                 (impl != null && !bridge.owner.isSubClass(impl.owner, types))) {
   292                 // No bridge was added yet.
   293                 if (impl != null && isBridgeNeeded(meth, impl, origin.type)) {
   294                     addBridge(pos, meth, impl, origin, bridge==impl, bridges);
   295                 } else if (impl == meth
   296                            && impl.owner != origin
   297                            && (impl.flags() & FINAL) == 0
   298                            && (meth.flags() & (ABSTRACT|PUBLIC)) == PUBLIC
   299                            && (origin.flags() & PUBLIC) > (impl.owner.flags() & PUBLIC)) {
   300                     // this is to work around a horrible but permanent
   301                     // reflection design error.
   302                     addBridge(pos, meth, impl, origin, false, bridges);
   303                 }
   304             } else if ((bridge.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) == SYNTHETIC) {
   305                 MethodSymbol other = overridden.get(bridge);
   306                 if (other != null && other != meth) {
   307                     if (impl == null || !impl.overrides(other, origin, types, true)) {
   308                         // Bridge for other symbol pair was added
   309                         log.error(pos, "name.clash.same.erasure.no.override",
   310                                   other, other.location(origin.type, types),
   311                                   meth,  meth.location(origin.type, types));
   312                     }
   313                 }
   314             } else if (!bridge.overrides(meth, origin, types, true)) {
   315                 // Accidental binary override without source override.
   316                 if (bridge.owner == origin ||
   317                     types.asSuper(bridge.owner.type, meth.owner) == null)
   318                     // Don't diagnose the problem if it would already
   319                     // have been reported in the superclass
   320                     log.error(pos, "name.clash.same.erasure.no.override",
   321                               bridge, bridge.location(origin.type, types),
   322                               meth,  meth.location(origin.type, types));
   323             }
   324         }
   325     }
   326     // where
   327         Filter<Symbol> overrideBridgeFilter = new Filter<Symbol>() {
   328             public boolean accepts(Symbol s) {
   329                 return (s.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC;
   330             }
   331         };
   332         /**
   333          * @param method The symbol for which a bridge might have to be added
   334          * @param impl The implementation of method
   335          * @param dest The type in which the bridge would go
   336          */
   337         private boolean isBridgeNeeded(MethodSymbol method,
   338                                        MethodSymbol impl,
   339                                        Type dest) {
   340             if (impl != method) {
   341                 // If either method or impl have different erasures as
   342                 // members of dest, a bridge is needed.
   343                 Type method_erasure = method.erasure(types);
   344                 if (!isSameMemberWhenErased(dest, method, method_erasure))
   345                     return true;
   346                 Type impl_erasure = impl.erasure(types);
   347                 if (!isSameMemberWhenErased(dest, impl, impl_erasure))
   348                     return true;
   350                 // If the erasure of the return type is different, a
   351                 // bridge is needed.
   352                 return !types.isSameType(impl_erasure.getReturnType(),
   353                                          method_erasure.getReturnType());
   354             } else {
   355                // method and impl are the same...
   356                 if ((method.flags() & ABSTRACT) != 0) {
   357                     // ...and abstract so a bridge is not needed.
   358                     // Concrete subclasses will bridge as needed.
   359                     return false;
   360                 }
   362                 // The erasure of the return type is always the same
   363                 // for the same symbol.  Reducing the three tests in
   364                 // the other branch to just one:
   365                 return !isSameMemberWhenErased(dest, method, method.erasure(types));
   366             }
   367         }
   368         /**
   369          * Lookup the method as a member of the type.  Compare the
   370          * erasures.
   371          * @param type the class where to look for the method
   372          * @param method the method to look for in class
   373          * @param erasure the erasure of method
   374          */
   375         private boolean isSameMemberWhenErased(Type type,
   376                                                MethodSymbol method,
   377                                                Type erasure) {
   378             return types.isSameType(erasure(types.memberType(type, method)),
   379                                     erasure);
   380         }
   382     void addBridges(DiagnosticPosition pos,
   383                     TypeSymbol i,
   384                     ClassSymbol origin,
   385                     ListBuffer<JCTree> bridges) {
   386         for (Scope.Entry e = i.members().elems; e != null; e = e.sibling)
   387             addBridgeIfNeeded(pos, e.sym, origin, bridges);
   388         for (List<Type> l = types.interfaces(i.type); l.nonEmpty(); l = l.tail)
   389             addBridges(pos, l.head.tsym, origin, bridges);
   390     }
   392     /** Add all necessary bridges to some class appending them to list buffer.
   393      *  @param pos     The source code position to be used for the bridges.
   394      *  @param origin  The class in which the bridges go.
   395      *  @param bridges The list buffer to which the bridges are added.
   396      */
   397     void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
   398         Type st = types.supertype(origin.type);
   399         while (st.tag == CLASS) {
   400 //          if (isSpecialization(st))
   401             addBridges(pos, st.tsym, origin, bridges);
   402             st = types.supertype(st);
   403         }
   404         for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
   405 //          if (isSpecialization(l.head))
   406             addBridges(pos, l.head.tsym, origin, bridges);
   407     }
   409 /* ************************************************************************
   410  * Visitor methods
   411  *************************************************************************/
   413     /** Visitor argument: proto-type.
   414      */
   415     private Type pt;
   417     /** Visitor method: perform a type translation on tree.
   418      */
   419     public <T extends JCTree> T translate(T tree, Type pt) {
   420         Type prevPt = this.pt;
   421         try {
   422             this.pt = pt;
   423             return translate(tree);
   424         } finally {
   425             this.pt = prevPt;
   426         }
   427     }
   429     /** Visitor method: perform a type translation on list of trees.
   430      */
   431     public <T extends JCTree> List<T> translate(List<T> trees, Type pt) {
   432         Type prevPt = this.pt;
   433         List<T> res;
   434         try {
   435             this.pt = pt;
   436             res = translate(trees);
   437         } finally {
   438             this.pt = prevPt;
   439         }
   440         return res;
   441     }
   443     public void visitClassDef(JCClassDecl tree) {
   444         translateClass(tree.sym);
   445         result = tree;
   446     }
   448     JCMethodDecl currentMethod = null;
   449     public void visitMethodDef(JCMethodDecl tree) {
   450         JCMethodDecl previousMethod = currentMethod;
   451         try {
   452             currentMethod = tree;
   453             tree.restype = translate(tree.restype, null);
   454             tree.typarams = List.nil();
   455             tree.params = translateVarDefs(tree.params);
   456             tree.thrown = translate(tree.thrown, null);
   457             tree.body = translate(tree.body, tree.sym.erasure(types).getReturnType());
   458             tree.type = erasure(tree.type);
   459             result = tree;
   460         } finally {
   461             currentMethod = previousMethod;
   462         }
   464         // Check that we do not introduce a name clash by erasing types.
   465         for (Scope.Entry e = tree.sym.owner.members().lookup(tree.name);
   466              e.sym != null;
   467              e = e.next()) {
   468             if (e.sym != tree.sym &&
   469                 types.isSameType(erasure(e.sym.type), tree.type)) {
   470                 log.error(tree.pos(),
   471                           "name.clash.same.erasure", tree.sym,
   472                           e.sym);
   473                 return;
   474             }
   475         }
   476     }
   478     public void visitVarDef(JCVariableDecl tree) {
   479         tree.vartype = translate(tree.vartype, null);
   480         tree.init = translate(tree.init, tree.sym.erasure(types));
   481         tree.type = erasure(tree.type);
   482         result = tree;
   483     }
   485     public void visitDoLoop(JCDoWhileLoop tree) {
   486         tree.body = translate(tree.body);
   487         tree.cond = translate(tree.cond, syms.booleanType);
   488         result = tree;
   489     }
   491     public void visitWhileLoop(JCWhileLoop tree) {
   492         tree.cond = translate(tree.cond, syms.booleanType);
   493         tree.body = translate(tree.body);
   494         result = tree;
   495     }
   497     public void visitForLoop(JCForLoop tree) {
   498         tree.init = translate(tree.init, null);
   499         if (tree.cond != null)
   500             tree.cond = translate(tree.cond, syms.booleanType);
   501         tree.step = translate(tree.step, null);
   502         tree.body = translate(tree.body);
   503         result = tree;
   504     }
   506     public void visitForeachLoop(JCEnhancedForLoop tree) {
   507         tree.var = translate(tree.var, null);
   508         Type iterableType = tree.expr.type;
   509         tree.expr = translate(tree.expr, erasure(tree.expr.type));
   510         if (types.elemtype(tree.expr.type) == null)
   511             tree.expr.type = iterableType; // preserve type for Lower
   512         tree.body = translate(tree.body);
   513         result = tree;
   514     }
   516     public void visitSwitch(JCSwitch tree) {
   517         Type selsuper = types.supertype(tree.selector.type);
   518         boolean enumSwitch = selsuper != null &&
   519             selsuper.tsym == syms.enumSym;
   520         Type target = enumSwitch ? erasure(tree.selector.type) : syms.intType;
   521         tree.selector = translate(tree.selector, target);
   522         tree.cases = translateCases(tree.cases);
   523         result = tree;
   524     }
   526     public void visitCase(JCCase tree) {
   527         tree.pat = translate(tree.pat, null);
   528         tree.stats = translate(tree.stats);
   529         result = tree;
   530     }
   532     public void visitSynchronized(JCSynchronized tree) {
   533         tree.lock = translate(tree.lock, erasure(tree.lock.type));
   534         tree.body = translate(tree.body);
   535         result = tree;
   536     }
   538     public void visitTry(JCTry tree) {
   539         tree.resources = translate(tree.resources, syms.autoCloseableType);
   540         tree.body = translate(tree.body);
   541         tree.catchers = translateCatchers(tree.catchers);
   542         tree.finalizer = translate(tree.finalizer);
   543         result = tree;
   544     }
   546     public void visitConditional(JCConditional tree) {
   547         tree.cond = translate(tree.cond, syms.booleanType);
   548         tree.truepart = translate(tree.truepart, erasure(tree.type));
   549         tree.falsepart = translate(tree.falsepart, erasure(tree.type));
   550         tree.type = erasure(tree.type);
   551         result = retype(tree, tree.type, pt);
   552     }
   554    public void visitIf(JCIf tree) {
   555         tree.cond = translate(tree.cond, syms.booleanType);
   556         tree.thenpart = translate(tree.thenpart);
   557         tree.elsepart = translate(tree.elsepart);
   558         result = tree;
   559     }
   561     public void visitExec(JCExpressionStatement tree) {
   562         tree.expr = translate(tree.expr, null);
   563         result = tree;
   564     }
   566     public void visitReturn(JCReturn tree) {
   567         tree.expr = translate(tree.expr, currentMethod.sym.erasure(types).getReturnType());
   568         result = tree;
   569     }
   571     public void visitThrow(JCThrow tree) {
   572         tree.expr = translate(tree.expr, erasure(tree.expr.type));
   573         result = tree;
   574     }
   576     public void visitAssert(JCAssert tree) {
   577         tree.cond = translate(tree.cond, syms.booleanType);
   578         if (tree.detail != null)
   579             tree.detail = translate(tree.detail, erasure(tree.detail.type));
   580         result = tree;
   581     }
   583     public void visitApply(JCMethodInvocation tree) {
   584         tree.meth = translate(tree.meth, null);
   585         Symbol meth = TreeInfo.symbol(tree.meth);
   586         Type mt = meth.erasure(types);
   587         List<Type> argtypes = mt.getParameterTypes();
   588         if (allowEnums &&
   589             meth.name==names.init &&
   590             meth.owner == syms.enumSym)
   591             argtypes = argtypes.tail.tail;
   592         if (tree.varargsElement != null)
   593             tree.varargsElement = types.erasure(tree.varargsElement);
   594         else
   595             Assert.check(tree.args.length() == argtypes.length());
   596         tree.args = translateArgs(tree.args, argtypes, tree.varargsElement);
   598         // Insert casts of method invocation results as needed.
   599         result = retype(tree, mt.getReturnType(), pt);
   600     }
   602     public void visitNewClass(JCNewClass tree) {
   603         if (tree.encl != null)
   604             tree.encl = translate(tree.encl, erasure(tree.encl.type));
   605         tree.clazz = translate(tree.clazz, null);
   606         if (tree.varargsElement != null)
   607             tree.varargsElement = types.erasure(tree.varargsElement);
   608         tree.args = translateArgs(
   609             tree.args, tree.constructor.erasure(types).getParameterTypes(), tree.varargsElement);
   610         tree.def = translate(tree.def, null);
   611         tree.type = erasure(tree.type);
   612         result = tree;
   613     }
   615     public void visitNewArray(JCNewArray tree) {
   616         tree.elemtype = translate(tree.elemtype, null);
   617         translate(tree.dims, syms.intType);
   618         if (tree.type != null) {
   619             tree.elems = translate(tree.elems, erasure(types.elemtype(tree.type)));
   620             tree.type = erasure(tree.type);
   621         } else {
   622             tree.elems = translate(tree.elems, null);
   623         }
   625         result = tree;
   626     }
   628     @Override
   629     public void visitLambda(JCLambda tree) {
   630         Assert.error("Translation of lambda expression not supported yet");
   631     }
   633     @Override
   634     public void visitReference(JCMemberReference tree) {
   635         Assert.error("Translation of method reference not supported yet");
   636     }
   638     public void visitParens(JCParens tree) {
   639         tree.expr = translate(tree.expr, pt);
   640         tree.type = erasure(tree.type);
   641         result = tree;
   642     }
   644     public void visitAssign(JCAssign tree) {
   645         tree.lhs = translate(tree.lhs, null);
   646         tree.rhs = translate(tree.rhs, erasure(tree.lhs.type));
   647         tree.type = erasure(tree.type);
   648         result = tree;
   649     }
   651     public void visitAssignop(JCAssignOp tree) {
   652         tree.lhs = translate(tree.lhs, null);
   653         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
   654         tree.type = erasure(tree.type);
   655         result = tree;
   656     }
   658     public void visitUnary(JCUnary tree) {
   659         tree.arg = translate(tree.arg, tree.operator.type.getParameterTypes().head);
   660         result = tree;
   661     }
   663     public void visitBinary(JCBinary tree) {
   664         tree.lhs = translate(tree.lhs, tree.operator.type.getParameterTypes().head);
   665         tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head);
   666         result = tree;
   667     }
   669     public void visitTypeCast(JCTypeCast tree) {
   670         tree.clazz = translate(tree.clazz, null);
   671         tree.type = erasure(tree.type);
   672         tree.expr = translate(tree.expr, tree.type);
   673         result = tree;
   674     }
   676     public void visitTypeTest(JCInstanceOf tree) {
   677         tree.expr = translate(tree.expr, null);
   678         tree.clazz = translate(tree.clazz, null);
   679         result = tree;
   680     }
   682     public void visitIndexed(JCArrayAccess tree) {
   683         tree.indexed = translate(tree.indexed, erasure(tree.indexed.type));
   684         tree.index = translate(tree.index, syms.intType);
   686         // Insert casts of indexed expressions as needed.
   687         result = retype(tree, types.elemtype(tree.indexed.type), pt);
   688     }
   690     // There ought to be nothing to rewrite here;
   691     // we don't generate code.
   692     public void visitAnnotation(JCAnnotation tree) {
   693         result = tree;
   694     }
   696     public void visitIdent(JCIdent tree) {
   697         Type et = tree.sym.erasure(types);
   699         // Map type variables to their bounds.
   700         if (tree.sym.kind == TYP && tree.sym.type.tag == TYPEVAR) {
   701             result = make.at(tree.pos).Type(et);
   702         } else
   703         // Map constants expressions to themselves.
   704         if (tree.type.constValue() != null) {
   705             result = tree;
   706         }
   707         // Insert casts of variable uses as needed.
   708         else if (tree.sym.kind == VAR) {
   709             result = retype(tree, et, pt);
   710         }
   711         else {
   712             tree.type = erasure(tree.type);
   713             result = tree;
   714         }
   715     }
   717     public void visitSelect(JCFieldAccess tree) {
   718         Type t = tree.selected.type;
   719         while (t.tag == TYPEVAR)
   720             t = t.getUpperBound();
   721         if (t.isCompound()) {
   722             if ((tree.sym.flags() & IPROXY) != 0) {
   723                 tree.sym = ((MethodSymbol)tree.sym).
   724                     implemented((TypeSymbol)tree.sym.owner, types);
   725             }
   726             tree.selected = coerce(
   727                 translate(tree.selected, erasure(tree.selected.type)),
   728                 erasure(tree.sym.owner.type));
   729         } else
   730             tree.selected = translate(tree.selected, erasure(t));
   732         // Map constants expressions to themselves.
   733         if (tree.type.constValue() != null) {
   734             result = tree;
   735         }
   736         // Insert casts of variable uses as needed.
   737         else if (tree.sym.kind == VAR) {
   738             result = retype(tree, tree.sym.erasure(types), pt);
   739         }
   740         else {
   741             tree.type = erasure(tree.type);
   742             result = tree;
   743         }
   744     }
   746     public void visitTypeArray(JCArrayTypeTree tree) {
   747         tree.elemtype = translate(tree.elemtype, null);
   748         tree.type = erasure(tree.type);
   749         result = tree;
   750     }
   752     /** Visitor method for parameterized types.
   753      */
   754     public void visitTypeApply(JCTypeApply tree) {
   755         JCTree clazz = translate(tree.clazz, null);
   756         result = clazz;
   757     }
   759 /**************************************************************************
   760  * utility methods
   761  *************************************************************************/
   763     private Type erasure(Type t) {
   764         return types.erasure(t);
   765     }
   767     private boolean boundsRestricted(ClassSymbol c) {
   768         Type st = types.supertype(c.type);
   769         if (st.isParameterized()) {
   770             List<Type> actuals = st.allparams();
   771             List<Type> formals = st.tsym.type.allparams();
   772             while (!actuals.isEmpty() && !formals.isEmpty()) {
   773                 Type actual = actuals.head;
   774                 Type formal = formals.head;
   776                 if (!types.isSameType(types.erasure(actual),
   777                         types.erasure(formal)))
   778                     return true;
   780                 actuals = actuals.tail;
   781                 formals = formals.tail;
   782             }
   783         }
   784         return false;
   785     }
   787     private List<JCTree> addOverrideBridgesIfNeeded(DiagnosticPosition pos,
   788                                     final ClassSymbol c) {
   789         ListBuffer<JCTree> buf = ListBuffer.lb();
   790         if (c.isInterface() || !boundsRestricted(c))
   791             return buf.toList();
   792         Type t = types.supertype(c.type);
   793             Scope s = t.tsym.members();
   794             if (s.elems != null) {
   795                 for (Symbol sym : s.getElements(new NeedsOverridBridgeFilter(c))) {
   797                     MethodSymbol m = (MethodSymbol)sym;
   798                     MethodSymbol member = (MethodSymbol)m.asMemberOf(c.type, types);
   799                     MethodSymbol impl = m.implementation(c, types, false);
   801                     if ((impl == null || impl.owner != c) &&
   802                             !types.isSameType(member.erasure(types), m.erasure(types))) {
   803                         addOverrideBridges(pos, m, member, c, buf);
   804                     }
   805                 }
   806             }
   807         return buf.toList();
   808     }
   809     // where
   810         class NeedsOverridBridgeFilter implements Filter<Symbol> {
   812             ClassSymbol c;
   814             NeedsOverridBridgeFilter(ClassSymbol c) {
   815                 this.c = c;
   816             }
   817             public boolean accepts(Symbol s) {
   818                 return s.kind == MTH &&
   819                             !s.isConstructor() &&
   820                             s.isInheritedIn(c, types) &&
   821                             (s.flags() & FINAL) == 0 &&
   822                             (s.flags() & (SYNTHETIC | OVERRIDE_BRIDGE)) != SYNTHETIC;
   823             }
   824         }
   826     private void addOverrideBridges(DiagnosticPosition pos,
   827                                     MethodSymbol impl,
   828                                     MethodSymbol member,
   829                                     ClassSymbol c,
   830                                     ListBuffer<JCTree> bridges) {
   831         Type implErasure = impl.erasure(types);
   832         long flags = (impl.flags() & AccessFlags) | SYNTHETIC | BRIDGE | OVERRIDE_BRIDGE;
   833         member = new MethodSymbol(flags, member.name, member.type, c);
   834         JCMethodDecl md = make.MethodDef(member, null);
   835         JCExpression receiver = make.Super(types.supertype(c.type).tsym.erasure(types), c);
   836         Type calltype = erasure(impl.type.getReturnType());
   837         JCExpression call =
   838             make.Apply(null,
   839                        make.Select(receiver, impl).setType(calltype),
   840                        translateArgs(make.Idents(md.params),
   841                                      implErasure.getParameterTypes(), null))
   842             .setType(calltype);
   843         JCStatement stat = (member.getReturnType().tag == VOID)
   844             ? make.Exec(call)
   845             : make.Return(coerce(call, member.erasure(types).getReturnType()));
   846         md.body = make.Block(0, List.of(stat));
   847         c.members().enter(member);
   848         bridges.append(md);
   849     }
   851 /**************************************************************************
   852  * main method
   853  *************************************************************************/
   855     private Env<AttrContext> env;
   857     void translateClass(ClassSymbol c) {
   858         Type st = types.supertype(c.type);
   860         // process superclass before derived
   861         if (st.tag == CLASS)
   862             translateClass((ClassSymbol)st.tsym);
   864         Env<AttrContext> myEnv = enter.typeEnvs.remove(c);
   865         if (myEnv == null)
   866             return;
   867         Env<AttrContext> oldEnv = env;
   868         try {
   869             env = myEnv;
   870             // class has not been translated yet
   872             TreeMaker savedMake = make;
   873             Type savedPt = pt;
   874             make = make.forToplevel(env.toplevel);
   875             pt = null;
   876             try {
   877                 JCClassDecl tree = (JCClassDecl) env.tree;
   878                 tree.typarams = List.nil();
   879                 super.visitClassDef(tree);
   880                 make.at(tree.pos);
   881                 if (addBridges) {
   882                     ListBuffer<JCTree> bridges = new ListBuffer<JCTree>();
   883                     if (false) //see CR: 6996415
   884                         bridges.appendList(addOverrideBridgesIfNeeded(tree, c));
   885                     if ((tree.sym.flags() & INTERFACE) == 0)
   886                         addBridges(tree.pos(), tree.sym, bridges);
   887                     tree.defs = bridges.toList().prependList(tree.defs);
   888                 }
   889                 tree.type = erasure(tree.type);
   890             } finally {
   891                 make = savedMake;
   892                 pt = savedPt;
   893             }
   894         } finally {
   895             env = oldEnv;
   896         }
   897     }
   899     /** Translate a toplevel class definition.
   900      *  @param cdef    The definition to be translated.
   901      */
   902     public JCTree translateTopLevelClass(JCTree cdef, TreeMaker make) {
   903         // note that this method does NOT support recursion.
   904         this.make = make;
   905         pt = null;
   906         return translate(cdef, null);
   907     }
   908 }

mercurial