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

Tue, 09 Oct 2012 19:31:58 -0700

author
jjg
date
Tue, 09 Oct 2012 19:31:58 -0700
changeset 1358
fc123bdeddb8
parent 1357
c75be5bc5283
child 1374
c002fdee76fd
permissions
-rw-r--r--

8000208: fix langtools javadoc comment issues
Reviewed-by: bpatel, mcimadamore

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

mercurial