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

Thu, 25 Oct 2012 11:09:36 -0700

author
jjg
date
Thu, 25 Oct 2012 11:09:36 -0700
changeset 1374
c002fdee76fd
parent 1358
fc123bdeddb8
child 1380
a65971893c50
permissions
-rw-r--r--

7200915: convert TypeTags from a series of small ints to an enum
Reviewed-by: jjg, mcimadamore
Contributed-by: vicente.romero@oracle.com

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

mercurial