rt/emul/compact/src/main/java/java/lang/invoke/LambdaMetafactory.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 14 Sep 2014 19:27:44 +0200
changeset 1692 2f800fdc371e
permissions -rw-r--r--
Adding necessary fake classes to allow Javac to compile lamda expressions against our emulation library.
     1 /*
     2  * Copyright (c) 2012, 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  */
    25 
    26 package java.lang.invoke;
    27 
    28 import java.io.Serializable;
    29 import java.util.Arrays;
    30 
    31 /**
    32  * <p>Methods to facilitate the creation of simple "function objects" that
    33  * implement one or more interfaces by delegation to a provided {@link MethodHandle},
    34  * possibly after type adaptation and partial evaluation of arguments.  These
    35  * methods are typically used as <em>bootstrap methods</em> for {@code invokedynamic}
    36  * call sites, to support the <em>lambda expression</em> and <em>method
    37  * reference expression</em> features of the Java Programming Language.
    38  *
    39  * <p>Indirect access to the behavior specified by the provided {@code MethodHandle}
    40  * proceeds in order through three phases:
    41  * <ul>
    42  *     <li><em>Linkage</em> occurs when the methods in this class are invoked.
    43  *     They take as arguments an interface to be implemented (typically a
    44  *     <em>functional interface</em>, one with a single abstract method), a
    45  *     name and signature of a method from that interface to be implemented, a
    46  *     method handle describing the desired implementation behavior
    47  *     for that method, and possibly other additional metadata, and produce a
    48  *     {@link CallSite} whose target can be used to create suitable function
    49  *     objects.  Linkage may involve dynamically loading a new class that
    50  *     implements the target interface. The {@code CallSite} can be considered a
    51  *     "factory" for function objects and so these linkage methods are referred
    52  *     to as "metafactories".</li>
    53  *
    54  *     <li><em>Capture</em> occurs when the {@code CallSite}'s target is
    55  *     invoked, typically through an {@code invokedynamic} call site,
    56  *     producing a function object.  This may occur many times for
    57  *     a single factory {@code CallSite}.  Capture may involve allocation of a
    58  *     new function object, or may return an existing function object.  The
    59  *     behavior {@code MethodHandle} may have additional parameters beyond those
    60  *     of the specified interface method; these are referred to as <em>captured
    61  *     parameters</em>, which must be provided as arguments to the
    62  *     {@code CallSite} target, and which may be early-bound to the behavior
    63  *     {@code MethodHandle}.  The number of captured parameters and their types
    64  *     are determined during linkage.</li>
    65  *
    66  *     <li><em>Invocation</em> occurs when an implemented interface method
    67  *     is invoked on a function object.  This may occur many times for a single
    68  *     function object.  The method referenced by the behavior {@code MethodHandle}
    69  *     is invoked with the captured arguments and any additional arguments
    70  *     provided on invocation, as if by {@link MethodHandle#invoke(Object...)}.</li>
    71  * </ul>
    72  *
    73  * <p>It is sometimes useful to restrict the set of inputs or results permitted
    74  * at invocation.  For example, when the generic interface {@code Predicate<T>}
    75  * is parameterized as {@code Predicate<String>}, the input must be a
    76  * {@code String}, even though the method to implement allows any {@code Object}.
    77  * At linkage time, an additional {@link MethodType} parameter describes the
    78  * "instantiated" method type; on invocation, the arguments and eventual result
    79  * are checked against this {@code MethodType}.
    80  *
    81  * <p>This class provides two forms of linkage methods: a standard version
    82  * ({@link #metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)})
    83  * using an optimized protocol, and an alternate version
    84  * {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}).
    85  * The alternate version is a generalization of the standard version, providing
    86  * additional control over the behavior of the generated function objects via
    87  * flags and additional arguments.  The alternate version adds the ability to
    88  * manage the following attributes of function objects:
    89  *
    90  * <ul>
    91  *     <li><em>Bridging.</em>  It is sometimes useful to implement multiple
    92  *     variations of the method signature, involving argument or return type
    93  *     adaptation.  This occurs when multiple distinct VM signatures for a method
    94  *     are logically considered to be the same method by the language.  The
    95  *     flag {@code FLAG_BRIDGES} indicates that a list of additional
    96  *     {@code MethodType}s will be provided, each of which will be implemented
    97  *     by the resulting function object.  These methods will share the same
    98  *     name and instantiated type.</li>
    99  *
   100  *     <li><em>Multiple interfaces.</em>  If needed, more than one interface
   101  *     can be implemented by the function object.  (These additional interfaces
   102  *     are typically marker interfaces with no methods.)  The flag {@code FLAG_MARKERS}
   103  *     indicates that a list of additional interfaces will be provided, each of
   104  *     which should be implemented by the resulting function object.</li>
   105  *
   106  *     <li><em>Serializability.</em>  The generated function objects do not
   107  *     generally support serialization.  If desired, {@code FLAG_SERIALIZABLE}
   108  *     can be used to indicate that the function objects should be serializable.
   109  *     Serializable function objects will use, as their serialized form,
   110  *     instances of the class {@code SerializedLambda}, which requires additional
   111  *     assistance from the capturing class (the class described by the
   112  *     {@link MethodHandles.Lookup} parameter {@code caller}); see
   113  *     {@link SerializedLambda} for details.</li>
   114  * </ul>
   115  *
   116  * <p>Assume the linkage arguments are as follows:
   117  * <ul>
   118  *      <li>{@code invokedType} (describing the {@code CallSite} signature) has
   119  *      K parameters of types (D1..Dk) and return type Rd;</li>
   120  *      <li>{@code samMethodType} (describing the implemented method type) has N
   121  *      parameters, of types (U1..Un) and return type Ru;</li>
   122  *      <li>{@code implMethod} (the {@code MethodHandle} providing the
   123  *      implementation has M parameters, of types (A1..Am) and return type Ra
   124  *      (if the method describes an instance method, the method type of this
   125  *      method handle already includes an extra first argument corresponding to
   126  *      the receiver);</li>
   127  *      <li>{@code instantiatedMethodType} (allowing restrictions on invocation)
   128  *      has N parameters, of types (T1..Tn) and return type Rt.</li>
   129  * </ul>
   130  *
   131  * <p>Then the following linkage invariants must hold:
   132  * <ul>
   133  *     <li>Rd is an interface</li>
   134  *     <li>{@code implMethod} is a <em>direct method handle</em></li>
   135  *     <li>{@code samMethodType} and {@code instantiatedMethodType} have the same
   136  *     arity N, and for i=1..N, Ti and Ui are the same type, or Ti and Ui are
   137  *     both reference types and Ti is a subtype of Ui</li>
   138  *     <li>Either Rt and Ru are the same type, or both are reference types and
   139  *     Rt is a subtype of Ru</li>
   140  *     <li>K + N = M</li>
   141  *     <li>For i=1..K, Di = Ai</li>
   142  *     <li>For i=1..N, Ti is adaptable to Aj, where j=i+k</li>
   143  *     <li>The return type Rt is void, or the return type Ra is not void and is
   144  *     adaptable to Rt</li>
   145  * </ul>
   146  *
   147  * <p>Further, at capture time, if {@code implMethod} corresponds to an instance
   148  * method, and there are any capture arguments ({@code K > 0}), then the first
   149  * capture argument (corresponding to the receiver) must be non-null.
   150  *
   151  * <p>A type Q is considered adaptable to S as follows:
   152  * <table summary="adaptable types">
   153  *     <tr><th>Q</th><th>S</th><th>Link-time checks</th><th>Invocation-time checks</th></tr>
   154  *     <tr>
   155  *         <td>Primitive</td><td>Primitive</td>
   156  *         <td>Q can be converted to S via a primitive widening conversion</td>
   157  *         <td>None</td>
   158  *     </tr>
   159  *     <tr>
   160  *         <td>Primitive</td><td>Reference</td>
   161  *         <td>S is a supertype of the Wrapper(Q)</td>
   162  *         <td>Cast from Wrapper(Q) to S</td>
   163  *     </tr>
   164  *     <tr>
   165  *         <td>Reference</td><td>Primitive</td>
   166  *         <td>for parameter types: Q is a primitive wrapper and Primitive(Q)
   167  *         can be widened to S
   168  *         <br>for return types: If Q is a primitive wrapper, check that
   169  *         Primitive(Q) can be widened to S</td>
   170  *         <td>If Q is not a primitive wrapper, cast Q to the base Wrapper(S);
   171  *         for example Number for numeric types</td>
   172  *     </tr>
   173  *     <tr>
   174  *         <td>Reference</td><td>Reference</td>
   175  *         <td>for parameter types: S is a supertype of Q
   176  *         <br>for return types: none</td>
   177  *         <td>Cast from Q to S</td>
   178  *     </tr>
   179  * </table>
   180  *
   181  * @apiNote These linkage methods are designed to support the evaluation
   182  * of <em>lambda expressions</em> and <em>method references</em> in the Java
   183  * Language.  For every lambda expressions or method reference in the source code,
   184  * there is a target type which is a functional interface.  Evaluating a lambda
   185  * expression produces an object of its target type. The recommended mechanism
   186  * for evaluating lambda expressions is to desugar the lambda body to a method,
   187  * invoke an invokedynamic call site whose static argument list describes the
   188  * sole method of the functional interface and the desugared implementation
   189  * method, and returns an object (the lambda object) that implements the target
   190  * type. (For method references, the implementation method is simply the
   191  * referenced method; no desugaring is needed.)
   192  *
   193  * <p>The argument list of the implementation method and the argument list of
   194  * the interface method(s) may differ in several ways.  The implementation
   195  * methods may have additional arguments to accommodate arguments captured by
   196  * the lambda expression; there may also be differences resulting from permitted
   197  * adaptations of arguments, such as casting, boxing, unboxing, and primitive
   198  * widening. (Varargs adaptations are not handled by the metafactories; these are
   199  * expected to be handled by the caller.)
   200  *
   201  * <p>Invokedynamic call sites have two argument lists: a static argument list
   202  * and a dynamic argument list.  The static argument list is stored in the
   203  * constant pool; the dynamic argument is pushed on the operand stack at capture
   204  * time.  The bootstrap method has access to the entire static argument list
   205  * (which in this case, includes information describing the implementation method,
   206  * the target interface, and the target interface method(s)), as well as a
   207  * method signature describing the number and static types (but not the values)
   208  * of the dynamic arguments and the static return type of the invokedynamic site.
   209  *
   210  * @implNote The implementation method is described with a method handle. In
   211  * theory, any method handle could be used. Currently supported are direct method
   212  * handles representing invocation of virtual, interface, constructor and static
   213  * methods.
   214  */
   215 public class LambdaMetafactory {
   216 
   217     /** Flag for alternate metafactories indicating the lambda object
   218      * must be serializable */
   219     public static final int FLAG_SERIALIZABLE = 1 << 0;
   220 
   221     /**
   222      * Flag for alternate metafactories indicating the lambda object implements
   223      * other marker interfaces
   224      * besides Serializable
   225      */
   226     public static final int FLAG_MARKERS = 1 << 1;
   227 
   228     /**
   229      * Flag for alternate metafactories indicating the lambda object requires
   230      * additional bridge methods
   231      */
   232     public static final int FLAG_BRIDGES = 1 << 2;
   233 
   234     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
   235     private static final MethodType[] EMPTY_MT_ARRAY = new MethodType[0];
   236 
   237     /**
   238      * Facilitates the creation of simple "function objects" that implement one
   239      * or more interfaces by delegation to a provided {@link MethodHandle},
   240      * after appropriate type adaptation and partial evaluation of arguments.
   241      * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
   242      * call sites, to support the <em>lambda expression</em> and <em>method
   243      * reference expression</em> features of the Java Programming Language.
   244      *
   245      * <p>This is the standard, streamlined metafactory; additional flexibility
   246      * is provided by {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}.
   247      * A general description of the behavior of this method is provided
   248      * {@link LambdaMetafactory above}.
   249      *
   250      * <p>When the target of the {@code CallSite} returned from this method is
   251      * invoked, the resulting function objects are instances of a class which
   252      * implements the interface named by the return type of {@code invokedType},
   253      * declares a method with the name given by {@code invokedName} and the
   254      * signature given by {@code samMethodType}.  It may also override additional
   255      * methods from {@code Object}.
   256      *
   257      * @param caller Represents a lookup context with the accessibility
   258      *               privileges of the caller.  When used with {@code invokedynamic},
   259      *               this is stacked automatically by the VM.
   260      * @param invokedName The name of the method to implement.  When used with
   261      *                    {@code invokedynamic}, this is provided by the
   262      *                    {@code NameAndType} of the {@code InvokeDynamic}
   263      *                    structure and is stacked automatically by the VM.
   264      * @param invokedType The expected signature of the {@code CallSite}.  The
   265      *                    parameter types represent the types of capture variables;
   266      *                    the return type is the interface to implement.   When
   267      *                    used with {@code invokedynamic}, this is provided by
   268      *                    the {@code NameAndType} of the {@code InvokeDynamic}
   269      *                    structure and is stacked automatically by the VM.
   270      *                    In the event that the implementation method is an
   271      *                    instance method and this signature has any parameters,
   272      *                    the first parameter in the invocation signature must
   273      *                    correspond to the receiver.
   274      * @param samMethodType Signature and return type of method to be implemented
   275      *                      by the function object.
   276      * @param implMethod A direct method handle describing the implementation
   277      *                   method which should be called (with suitable adaptation
   278      *                   of argument types, return types, and with captured
   279      *                   arguments prepended to the invocation arguments) at
   280      *                   invocation time.
   281      * @param instantiatedMethodType The signature and return type that should
   282      *                               be enforced dynamically at invocation time.
   283      *                               This may be the same as {@code samMethodType},
   284      *                               or may be a specialization of it.
   285      * @return a CallSite whose target can be used to perform capture, generating
   286      *         instances of the interface named by {@code invokedType}
   287      * @throws LambdaConversionException If any of the linkage invariants
   288      *                                   described {@link LambdaMetafactory above}
   289      *                                   are violated
   290      */
   291     public static CallSite metafactory(MethodHandles.Lookup caller,
   292                                        String invokedName,
   293                                        MethodType invokedType,
   294                                        MethodType samMethodType,
   295                                        MethodHandle implMethod,
   296                                        MethodType instantiatedMethodType)
   297      {
   298         throw new IllegalStateException();
   299     }
   300 
   301     /**
   302      * Facilitates the creation of simple "function objects" that implement one
   303      * or more interfaces by delegation to a provided {@link MethodHandle},
   304      * after appropriate type adaptation and partial evaluation of arguments.
   305      * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
   306      * call sites, to support the <em>lambda expression</em> and <em>method
   307      * reference expression</em> features of the Java Programming Language.
   308      *
   309      * <p>This is the general, more flexible metafactory; a streamlined version
   310      * is provided by {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}.
   311      * A general description of the behavior of this method is provided
   312      * {@link LambdaMetafactory above}.
   313      *
   314      * <p>The argument list for this method includes three fixed parameters,
   315      * corresponding to the parameters automatically stacked by the VM for the
   316      * bootstrap method in an {@code invokedynamic} invocation, and an {@code Object[]}
   317      * parameter that contains additional parameters.  The declared argument
   318      * list for this method is:
   319      *
   320      * <pre>{@code
   321      *  CallSite altMetafactory(MethodHandles.Lookup caller,
   322      *                          String invokedName,
   323      *                          MethodType invokedType,
   324      *                          Object... args)
   325      * }</pre>
   326      *
   327      * <p>but it behaves as if the argument list is as follows:
   328      *
   329      * <pre>{@code
   330      *  CallSite altMetafactory(MethodHandles.Lookup caller,
   331      *                          String invokedName,
   332      *                          MethodType invokedType,
   333      *                          MethodType samMethodType,
   334      *                          MethodHandle implMethod,
   335      *                          MethodType instantiatedMethodType,
   336      *                          int flags,
   337      *                          int markerInterfaceCount,  // IF flags has MARKERS set
   338      *                          Class... markerInterfaces, // IF flags has MARKERS set
   339      *                          int bridgeCount,           // IF flags has BRIDGES set
   340      *                          MethodType... bridges      // IF flags has BRIDGES set
   341      *                          )
   342      * }</pre>
   343      *
   344      * <p>Arguments that appear in the argument list for
   345      * {@link #metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)}
   346      * have the same specification as in that method.  The additional arguments
   347      * are interpreted as follows:
   348      * <ul>
   349      *     <li>{@code flags} indicates additional options; this is a bitwise
   350      *     OR of desired flags.  Defined flags are {@link #FLAG_BRIDGES},
   351      *     {@link #FLAG_MARKERS}, and {@link #FLAG_SERIALIZABLE}.</li>
   352      *     <li>{@code markerInterfaceCount} is the number of additional interfaces
   353      *     the function object should implement, and is present if and only if the
   354      *     {@code FLAG_MARKERS} flag is set.</li>
   355      *     <li>{@code markerInterfaces} is a variable-length list of additional
   356      *     interfaces to implement, whose length equals {@code markerInterfaceCount},
   357      *     and is present if and only if the {@code FLAG_MARKERS} flag is set.</li>
   358      *     <li>{@code bridgeCount} is the number of additional method signatures
   359      *     the function object should implement, and is present if and only if
   360      *     the {@code FLAG_BRIDGES} flag is set.</li>
   361      *     <li>{@code bridges} is a variable-length list of additional
   362      *     methods signatures to implement, whose length equals {@code bridgeCount},
   363      *     and is present if and only if the {@code FLAG_BRIDGES} flag is set.</li>
   364      * </ul>
   365      *
   366      * <p>Each class named by {@code markerInterfaces} is subject to the same
   367      * restrictions as {@code Rd}, the return type of {@code invokedType},
   368      * as described {@link LambdaMetafactory above}.  Each {@code MethodType}
   369      * named by {@code bridges} is subject to the same restrictions as
   370      * {@code samMethodType}, as described {@link LambdaMetafactory above}.
   371      *
   372      * <p>When FLAG_SERIALIZABLE is set in {@code flags}, the function objects
   373      * will implement {@code Serializable}, and will have a {@code writeReplace}
   374      * method that returns an appropriate {@link SerializedLambda}.  The
   375      * {@code caller} class must have an appropriate {@code $deserializeLambda$}
   376      * method, as described in {@link SerializedLambda}.
   377      *
   378      * <p>When the target of the {@code CallSite} returned from this method is
   379      * invoked, the resulting function objects are instances of a class with
   380      * the following properties:
   381      * <ul>
   382      *     <li>The class implements the interface named by the return type
   383      *     of {@code invokedType} and any interfaces named by {@code markerInterfaces}</li>
   384      *     <li>The class declares methods with the name given by {@code invokedName},
   385      *     and the signature given by {@code samMethodType} and additional signatures
   386      *     given by {@code bridges}</li>
   387      *     <li>The class may override methods from {@code Object}, and may
   388      *     implement methods related to serialization.</li>
   389      * </ul>
   390      *
   391      * @param caller Represents a lookup context with the accessibility
   392      *               privileges of the caller.  When used with {@code invokedynamic},
   393      *               this is stacked automatically by the VM.
   394      * @param invokedName The name of the method to implement.  When used with
   395      *                    {@code invokedynamic}, this is provided by the
   396      *                    {@code NameAndType} of the {@code InvokeDynamic}
   397      *                    structure and is stacked automatically by the VM.
   398      * @param invokedType The expected signature of the {@code CallSite}.  The
   399      *                    parameter types represent the types of capture variables;
   400      *                    the return type is the interface to implement.   When
   401      *                    used with {@code invokedynamic}, this is provided by
   402      *                    the {@code NameAndType} of the {@code InvokeDynamic}
   403      *                    structure and is stacked automatically by the VM.
   404      *                    In the event that the implementation method is an
   405      *                    instance method and this signature has any parameters,
   406      *                    the first parameter in the invocation signature must
   407      *                    correspond to the receiver.
   408      * @param  args       An {@code Object[]} array containing the required
   409      *                    arguments {@code samMethodType}, {@code implMethod},
   410      *                    {@code instantiatedMethodType}, {@code flags}, and any
   411      *                    optional arguments, as described
   412      *                    {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)} above}
   413      * @return a CallSite whose target can be used to perform capture, generating
   414      *         instances of the interface named by {@code invokedType}
   415      * @throws LambdaConversionException If any of the linkage invariants
   416      *                                   described {@link LambdaMetafactory above}
   417      *                                   are violated
   418      */
   419     public static CallSite altMetafactory(MethodHandles.Lookup caller,
   420                                           String invokedName,
   421                                           MethodType invokedType,
   422                                           Object... args)
   423     {
   424         throw new IllegalStateException();
   425     }
   426 }