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

Wed, 19 Jun 2013 11:48:05 +0100

author
chegar
date
Wed, 19 Jun 2013 11:48:05 +0100
changeset 1843
be62183f938a
parent 1824
455be95bd1b5
child 1882
39ec5d8a691b
permissions
-rw-r--r--

8017045: anti-delta fix for 8013789
Reviewed-by: alanb

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

mercurial