jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java
author mhaupt
Tue, 23 Feb 2016 07:17:54 +0100
changeset 36112 e71e97060bf5
parent 35772 044f660251cc
child 36114 a5ed9456c9be
permissions -rw-r--r--
8150360: augment/correct MethodHandle API documentation Reviewed-by: psandoz
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
     1
/*
34959
4e7903220c89 8147078: MethodHandles.catchException does not enforce Throwable subtype
mhaupt
parents: 34882
diff changeset
     2
 * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
     4
 *
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
     5
 * This code is free software; you can redistribute it and/or modify it
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
     6
 * under the terms of the GNU General Public License version 2 only, as
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4537
diff changeset
     7
 * published by the Free Software Foundation.  Oracle designates this
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
     8
 * particular file as subject to the "Classpath" exception as provided
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4537
diff changeset
     9
 * by Oracle in the LICENSE file that accompanied this code.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    10
 *
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    14
 * version 2 for more details (a copy is included in the LICENSE file that
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    15
 * accompanied this code).
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    16
 *
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    17
 * You should have received a copy of the GNU General Public License version
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    20
 *
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4537
diff changeset
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4537
diff changeset
    22
 * or visit www.oracle.com if you need additional information or have any
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 4537
diff changeset
    23
 * questions.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    24
 */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    25
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
    26
package java.lang.invoke;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    27
7053
da0e2dc092d3 6953246: JSR 292 should support SAM conversion
jrose
parents: 7052
diff changeset
    28
import java.lang.reflect.*;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    29
import java.util.*;
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
    30
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
    31
import sun.invoke.util.ValueConversions;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
    32
import sun.invoke.util.VerifyAccess;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
    33
import sun.invoke.util.Wrapper;
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
    34
import sun.reflect.CallerSensitive;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    35
import sun.reflect.Reflection;
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
    36
import sun.reflect.misc.ReflectUtil;
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
    37
import sun.security.util.SecurityConstants;
24572
5c9e5961d21c 8037210: Get rid of char-based descriptions 'J' of basic types
vlivanov
parents: 24367
diff changeset
    38
import java.lang.invoke.LambdaForm.BasicType;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    39
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
    40
import static java.lang.invoke.MethodHandleStatics.*;
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
    41
import static java.lang.invoke.MethodHandleImpl.Intrinsic;
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
    42
import static java.lang.invoke.MethodHandleNatives.Constants.*;
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
    43
import java.util.concurrent.ConcurrentHashMap;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    44
import java.util.stream.Collectors;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    45
import java.util.stream.Stream;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    46
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    47
/**
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    48
 * This class consists exclusively of static methods that operate on or return
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    49
 * method handles. They fall into several categories:
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
    50
 * <ul>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
    51
 * <li>Lookup methods which help create method handles for methods and fields.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
    52
 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
    53
 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
    54
 * </ul>
24367
705490680527 8030709: Tidy warnings cleanup for java.lang package; minor cleanup in java.math, javax.script
yan
parents: 23898
diff changeset
    55
 *
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    56
 * @author John Rose, JSR 292 EG
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
    57
 * @since 1.7
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    58
 */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    59
public class MethodHandles {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    60
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    61
    private MethodHandles() { }  // do not instantiate
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    62
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
    63
    private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
34720
c2192aa0ab88 8144723: MethodHandleImpl.initStatics is no longer needed
redestad
parents: 34430
diff changeset
    64
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    65
    // See IMPL_LOOKUP below.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    66
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    67
    //// Method handle creation from ordinary methods.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    68
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    69
    /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    70
     * Returns a {@link Lookup lookup object} with
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    71
     * full capabilities to emulate all supported bytecode behaviors of the caller.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    72
     * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    73
     * Factory methods on the lookup object can create
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    74
     * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    75
     * for any member that the caller has access to via bytecodes,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    76
     * including protected and private fields and methods.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    77
     * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    78
     * Do not store it in place where untrusted code can access it.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    79
     * <p>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    80
     * This method is caller sensitive, which means that it may return different
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    81
     * values to different callers.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    82
     * <p>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    83
     * For any given caller class {@code C}, the lookup object returned by this call
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    84
     * has equivalent capabilities to any lookup object
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    85
     * supplied by the JVM to the bootstrap method of an
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    86
     * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    87
     * executing in the same caller class {@code C}.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    88
     * @return a lookup object for the caller of this method, with private access
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
    89
     */
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
    90
    @CallerSensitive
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    91
    public static Lookup lookup() {
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
    92
        return new Lookup(Reflection.getCallerClass());
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    93
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    94
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    95
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
    96
     * Returns a {@link Lookup lookup object} which is trusted minimally.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    97
     * It can only be used to create method handles to
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    98
     * publicly accessible fields and methods.
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
    99
     * <p>
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   100
     * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   101
     * of this lookup object will be {@link java.lang.Object}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   102
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   103
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   104
     * <em>Discussion:</em>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   105
     * The lookup class can be changed to any other class {@code C} using an expression of the form
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   106
     * {@link Lookup#in publicLookup().in(C.class)}.
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   107
     * Since all classes have equal access to public names,
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   108
     * such a change would confer no new access rights.
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   109
     * A public lookup object is always subject to
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   110
     * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   111
     * Also, it cannot access
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   112
     * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   113
     * @return a lookup object which is trusted minimally
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   114
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   115
    public static Lookup publicLookup() {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   116
        return Lookup.PUBLIC_LOOKUP;
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   117
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   118
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   119
    /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   120
     * Performs an unchecked "crack" of a
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   121
     * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   122
     * The result is as if the user had obtained a lookup object capable enough
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   123
     * to crack the target method handle, called
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   124
     * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   125
     * on the target to obtain its symbolic reference, and then called
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   126
     * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   127
     * to resolve the symbolic reference to a member.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   128
     * <p>
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   129
     * If there is a security manager, its {@code checkPermission} method
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   130
     * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   131
     * @param <T> the desired type of the result, either {@link Member} or a subtype
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   132
     * @param target a direct method handle to crack into symbolic reference components
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   133
     * @param expected a class object representing the desired result type {@code T}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   134
     * @return a reference to the method, constructor, or field object
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   135
     * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   136
     * @exception NullPointerException if either argument is {@code null}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   137
     * @exception IllegalArgumentException if the target is not a direct method handle
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   138
     * @exception ClassCastException if the member is not of the expected type
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   139
     * @since 1.8
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   140
     */
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   141
    public static <T extends Member> T
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   142
    reflectAs(Class<T> expected, MethodHandle target) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   143
        SecurityManager smgr = System.getSecurityManager();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   144
        if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   145
        Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   146
        return lookup.revealDirect(target).reflectAs(expected, lookup);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   147
    }
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   148
    // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
   149
    private static final java.security.Permission ACCESS_PERMISSION =
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   150
        new ReflectPermission("suppressAccessChecks");
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   151
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   152
    /**
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   153
     * A <em>lookup object</em> is a factory for creating method handles,
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   154
     * when the creation requires access checking.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   155
     * Method handles do not perform
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   156
     * access checks when they are called, but rather when they are created.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   157
     * Therefore, method handle access
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   158
     * restrictions must be enforced when a method handle is created.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   159
     * The caller class against which those restrictions are enforced
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   160
     * is known as the {@linkplain #lookupClass lookup class}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   161
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   162
     * A lookup class which needs to create method handles will call
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   163
     * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   164
     * When the {@code Lookup} factory object is created, the identity of the lookup class is
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   165
     * determined, and securely stored in the {@code Lookup} object.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   166
     * The lookup class (or its delegates) may then use factory methods
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   167
     * on the {@code Lookup} object to create method handles for access-checked members.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   168
     * This includes all methods, constructors, and fields which are allowed to the lookup class,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   169
     * even private ones.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   170
     *
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   171
     * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   172
     * The factory methods on a {@code Lookup} object correspond to all major
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   173
     * use cases for methods, constructors, and fields.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   174
     * Each method handle created by a factory method is the functional
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   175
     * equivalent of a particular <em>bytecode behavior</em>.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   176
     * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   177
     * Here is a summary of the correspondence between these factory methods and
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   178
     * the behavior of the resulting method handles:
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   179
     * <table border=1 cellpadding=5 summary="lookup method behaviors">
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   180
     * <tr>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   181
     *     <th><a name="equiv"></a>lookup expression</th>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   182
     *     <th>member</th>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   183
     *     <th>bytecode behavior</th>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   184
     * </tr>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   185
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   186
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   187
     *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   188
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   189
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   190
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   191
     *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   192
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   193
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   194
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   195
     *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   196
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   197
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   198
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   199
     *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   200
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   201
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   202
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   203
     *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   204
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   205
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   206
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   207
     *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   208
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   209
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   210
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   211
     *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   212
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   213
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   214
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   215
     *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   216
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   217
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   218
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   219
     *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   220
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   221
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   222
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   223
     *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   224
     * </tr>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   225
     * <tr>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   226
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   227
     *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   228
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   229
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   230
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   231
     *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   232
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   233
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   234
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   235
     *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   236
     * </tr>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   237
     * <tr>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   238
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   239
     *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   240
     * </tr>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   241
     * </table>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   242
     *
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   243
     * Here, the type {@code C} is the class or interface being searched for a member,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   244
     * documented as a parameter named {@code refc} in the lookup methods.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   245
     * The method type {@code MT} is composed from the return type {@code T}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   246
     * and the sequence of argument types {@code A*}.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   247
     * The constructor also has a sequence of argument types {@code A*} and
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   248
     * is deemed to return the newly-created object of type {@code C}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   249
     * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   250
     * The formal parameter {@code this} stands for the self-reference of type {@code C};
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   251
     * if it is present, it is always the leading argument to the method handle invocation.
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   252
     * (In the case of some {@code protected} members, {@code this} may be
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   253
     * restricted in type to the lookup class; see below.)
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   254
     * The name {@code arg} stands for all the other method handle arguments.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   255
     * In the code examples for the Core Reflection API, the name {@code thisOrNull}
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   256
     * stands for a null reference if the accessed method or field is static,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   257
     * and {@code this} otherwise.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   258
     * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   259
     * for reflective objects corresponding to the given members.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   260
     * <p>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   261
     * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   262
     * as if by {@code ldc CONSTANT_Class}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   263
     * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   264
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   265
     * In cases where the given member is of variable arity (i.e., a method or constructor)
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   266
     * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   267
     * In all other cases, the returned method handle will be of fixed arity.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   268
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   269
     * <em>Discussion:</em>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   270
     * The equivalence between looked-up method handles and underlying
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   271
     * class members and bytecode behaviors
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   272
     * can break down in a few ways:
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   273
     * <ul style="font-size:smaller;">
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   274
     * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   275
     * the lookup can still succeed, even when there is no equivalent
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   276
     * Java expression or bytecoded constant.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   277
     * <li>Likewise, if {@code T} or {@code MT}
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   278
     * is not symbolically accessible from the lookup class's loader,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   279
     * the lookup can still succeed.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   280
     * For example, lookups for {@code MethodHandle.invokeExact} and
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
   281
     * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   282
     * <li>If there is a security manager installed, it can forbid the lookup
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   283
     * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   284
     * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   285
     * constant is not subject to security manager checks.
20529
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
   286
     * <li>If the looked-up method has a
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
   287
     * <a href="MethodHandle.html#maxarity">very large arity</a>,
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
   288
     * the method handle creation may fail, due to the method handle
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
   289
     * type having too many parameters.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   290
     * </ul>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   291
     *
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   292
     * <h1><a name="access"></a>Access checking</h1>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   293
     * Access checks are applied in the factory methods of {@code Lookup},
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   294
     * when a method handle is created.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   295
     * This is a key difference from the Core Reflection API, since
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   296
     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   297
     * performs access checking against every caller, on every call.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   298
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   299
     * All access checks start from a {@code Lookup} object, which
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   300
     * compares its recorded lookup class against all requests to
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   301
     * create method handles.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   302
     * A single {@code Lookup} object can be used to create any number
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   303
     * of access-checked method handles, all checked against a single
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   304
     * lookup class.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   305
     * <p>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   306
     * A {@code Lookup} object can be shared with other trusted code,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   307
     * such as a metaobject protocol.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   308
     * A shared {@code Lookup} object delegates the capability
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   309
     * to create method handles on private members of the lookup class.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   310
     * Even if privileged code uses the {@code Lookup} object,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   311
     * the access checking is confined to the privileges of the
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   312
     * original lookup class.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   313
     * <p>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   314
     * A lookup can fail, because
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   315
     * the containing class is not accessible to the lookup class, or
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   316
     * because the desired class member is missing, or because the
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   317
     * desired class member is not accessible to the lookup class, or
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   318
     * because the lookup object is not trusted enough to access the member.
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   319
     * In any of these cases, a {@code ReflectiveOperationException} will be
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   320
     * thrown from the attempted lookup.  The exact class will be one of
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   321
     * the following:
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   322
     * <ul>
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   323
     * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   324
     * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   325
     * <li>IllegalAccessException &mdash; if the member exists but an access check fails
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   326
     * </ul>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   327
     * <p>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   328
     * In general, the conditions under which a method handle may be
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   329
     * looked up for a method {@code M} are no more restrictive than the conditions
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   330
     * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   331
     * Where the JVM would raise exceptions like {@code NoSuchMethodError},
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   332
     * a method handle lookup will generally raise a corresponding
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   333
     * checked exception, such as {@code NoSuchMethodException}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   334
     * And the effect of invoking the method handle resulting from the lookup
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   335
     * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   336
     * to executing the compiled, verified, and resolved call to {@code M}.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   337
     * The same point is true of fields and constructors.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   338
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   339
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   340
     * Access checks only apply to named and reflected methods,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   341
     * constructors, and fields.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   342
     * Other method handle creation methods, such as
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   343
     * {@link MethodHandle#asType MethodHandle.asType},
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   344
     * do not require any access checks, and are used
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   345
     * independently of any {@code Lookup} object.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   346
     * <p>
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   347
     * If the desired member is {@code protected}, the usual JVM rules apply,
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   348
     * including the requirement that the lookup class must be either be in the
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   349
     * same package as the desired member, or must inherit that member.
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   350
     * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   351
     * In addition, if the desired member is a non-static field or method
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   352
     * in a different package, the resulting method handle may only be applied
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   353
     * to objects of the lookup class or one of its subclasses.
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   354
     * This requirement is enforced by narrowing the type of the leading
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   355
     * {@code this} parameter from {@code C}
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   356
     * (which will necessarily be a superclass of the lookup class)
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   357
     * to the lookup class itself.
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   358
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   359
     * The JVM imposes a similar requirement on {@code invokespecial} instruction,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   360
     * that the receiver argument must match both the resolved method <em>and</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   361
     * the current class.  Again, this requirement is enforced by narrowing the
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   362
     * type of the leading parameter to the resulting method handle.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   363
     * (See the Java Virtual Machine Specification, section 4.10.1.9.)
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   364
     * <p>
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   365
     * The JVM represents constructors and static initializer blocks as internal methods
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   366
     * with special names ({@code "<init>"} and {@code "<clinit>"}).
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   367
     * The internal syntax of invocation instructions allows them to refer to such internal
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   368
     * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   369
     * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   370
     * <p>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   371
     * In some cases, access between nested classes is obtained by the Java compiler by creating
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   372
     * an wrapper method to access a private method of another class
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   373
     * in the same top-level declaration.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   374
     * For example, a nested class {@code C.D}
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   375
     * can access private members within other related classes such as
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   376
     * {@code C}, {@code C.D.E}, or {@code C.B},
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   377
     * but the Java compiler may need to generate wrapper methods in
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   378
     * those related classes.  In such cases, a {@code Lookup} object on
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   379
     * {@code C.E} would be unable to those private members.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   380
     * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   381
     * which can transform a lookup on {@code C.E} into one on any of those other
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   382
     * classes, without special elevation of privilege.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   383
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   384
     * The accesses permitted to a given lookup object may be limited,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   385
     * according to its set of {@link #lookupModes lookupModes},
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   386
     * to a subset of members normally accessible to the lookup class.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   387
     * For example, the {@link MethodHandles#publicLookup publicLookup}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   388
     * method produces a lookup object which is only allowed to access
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   389
     * public members in public classes.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   390
     * The caller sensitive method {@link MethodHandles#lookup lookup}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   391
     * produces a lookup object with full capabilities relative to
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   392
     * its caller class, to emulate all supported bytecode behaviors.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   393
     * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   394
     * with fewer access modes than the original lookup object.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   395
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   396
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   397
     * <a name="privacc"></a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   398
     * <em>Discussion of private access:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   399
     * We say that a lookup has <em>private access</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   400
     * if its {@linkplain #lookupModes lookup modes}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   401
     * include the possibility of accessing {@code private} members.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   402
     * As documented in the relevant methods elsewhere,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   403
     * only lookups with private access possess the following capabilities:
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   404
     * <ul style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   405
     * <li>access private fields, methods, and constructors of the lookup class
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   406
     * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   407
     *     such as {@code Class.forName}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   408
     * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   409
     * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   410
     *     for classes accessible to the lookup class
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   411
     * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   412
     *     within the same package member
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   413
     * </ul>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   414
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   415
     * Each of these permissions is a consequence of the fact that a lookup object
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   416
     * with private access can be securely traced back to an originating class,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   417
     * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   418
     * can be reliably determined and emulated by method handles.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   419
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   420
     * <h1><a name="secmgr"></a>Security manager interactions</h1>
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   421
     * Although bytecode instructions can only refer to classes in
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   422
     * a related class loader, this API can search for methods in any
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   423
     * class, as long as a reference to its {@code Class} object is
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   424
     * available.  Such cross-loader references are also possible with the
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   425
     * Core Reflection API, and are impossible to bytecode instructions
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   426
     * such as {@code invokestatic} or {@code getfield}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   427
     * There is a {@linkplain java.lang.SecurityManager security manager API}
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   428
     * to allow applications to check such cross-loader references.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   429
     * These checks apply to both the {@code MethodHandles.Lookup} API
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   430
     * and the Core Reflection API
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   431
     * (as found on {@link java.lang.Class Class}).
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   432
     * <p>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   433
     * If a security manager is present, member and class lookups are subject to
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   434
     * additional checks.
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   435
     * From one to three calls are made to the security manager.
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   436
     * Any of these calls can refuse access by throwing a
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   437
     * {@link java.lang.SecurityException SecurityException}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   438
     * Define {@code smgr} as the security manager,
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   439
     * {@code lookc} as the lookup class of the current lookup object,
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   440
     * {@code refc} as the containing class in which the member
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   441
     * is being sought, and {@code defc} as the class in which the
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   442
     * member is actually defined.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   443
     * (If a class or other type is being accessed,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   444
     * the {@code refc} and {@code defc} values are the class itself.)
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   445
     * The value {@code lookc} is defined as <em>not present</em>
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   446
     * if the current lookup object does not have
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   447
     * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   448
     * The calls are made according to the following rules:
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   449
     * <ul>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   450
     * <li><b>Step 1:</b>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   451
     *     If {@code lookc} is not present, or if its class loader is not
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   452
     *     the same as or an ancestor of the class loader of {@code refc},
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   453
     *     then {@link SecurityManager#checkPackageAccess
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   454
     *     smgr.checkPackageAccess(refcPkg)} is called,
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   455
     *     where {@code refcPkg} is the package of {@code refc}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   456
     * <li><b>Step 2a:</b>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   457
     *     If the retrieved member is not public and
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   458
     *     {@code lookc} is not present, then
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   459
     *     {@link SecurityManager#checkPermission smgr.checkPermission}
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   460
     *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   461
     * <li><b>Step 2b:</b>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   462
     *     If the retrieved class has a {@code null} class loader,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   463
     *     and {@code lookc} is not present, then
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   464
     *     {@link SecurityManager#checkPermission smgr.checkPermission}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   465
     *     with {@code RuntimePermission("getClassLoader")} is called.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   466
     * <li><b>Step 3:</b>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   467
     *     If the retrieved member is not public,
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   468
     *     and if {@code lookc} is not present,
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   469
     *     and if {@code defc} and {@code refc} are different,
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   470
     *     then {@link SecurityManager#checkPackageAccess
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   471
     *     smgr.checkPackageAccess(defcPkg)} is called,
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   472
     *     where {@code defcPkg} is the package of {@code defc}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   473
     * </ul>
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   474
     * Security checks are performed after other access checks have passed.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   475
     * Therefore, the above rules presuppose a member or class that is public,
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   476
     * or else that is being accessed from a lookup class that has
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   477
     * rights to access the member or class.
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   478
     *
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   479
     * <h1><a name="callsens"></a>Caller sensitive methods</h1>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   480
     * A small number of Java methods have a special property called caller sensitivity.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   481
     * A <em>caller-sensitive</em> method can behave differently depending on the
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   482
     * identity of its immediate caller.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   483
     * <p>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   484
     * If a method handle for a caller-sensitive method is requested,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   485
     * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   486
     * but they take account of the lookup class in a special way.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   487
     * The resulting method handle behaves as if it were called
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   488
     * from an instruction contained in the lookup class,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   489
     * so that the caller-sensitive method detects the lookup class.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   490
     * (By contrast, the invoker of the method handle is disregarded.)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   491
     * Thus, in the case of caller-sensitive methods,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   492
     * different lookup classes may give rise to
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   493
     * differently behaving method handles.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   494
     * <p>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   495
     * In cases where the lookup object is
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   496
     * {@link MethodHandles#publicLookup() publicLookup()},
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   497
     * or some other lookup object without
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   498
     * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   499
     * the lookup class is disregarded.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   500
     * In such cases, no caller-sensitive method handle can be created,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   501
     * access is forbidden, and the lookup fails with an
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   502
     * {@code IllegalAccessException}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   503
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   504
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   505
     * For example, the caller-sensitive method
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   506
     * {@link java.lang.Class#forName(String) Class.forName(x)}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   507
     * can return varying classes or throw varying exceptions,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   508
     * depending on the class loader of the class that calls it.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   509
     * A public lookup of {@code Class.forName} will fail, because
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   510
     * there is no reasonable way to determine its bytecode behavior.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   511
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   512
     * If an application caches method handles for broad sharing,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   513
     * it should use {@code publicLookup()} to create them.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   514
     * If there is a lookup of {@code Class.forName}, it will fail,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   515
     * and the application must take appropriate action in that case.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   516
     * It may be that a later lookup, perhaps during the invocation of a
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   517
     * bootstrap method, can incorporate the specific identity
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   518
     * of the caller, making the method accessible.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   519
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   520
     * The function {@code MethodHandles.lookup} is caller sensitive
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   521
     * so that there can be a secure foundation for lookups.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   522
     * Nearly all other methods in the JSR 292 API rely on lookup
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   523
     * objects to check access requests.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   524
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   525
    public static final
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   526
    class Lookup {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   527
        /** The class on behalf of whom the lookup is being performed. */
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   528
        private final Class<?> lookupClass;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   529
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   530
        /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   531
        private final int allowedModes;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   532
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   533
        /** A single-bit mask representing {@code public} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   534
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   535
         *  The value, {@code 0x01}, happens to be the same as the value of the
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   536
         *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   537
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   538
        public static final int PUBLIC = Modifier.PUBLIC;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   539
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   540
        /** A single-bit mask representing {@code private} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   541
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   542
         *  The value, {@code 0x02}, happens to be the same as the value of the
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   543
         *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   544
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   545
        public static final int PRIVATE = Modifier.PRIVATE;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   546
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   547
        /** A single-bit mask representing {@code protected} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   548
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   549
         *  The value, {@code 0x04}, happens to be the same as the value of the
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   550
         *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   551
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   552
        public static final int PROTECTED = Modifier.PROTECTED;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   553
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   554
        /** A single-bit mask representing {@code package} access (default access),
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   555
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   556
         *  The value is {@code 0x08}, which does not correspond meaningfully to
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   557
         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   558
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   559
        public static final int PACKAGE = Modifier.STATIC;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   560
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   561
        private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   562
        private static final int TRUSTED   = -1;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   563
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   564
        private static int fixmods(int mods) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   565
            mods &= (ALL_MODES - PACKAGE);
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   566
            return (mods != 0) ? mods : PACKAGE;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   567
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   568
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   569
        /** Tells which class is performing the lookup.  It is this class against
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   570
         *  which checks are performed for visibility and access permissions.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   571
         *  <p>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   572
         *  The class implies a maximum level of access permission,
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   573
         *  but the permissions may be additionally limited by the bitmask
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   574
         *  {@link #lookupModes lookupModes}, which controls whether non-public members
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   575
         *  can be accessed.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   576
         *  @return the lookup class, on behalf of which this lookup object finds members
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   577
         */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   578
        public Class<?> lookupClass() {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   579
            return lookupClass;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   580
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   581
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   582
        // This is just for calling out to MethodHandleImpl.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   583
        private Class<?> lookupClassOrNull() {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   584
            return (allowedModes == TRUSTED) ? null : lookupClass;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   585
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   586
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   587
        /** Tells which access-protection classes of members this lookup object can produce.
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   588
         *  The result is a bit-mask of the bits
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   589
         *  {@linkplain #PUBLIC PUBLIC (0x01)},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   590
         *  {@linkplain #PRIVATE PRIVATE (0x02)},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   591
         *  {@linkplain #PROTECTED PROTECTED (0x04)},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   592
         *  and {@linkplain #PACKAGE PACKAGE (0x08)}.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   593
         *  <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   594
         *  A freshly-created lookup object
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   595
         *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   596
         *  has all possible bits set, since the caller class can access all its own members.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   597
         *  A lookup object on a new lookup class
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   598
         *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   599
         *  may have some mode bits set to zero.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   600
         *  The purpose of this is to restrict access via the new lookup object,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   601
         *  so that it can access only names which can be reached by the original
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   602
         *  lookup object, and also by the new lookup class.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   603
         *  @return the lookup modes, which limit the kinds of access performed by this lookup object
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   604
         */
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   605
        public int lookupModes() {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   606
            return allowedModes & ALL_MODES;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   607
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   608
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   609
        /** Embody the current class (the lookupClass) as a lookup class
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   610
         * for method handle creation.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   611
         * Must be called by from a method in this package,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   612
         * which in turn is called by a method not in this package.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   613
         */
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   614
        Lookup(Class<?> lookupClass) {
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   615
            this(lookupClass, ALL_MODES);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   616
            // make sure we haven't accidentally picked up a privileged class:
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   617
            checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   618
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   619
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   620
        private Lookup(Class<?> lookupClass, int allowedModes) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   621
            this.lookupClass = lookupClass;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   622
            this.allowedModes = allowedModes;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   623
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   624
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   625
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   626
         * Creates a lookup on the specified new lookup class.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   627
         * The resulting object will report the specified
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   628
         * class as its own {@link #lookupClass lookupClass}.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   629
         * <p>
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   630
         * However, the resulting {@code Lookup} object is guaranteed
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   631
         * to have no more access capabilities than the original.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   632
         * In particular, access capabilities can be lost as follows:<ul>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   633
         * <li>If the new lookup class differs from the old one,
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   634
         * protected members will not be accessible by virtue of inheritance.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   635
         * (Protected members may continue to be accessible because of package sharing.)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   636
         * <li>If the new lookup class is in a different package
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   637
         * than the old one, protected and default (package) members will not be accessible.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   638
         * <li>If the new lookup class is not within the same package member
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   639
         * as the old one, private members will not be accessible.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   640
         * <li>If the new lookup class is not accessible to the old lookup class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   641
         * then no members, not even public members, will be accessible.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   642
         * (In all other cases, public members will continue to be accessible.)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   643
         * </ul>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   644
         *
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   645
         * @param requestedLookupClass the desired lookup class for the new lookup object
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   646
         * @return a lookup object which reports the desired lookup class
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   647
         * @throws NullPointerException if the argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   648
         */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   649
        public Lookup in(Class<?> requestedLookupClass) {
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
   650
            Objects.requireNonNull(requestedLookupClass);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   651
            if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   652
                return new Lookup(requestedLookupClass, ALL_MODES);
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   653
            if (requestedLookupClass == this.lookupClass)
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   654
                return this;  // keep same capabilities
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   655
            int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   656
            if ((newModes & PACKAGE) != 0
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   657
                && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   658
                newModes &= ~(PACKAGE|PRIVATE);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   659
            }
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   660
            // Allow nestmate lookups to be created without special privilege:
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   661
            if ((newModes & PRIVATE) != 0
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   662
                && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   663
                newModes &= ~PRIVATE;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   664
            }
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
   665
            if ((newModes & PUBLIC) != 0
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
   666
                && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   667
                // The requested class it not accessible from the lookup class.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   668
                // No permissions.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   669
                newModes = 0;
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   670
            }
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   671
            checkUnprivilegedlookupClass(requestedLookupClass, newModes);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   672
            return new Lookup(requestedLookupClass, newModes);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   673
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   674
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   675
        // Make sure outer class is initialized first.
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
   676
        static { IMPL_NAMES.getClass(); }
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   677
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   678
        /** Version of lookup which is trusted minimally.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   679
         *  It can only be used to create method handles to
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   680
         *  publicly accessible members.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   681
         */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   682
        static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   683
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   684
        /** Package-private version of lookup which is trusted. */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   685
        static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   686
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   687
        private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
2764
2e45af54c0f9 6839839: access checking logic is wrong at three points in MethodHandles
jrose
parents: 2763
diff changeset
   688
            String name = lookupClass.getName();
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   689
            if (name.startsWith("java.lang.invoke."))
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   690
                throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   691
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   692
            // For caller-sensitive MethodHandles.lookup()
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   693
            // disallow lookup more restricted packages
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   694
            if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   695
                if (name.startsWith("java.") ||
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   696
                        (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   697
                    throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   698
                }
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   699
            }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   700
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   701
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   702
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   703
         * Displays the name of the class from which lookups are to be made.
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   704
         * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   705
         * If there are restrictions on the access permitted to this lookup,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   706
         * this is indicated by adding a suffix to the class name, consisting
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   707
         * of a slash and a keyword.  The keyword represents the strongest
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   708
         * allowed access, and is chosen as follows:
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   709
         * <ul>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   710
         * <li>If no access is allowed, the suffix is "/noaccess".
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   711
         * <li>If only public access is allowed, the suffix is "/public".
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   712
         * <li>If only public and package access are allowed, the suffix is "/package".
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   713
         * <li>If only public, package, and private access are allowed, the suffix is "/private".
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   714
         * </ul>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   715
         * If none of the above cases apply, it is the case that full
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   716
         * access (public, package, private, and protected) is allowed.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   717
         * In this case, no suffix is added.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   718
         * This is true only of an object obtained originally from
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   719
         * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   720
         * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   721
         * always have restricted access, and will display a suffix.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   722
         * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   723
         * (It may seem strange that protected access should be
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   724
         * stronger than private access.  Viewed independently from
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   725
         * package access, protected access is the first to be lost,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   726
         * because it requires a direct subclass relationship between
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   727
         * caller and callee.)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   728
         * @see #in
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   729
         */
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   730
        @Override
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   731
        public String toString() {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   732
            String cname = lookupClass.getName();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   733
            switch (allowedModes) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   734
            case 0:  // no privileges
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   735
                return cname + "/noaccess";
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   736
            case PUBLIC:
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   737
                return cname + "/public";
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   738
            case PUBLIC|PACKAGE:
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   739
                return cname + "/package";
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   740
            case ALL_MODES & ~PROTECTED:
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   741
                return cname + "/private";
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   742
            case ALL_MODES:
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   743
                return cname;
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   744
            case TRUSTED:
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   745
                return "/trusted";  // internal only; not exported
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   746
            default:  // Should not happen, but it's a bitfield...
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   747
                cname = cname + "/" + Integer.toHexString(allowedModes);
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   748
                assert(false) : cname;
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   749
                return cname;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   750
            }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   751
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   752
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   753
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   754
         * Produces a method handle for a static method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   755
         * The type of the method handle will be that of the method.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   756
         * (Since static methods do not take receivers, there is no
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   757
         * additional receiver argument inserted into the method handle type,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   758
         * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   759
         * The method and all its argument types must be accessible to the lookup object.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   760
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   761
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   762
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   763
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   764
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   765
         * If the returned method handle is invoked, the method's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   766
         * be initialized, if it has not already been initialized.
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   767
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
   768
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   769
import static java.lang.invoke.MethodHandles.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   770
import static java.lang.invoke.MethodType.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   771
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   772
MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   773
  "asList", methodType(List.class, Object[].class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   774
assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   775
         * }</pre></blockquote>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   776
         * @param refc the class from which the method is accessed
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   777
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   778
         * @param type the type of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   779
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   780
         * @throws NoSuchMethodException if the method does not exist
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   781
         * @throws IllegalAccessException if access checking fails,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   782
         *                                or if the method is not {@code static},
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   783
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   784
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   785
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   786
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   787
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   788
         */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   789
        public
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   790
        MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   791
            MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
   792
            return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
   793
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   794
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   795
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   796
         * Produces a method handle for a virtual method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   797
         * The type of the method handle will be that of the method,
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   798
         * with the receiver type (usually {@code refc}) prepended.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   799
         * The method and all its argument types must be accessible to the lookup object.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   800
         * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   801
         * When called, the handle will treat the first argument as a receiver
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   802
         * and dispatch on the receiver's type to determine which method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   803
         * implementation to enter.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   804
         * (The dispatching action is identical with that performed by an
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   805
         * {@code invokevirtual} or {@code invokeinterface} instruction.)
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   806
         * <p>
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   807
         * The first argument will be of type {@code refc} if the lookup
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   808
         * class has full privileges to access the member.  Otherwise
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   809
         * the member must be {@code protected} and the first argument
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   810
         * will be restricted in type to the lookup class.
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   811
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   812
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   813
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   814
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   815
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   816
         * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   817
         * instructions and method handles produced by {@code findVirtual},
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   818
         * if the class is {@code MethodHandle} and the name string is
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
   819
         * {@code invokeExact} or {@code invoke}, the resulting
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   820
         * method handle is equivalent to one produced by
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   821
         * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
   822
         * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   823
         * with the same {@code type} argument.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   824
         *
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   825
         * <b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
   826
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   827
import static java.lang.invoke.MethodHandles.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   828
import static java.lang.invoke.MethodType.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   829
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   830
MethodHandle MH_concat = publicLookup().findVirtual(String.class,
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   831
  "concat", methodType(String.class, String.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   832
MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   833
  "hashCode", methodType(int.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   834
MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   835
  "hashCode", methodType(int.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   836
assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   837
assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   838
assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   839
// interface method:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   840
MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   841
  "subSequence", methodType(CharSequence.class, int.class, int.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   842
assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   843
// constructor "internal method" must be accessed differently:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   844
MethodType MT_newString = methodType(void.class); //()V for new String()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   845
try { assertEquals("impossible", lookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   846
        .findVirtual(String.class, "<init>", MT_newString));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   847
 } catch (NoSuchMethodException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   848
MethodHandle MH_newString = publicLookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   849
  .findConstructor(String.class, MT_newString);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   850
assertEquals("", (String) MH_newString.invokeExact());
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   851
         * }</pre></blockquote>
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   852
         *
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   853
         * @param refc the class or interface from which the method is accessed
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   854
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   855
         * @param type the type of the method, with the receiver argument omitted
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   856
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   857
         * @throws NoSuchMethodException if the method does not exist
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   858
         * @throws IllegalAccessException if access checking fails,
35772
044f660251cc 8138884: MethodHandles.Lookup.findVirtual() Javadoc fails to consider private interface methods
srastogi
parents: 35716
diff changeset
   859
         *                                or if the method is {@code static},
044f660251cc 8138884: MethodHandles.Lookup.findVirtual() Javadoc fails to consider private interface methods
srastogi
parents: 35716
diff changeset
   860
         *                                or if the method is {@code private} method of interface,
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   861
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   862
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   863
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   864
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   865
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   866
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   867
        public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   868
            if (refc == MethodHandle.class) {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   869
                MethodHandle mh = findVirtualForMH(name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   870
                if (mh != null)  return mh;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   871
            }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   872
            byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   873
            MemberName method = resolveOrFail(refKind, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
   874
            return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
   875
        }
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   876
        private MethodHandle findVirtualForMH(String name, MethodType type) {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   877
            // these names require special lookups because of the implicit MethodType argument
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   878
            if ("invoke".equals(name))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   879
                return invoker(type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   880
            if ("invokeExact".equals(name))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   881
                return exactInvoker(type);
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
   882
            if ("invokeBasic".equals(name))
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
   883
                return basicInvoker(type);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   884
            assert(!MemberName.isMethodHandleInvokeName(name));
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   885
            return null;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   886
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   887
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   888
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   889
         * Produces a method handle which creates an object and initializes it, using
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   890
         * the constructor of the specified type.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   891
         * The parameter types of the method handle will be those of the constructor,
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   892
         * while the return type will be a reference to the constructor's class.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   893
         * The constructor and all its argument types must be accessible to the lookup object.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   894
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   895
         * The requested type must have a return type of {@code void}.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   896
         * (This is consistent with the JVM's treatment of constructor type descriptors.)
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   897
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   898
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   899
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   900
         * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   901
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   902
         * If the returned method handle is invoked, the constructor's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   903
         * be initialized, if it has not already been initialized.
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   904
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
   905
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   906
import static java.lang.invoke.MethodHandles.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   907
import static java.lang.invoke.MethodType.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   908
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   909
MethodHandle MH_newArrayList = publicLookup().findConstructor(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   910
  ArrayList.class, methodType(void.class, Collection.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   911
Collection orig = Arrays.asList("x", "y");
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   912
Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   913
assert(orig != copy);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   914
assertEquals(orig, copy);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   915
// a variable-arity constructor:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   916
MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   917
  ProcessBuilder.class, methodType(void.class, String[].class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   918
ProcessBuilder pb = (ProcessBuilder)
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   919
  MH_newProcessBuilder.invoke("x", "y", "z");
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   920
assertEquals("[x, y, z]", pb.command().toString());
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   921
         * }</pre></blockquote>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   922
         * @param refc the class or interface from which the method is accessed
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   923
         * @param type the type of the method, with the receiver argument omitted, and a void return type
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   924
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   925
         * @throws NoSuchMethodException if the constructor does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   926
         * @throws IllegalAccessException if access checking fails
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   927
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   928
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   929
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   930
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   931
         * @throws NullPointerException if any argument is null
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   932
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   933
        public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   934
            String name = "<init>";
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   935
            MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   936
            return getDirectConstructor(refc, ctor);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   937
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   938
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   939
        /**
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   940
         * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   941
         * initializer of the class is not run.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   942
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   943
         * @param targetName the fully qualified name of the class to be looked up.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   944
         * @return the requested class.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   945
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   946
         *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   947
         * @throws LinkageError if the linkage fails
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   948
         * @throws ClassNotFoundException if the class does not exist.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   949
         * @throws IllegalAccessException if the class is not accessible, using the allowed access
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   950
         * modes.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   951
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   952
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   953
         * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   954
         */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   955
        public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   956
            Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   957
            return accessClass(targetClass);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   958
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   959
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   960
        /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   961
         * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   962
         * static initializer of the class is not run.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   963
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   964
         * @param targetClass the class to be access-checked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   965
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   966
         * @return the class that has been access-checked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   967
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   968
         * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   969
         * modes.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   970
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   971
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   972
         * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   973
         */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   974
        public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   975
            if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   976
                throw new MemberName(targetClass).makeAccessException("access violation", this);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   977
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   978
            checkSecurityManager(targetClass, null);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   979
            return targetClass;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   980
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   981
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   982
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   983
         * Produces an early-bound method handle for a virtual method.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   984
         * It will bypass checks for overriding methods on the receiver,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   985
         * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   986
         * instruction from within the explicitly specified {@code specialCaller}.
2763
172d44ffd1e5 6839802: java.dyn needs to be on the CORE_PKGS list
jrose
parents: 2707
diff changeset
   987
         * The type of the method handle will be that of the method,
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   988
         * with a suitably restricted receiver type prepended.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   989
         * (The receiver type will be {@code specialCaller} or a subtype.)
2763
172d44ffd1e5 6839802: java.dyn needs to be on the CORE_PKGS list
jrose
parents: 2707
diff changeset
   990
         * The method and all its argument types must be accessible
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   991
         * to the lookup object.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   992
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   993
         * Before method resolution,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   994
         * if the explicitly specified caller class is not identical with the
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   995
         * lookup class, or if this lookup object does not have
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   996
         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   997
         * privileges, the access fails.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   998
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   999
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1000
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1001
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1002
         * <p style="font-size:smaller;">
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1003
         * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1004
         * even though the {@code invokespecial} instruction can refer to them
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1005
         * in special circumstances.  Use {@link #findConstructor findConstructor}
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1006
         * to access instance initialization methods in a safe manner.)</em>
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1007
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  1008
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1009
import static java.lang.invoke.MethodHandles.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1010
import static java.lang.invoke.MethodType.*;
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1011
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1012
static class Listie extends ArrayList {
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1013
  public String toString() { return "[wee Listie]"; }
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1014
  static Lookup lookup() { return MethodHandles.lookup(); }
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1015
}
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1016
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1017
// no access to constructor via invokeSpecial:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1018
MethodHandle MH_newListie = Listie.lookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1019
  .findConstructor(Listie.class, methodType(void.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1020
Listie l = (Listie) MH_newListie.invokeExact();
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1021
try { assertEquals("impossible", Listie.lookup().findSpecial(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1022
        Listie.class, "<init>", methodType(void.class), Listie.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1023
 } catch (NoSuchMethodException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1024
// access to super and self methods via invokeSpecial:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1025
MethodHandle MH_super = Listie.lookup().findSpecial(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1026
  ArrayList.class, "toString" , methodType(String.class), Listie.class);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1027
MethodHandle MH_this = Listie.lookup().findSpecial(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1028
  Listie.class, "toString" , methodType(String.class), Listie.class);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1029
MethodHandle MH_duper = Listie.lookup().findSpecial(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1030
  Object.class, "toString" , methodType(String.class), Listie.class);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1031
assertEquals("[]", (String) MH_super.invokeExact(l));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1032
assertEquals(""+l, (String) MH_this.invokeExact(l));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1033
assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1034
try { assertEquals("inaccessible", Listie.lookup().findSpecial(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1035
        String.class, "toString", methodType(String.class), Listie.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1036
 } catch (IllegalAccessException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1037
Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1038
assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1039
         * }</pre></blockquote>
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1040
         *
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1041
         * @param refc the class or interface from which the method is accessed
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1042
         * @param name the name of the method (which must not be "&lt;init&gt;")
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1043
         * @param type the type of the method, with the receiver argument omitted
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1044
         * @param specialCaller the proposed calling class to perform the {@code invokespecial}
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1045
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1046
         * @throws NoSuchMethodException if the method does not exist
35716
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1047
         * @throws IllegalAccessException if access checking fails,
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1048
         *                                or if the method is {@code static},
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1049
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1050
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1051
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1052
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1053
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1054
         */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1055
        public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1056
                                        Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1057
            checkSpecialCaller(specialCaller, refc);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1058
            Lookup specialLookup = this.in(specialCaller);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1059
            MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1060
            return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1061
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1062
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1063
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1064
         * Produces a method handle giving read access to a non-static field.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1065
         * The type of the method handle will have a return type of the field's
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1066
         * value type.
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1067
         * The method handle's single argument will be the instance containing
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1068
         * the field.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1069
         * Access checking is performed immediately on behalf of the lookup class.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1070
         * @param refc the class or interface from which the method is accessed
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1071
         * @param name the field's name
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1072
         * @param type the field's type
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1073
         * @return a method handle which can load values from the field
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1074
         * @throws NoSuchFieldException if the field does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1075
         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1076
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1077
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1078
         * @throws NullPointerException if any argument is null
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1079
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1080
        public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1081
            MemberName field = resolveOrFail(REF_getField, refc, name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1082
            return getDirectField(REF_getField, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1083
        }
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1084
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1085
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1086
         * Produces a method handle giving write access to a non-static field.
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1087
         * The type of the method handle will have a void return type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1088
         * The method handle will take two arguments, the instance containing
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1089
         * the field, and the value to be stored.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1090
         * The second argument will be of the field's value type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1091
         * Access checking is performed immediately on behalf of the lookup class.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1092
         * @param refc the class or interface from which the method is accessed
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1093
         * @param name the field's name
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1094
         * @param type the field's type
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1095
         * @return a method handle which can store values into the field
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1096
         * @throws NoSuchFieldException if the field does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1097
         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1098
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1099
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1100
         * @throws NullPointerException if any argument is null
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1101
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1102
        public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1103
            MemberName field = resolveOrFail(REF_putField, refc, name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1104
            return getDirectField(REF_putField, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1105
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1106
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1107
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1108
         * Produces a method handle giving read access to a static field.
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1109
         * The type of the method handle will have a return type of the field's
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1110
         * value type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1111
         * The method handle will take no arguments.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1112
         * Access checking is performed immediately on behalf of the lookup class.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1113
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1114
         * If the returned method handle is invoked, the field's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1115
         * be initialized, if it has not already been initialized.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1116
         * @param refc the class or interface from which the method is accessed
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1117
         * @param name the field's name
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1118
         * @param type the field's type
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1119
         * @return a method handle which can load values from the field
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1120
         * @throws NoSuchFieldException if the field does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1121
         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1122
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1123
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1124
         * @throws NullPointerException if any argument is null
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1125
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1126
        public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1127
            MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1128
            return getDirectField(REF_getStatic, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1129
        }
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1130
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1131
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1132
         * Produces a method handle giving write access to a static field.
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1133
         * The type of the method handle will have a void return type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1134
         * The method handle will take a single
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1135
         * argument, of the field's value type, the value to be stored.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1136
         * Access checking is performed immediately on behalf of the lookup class.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1137
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1138
         * If the returned method handle is invoked, the field's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1139
         * be initialized, if it has not already been initialized.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1140
         * @param refc the class or interface from which the method is accessed
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1141
         * @param name the field's name
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1142
         * @param type the field's type
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1143
         * @return a method handle which can store values into the field
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1144
         * @throws NoSuchFieldException if the field does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1145
         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1146
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1147
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1148
         * @throws NullPointerException if any argument is null
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1149
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1150
        public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1151
            MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1152
            return getDirectField(REF_putStatic, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1153
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1154
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1155
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1156
         * Produces an early-bound method handle for a non-static method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1157
         * The receiver must have a supertype {@code defc} in which a method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1158
         * of the given name and type is accessible to the lookup class.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1159
         * The method and all its argument types must be accessible to the lookup object.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1160
         * The type of the method handle will be that of the method,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1161
         * without any insertion of an additional receiver parameter.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1162
         * The given receiver will be bound into the method handle,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1163
         * so that every call to the method handle will invoke the
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1164
         * requested method on the given receiver.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1165
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1166
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1167
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1168
         * the method's variable arity modifier bit ({@code 0x0080}) is set
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1169
         * <em>and</em> the trailing array argument is not the only argument.
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1170
         * (If the trailing array argument is the only argument,
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1171
         * the given receiver value will be bound to it.)
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1172
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1173
         * This is equivalent to the following code:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1174
         * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1175
import static java.lang.invoke.MethodHandles.*;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1176
import static java.lang.invoke.MethodType.*;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1177
...
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1178
MethodHandle mh0 = lookup().findVirtual(defc, name, type);
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1179
MethodHandle mh1 = mh0.bindTo(receiver);
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1180
MethodType mt1 = mh1.type();
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1181
if (mh0.isVarargsCollector())
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1182
  mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1183
return mh1;
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1184
         * }</pre></blockquote>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1185
         * where {@code defc} is either {@code receiver.getClass()} or a super
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1186
         * type of that class, in which the requested method is accessible
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1187
         * to the lookup class.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1188
         * (Note that {@code bindTo} does not preserve variable arity.)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1189
         * @param receiver the object from which the method is accessed
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1190
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1191
         * @param type the type of the method, with the receiver argument omitted
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1192
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1193
         * @throws NoSuchMethodException if the method does not exist
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1194
         * @throws IllegalAccessException if access checking fails
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1195
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1196
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1197
         * @exception SecurityException if a security manager is present and it
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1198
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1199
         * @throws NullPointerException if any argument is null
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1200
         * @see MethodHandle#bindTo
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1201
         * @see #findVirtual
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1202
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1203
        public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1204
            Class<? extends Object> refc = receiver.getClass(); // may get NPE
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1205
            MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1206
            MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  1207
            return mh.bindArgumentL(0, receiver).setVarargs(method);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1208
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1209
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1210
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1211
         * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1212
         * to <i>m</i>, if the lookup class has permission.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1213
         * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1214
         * If <i>m</i> is virtual, overriding is respected on every call.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1215
         * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1216
         * The type of the method handle will be that of the method,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1217
         * with the receiver type prepended (but only if it is non-static).
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1218
         * If the method's {@code accessible} flag is not set,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1219
         * access checking is performed immediately on behalf of the lookup class.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1220
         * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1221
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1222
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1223
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1224
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1225
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1226
         * If <i>m</i> is static, and
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1227
         * if the returned method handle is invoked, the method's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1228
         * be initialized, if it has not already been initialized.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1229
         * @param m the reflected method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1230
         * @return a method handle which can invoke the reflected method
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1231
         * @throws IllegalAccessException if access checking fails
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1232
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1233
         *                                is set and {@code asVarargsCollector} fails
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1234
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1235
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1236
        public MethodHandle unreflect(Method m) throws IllegalAccessException {
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1237
            if (m.getDeclaringClass() == MethodHandle.class) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1238
                MethodHandle mh = unreflectForMH(m);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1239
                if (mh != null)  return mh;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1240
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1241
            MemberName method = new MemberName(m);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1242
            byte refKind = method.getReferenceKind();
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1243
            if (refKind == REF_invokeSpecial)
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1244
                refKind = REF_invokeVirtual;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1245
            assert(method.isMethod());
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1246
            Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1247
            return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1248
        }
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1249
        private MethodHandle unreflectForMH(Method m) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1250
            // these names require special lookups because they throw UnsupportedOperationException
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1251
            if (MemberName.isMethodHandleInvokeName(m.getName()))
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1252
                return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1253
            return null;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1254
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1255
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1256
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1257
         * Produces a method handle for a reflected method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1258
         * It will bypass checks for overriding methods on the receiver,
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1259
         * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1260
         * instruction from within the explicitly specified {@code specialCaller}.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1261
         * The type of the method handle will be that of the method,
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1262
         * with a suitably restricted receiver type prepended.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1263
         * (The receiver type will be {@code specialCaller} or a subtype.)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1264
         * If the method's {@code accessible} flag is not set,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1265
         * access checking is performed immediately on behalf of the lookup class,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1266
         * as if {@code invokespecial} instruction were being linked.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1267
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1268
         * Before method resolution,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1269
         * if the explicitly specified caller class is not identical with the
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1270
         * lookup class, or if this lookup object does not have
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1271
         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1272
         * privileges, the access fails.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1273
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1274
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1275
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1276
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1277
         * @param m the reflected method
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1278
         * @param specialCaller the class nominally calling the method
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1279
         * @return a method handle which can invoke the reflected method
35716
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1280
         * @throws IllegalAccessException if access checking fails,
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1281
         *                                or if the method is {@code static},
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1282
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1283
         *                                is set and {@code asVarargsCollector} fails
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1284
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1285
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1286
        public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1287
            checkSpecialCaller(specialCaller, null);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1288
            Lookup specialLookup = this.in(specialCaller);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1289
            MemberName method = new MemberName(m, true);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1290
            assert(method.isMethod());
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1291
            // ignore m.isAccessible:  this is a new kind of access
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1292
            return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1293
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1294
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1295
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1296
         * Produces a method handle for a reflected constructor.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1297
         * The type of the method handle will be that of the constructor,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1298
         * with the return type changed to the declaring class.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1299
         * The method handle will perform a {@code newInstance} operation,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1300
         * creating a new instance of the constructor's class on the
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1301
         * arguments passed to the method handle.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1302
         * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1303
         * If the constructor's {@code accessible} flag is not set,
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1304
         * access checking is performed immediately on behalf of the lookup class.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1305
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1306
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1307
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1308
         * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1309
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1310
         * If the returned method handle is invoked, the constructor's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1311
         * be initialized, if it has not already been initialized.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1312
         * @param c the reflected constructor
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1313
         * @return a method handle which can invoke the reflected constructor
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1314
         * @throws IllegalAccessException if access checking fails
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1315
         *                                or if the method's variable arity modifier bit
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1316
         *                                is set and {@code asVarargsCollector} fails
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1317
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1318
         */
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1319
        public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1320
            MemberName ctor = new MemberName(c);
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1321
            assert(ctor.isConstructor());
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1322
            Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1323
            return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1324
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1325
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1326
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1327
         * Produces a method handle giving read access to a reflected field.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1328
         * The type of the method handle will have a return type of the field's
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1329
         * value type.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1330
         * If the field is static, the method handle will take no arguments.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1331
         * Otherwise, its single argument will be the instance containing
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1332
         * the field.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  1333
         * If the field's {@code accessible} flag is not set,
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1334
         * access checking is performed immediately on behalf of the lookup class.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1335
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1336
         * If the field is static, and
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1337
         * if the returned method handle is invoked, the field's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1338
         * be initialized, if it has not already been initialized.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1339
         * @param f the reflected field
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1340
         * @return a method handle which can load values from the reflected field
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1341
         * @throws IllegalAccessException if access checking fails
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1342
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1343
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1344
        public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1345
            return unreflectField(f, false);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1346
        }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1347
        private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1348
            MemberName field = new MemberName(f, isSetter);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1349
            assert(isSetter
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1350
                    ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1351
                    : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1352
            Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1353
            return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1354
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1355
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1356
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1357
         * Produces a method handle giving write access to a reflected field.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1358
         * The type of the method handle will have a void return type.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1359
         * If the field is static, the method handle will take a single
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1360
         * argument, of the field's value type, the value to be stored.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1361
         * Otherwise, the two arguments will be the instance containing
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1362
         * the field, and the value to be stored.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  1363
         * If the field's {@code accessible} flag is not set,
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1364
         * access checking is performed immediately on behalf of the lookup class.
20532
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1365
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1366
         * If the field is static, and
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1367
         * if the returned method handle is invoked, the field's class will
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1368
         * be initialized, if it has not already been initialized.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1369
         * @param f the reflected field
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1370
         * @return a method handle which can store values into the reflected field
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1371
         * @throws IllegalAccessException if access checking fails
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1372
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1373
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1374
        public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1375
            return unreflectField(f, true);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1376
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1377
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1378
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1379
         * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1380
         * created by this lookup object or a similar one.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1381
         * Security and access checks are performed to ensure that this lookup object
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1382
         * is capable of reproducing the target method handle.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1383
         * This means that the cracking may fail if target is a direct method handle
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1384
         * but was created by an unrelated lookup object.
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1385
         * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1386
         * and was created by a lookup object for a different class.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1387
         * @param target a direct method handle to crack into symbolic reference components
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1388
         * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1389
         * @exception SecurityException if a security manager is present and it
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1390
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1391
         * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1392
         * @exception NullPointerException if the target is {@code null}
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1393
         * @see MethodHandleInfo
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1394
         * @since 1.8
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1395
         */
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1396
        public MethodHandleInfo revealDirect(MethodHandle target) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1397
            MemberName member = target.internalMemberName();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1398
            if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke()))
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1399
                throw newIllegalArgumentException("not a direct method handle");
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1400
            Class<?> defc = member.getDeclaringClass();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1401
            byte refKind = member.getReferenceKind();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1402
            assert(MethodHandleNatives.refKindIsValid(refKind));
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1403
            if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1404
                // Devirtualized method invocation is usually formally virtual.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1405
                // To avoid creating extra MemberName objects for this common case,
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1406
                // we encode this extra degree of freedom using MH.isInvokeSpecial.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1407
                refKind = REF_invokeVirtual;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1408
            if (refKind == REF_invokeVirtual && defc.isInterface())
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1409
                // Symbolic reference is through interface but resolves to Object method (toString, etc.)
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1410
                refKind = REF_invokeInterface;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1411
            // Check SM permissions and member access before cracking.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1412
            try {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1413
                checkAccess(refKind, defc, member);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1414
                checkSecurityManager(defc, member);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1415
            } catch (IllegalAccessException ex) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1416
                throw new IllegalArgumentException(ex);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1417
            }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1418
            if (allowedModes != TRUSTED && member.isCallerSensitive()) {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1419
                Class<?> callerClass = target.internalCallerClass();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1420
                if (!hasPrivateAccess() || callerClass != lookupClass())
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1421
                    throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1422
            }
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1423
            // Produce the handle to the results.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1424
            return new InfoFromMemberName(this, member, refKind);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1425
        }
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1426
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1427
        /// Helper methods, all package-private.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1428
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1429
        MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1430
            checkSymbolicClass(refc);  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1431
            Objects.requireNonNull(name);
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1432
            Objects.requireNonNull(type);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1433
            return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1434
                                            NoSuchFieldException.class);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1435
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1436
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1437
        MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1438
            checkSymbolicClass(refc);  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1439
            Objects.requireNonNull(name);
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1440
            Objects.requireNonNull(type);
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1441
            checkMethodName(refKind, name);  // NPE check on name
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1442
            return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1443
                                            NoSuchMethodException.class);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1444
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1445
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1446
        MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1447
            checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1448
            Objects.requireNonNull(member.getName());
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1449
            Objects.requireNonNull(member.getType());
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1450
            return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1451
                                            ReflectiveOperationException.class);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1452
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1453
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1454
        void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1455
            Objects.requireNonNull(refc);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1456
            Class<?> caller = lookupClassOrNull();
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
  1457
            if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1458
                throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1459
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1460
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1461
        /** Check name for an illegal leading "&lt;" character. */
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1462
        void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1463
            if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1464
                throw new NoSuchMethodException("illegal method name: "+name);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1465
        }
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1466
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1467
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1468
        /**
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1469
         * Find my trustable caller class if m is a caller sensitive method.
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1470
         * If this lookup object has private access, then the caller class is the lookupClass.
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1471
         * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1472
         */
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1473
        Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1474
            Class<?> callerClass = null;
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1475
            if (MethodHandleNatives.isCallerSensitive(m)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1476
                // Only lookups with private access are allowed to resolve caller-sensitive methods
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1477
                if (hasPrivateAccess()) {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1478
                    callerClass = lookupClass;
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1479
                } else {
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1480
                    throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1481
                }
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1482
            }
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1483
            return callerClass;
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1484
        }
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1485
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1486
        private boolean hasPrivateAccess() {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1487
            return (allowedModes & PRIVATE) != 0;
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1488
        }
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1489
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1490
        /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1491
         * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1492
         * Determines a trustable caller class to compare with refc, the symbolic reference class.
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1493
         * If this lookup object has private access, then the caller class is the lookupClass.
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1494
         */
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1495
        void checkSecurityManager(Class<?> refc, MemberName m) {
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1496
            SecurityManager smgr = System.getSecurityManager();
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1497
            if (smgr == null)  return;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1498
            if (allowedModes == TRUSTED)  return;
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1499
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1500
            // Step 1:
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1501
            boolean fullPowerLookup = hasPrivateAccess();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1502
            if (!fullPowerLookup ||
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1503
                !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1504
                ReflectUtil.checkPackageAccess(refc);
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1505
            }
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1506
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1507
            if (m == null) {  // findClass or accessClass
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1508
                // Step 2b:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1509
                if (!fullPowerLookup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1510
                    smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1511
                }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1512
                return;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1513
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1514
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1515
            // Step 2a:
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1516
            if (m.isPublic()) return;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1517
            if (!fullPowerLookup) {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1518
                smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1519
            }
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1520
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
  1521
            // Step 3:
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1522
            Class<?> defc = m.getDeclaringClass();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1523
            if (!fullPowerLookup && defc != refc) {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1524
                ReflectUtil.checkPackageAccess(defc);
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1525
            }
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1526
        }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1527
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1528
        void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1529
            boolean wantStatic = (refKind == REF_invokeStatic);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1530
            String message;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1531
            if (m.isConstructor())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1532
                message = "expected a method, not a constructor";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1533
            else if (!m.isMethod())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1534
                message = "expected a method";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1535
            else if (wantStatic != m.isStatic())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1536
                message = wantStatic ? "expected a static method" : "expected a non-static method";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1537
            else
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1538
                { checkAccess(refKind, refc, m); return; }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1539
            throw m.makeAccessException(message, this);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1540
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1541
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1542
        void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1543
            boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1544
            String message;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1545
            if (wantStatic != m.isStatic())
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1546
                message = wantStatic ? "expected a static field" : "expected a non-static field";
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1547
            else
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1548
                { checkAccess(refKind, refc, m); return; }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1549
            throw m.makeAccessException(message, this);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1550
        }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1551
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1552
        /** Check public/protected/private bits on the symbolic reference class and its member. */
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1553
        void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1554
            assert(m.referenceKindIsConsistentWith(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1555
                   MethodHandleNatives.refKindIsValid(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1556
                   (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1557
            int allowedModes = this.allowedModes;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1558
            if (allowedModes == TRUSTED)  return;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1559
            int mods = m.getModifiers();
20528
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1560
            if (Modifier.isProtected(mods) &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1561
                    refKind == REF_invokeVirtual &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1562
                    m.getDeclaringClass() == Object.class &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1563
                    m.getName().equals("clone") &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1564
                    refc.isArray()) {
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1565
                // The JVM does this hack also.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1566
                // (See ClassVerifier::verify_invoke_instructions
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1567
                // and LinkResolver::check_method_accessability.)
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1568
                // Because the JVM does not allow separate methods on array types,
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1569
                // there is no separate method for int[].clone.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1570
                // All arrays simply inherit Object.clone.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1571
                // But for access checking logic, we make Object.clone
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1572
                // (normally protected) appear to be public.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1573
                // Later on, when the DirectMethodHandle is created,
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1574
                // its leading argument will be restricted to the
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1575
                // requested array type.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1576
                // N.B. The return type is not adjusted, because
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1577
                // that is *not* the bytecode behavior.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1578
                mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1579
            }
25537
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1580
            if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1581
                // cannot "new" a protected ctor in a different package
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1582
                mods ^= Modifier.PROTECTED;
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1583
            }
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1584
            if (Modifier.isFinal(mods) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1585
                    MethodHandleNatives.refKindIsSetter(refKind))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1586
                throw m.makeAccessException("unexpected set of a final field", this);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1587
            if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1588
                return;  // common case
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1589
            int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1590
            if ((requestedModes & allowedModes) != 0) {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1591
                if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1592
                                                    mods, lookupClass(), allowedModes))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1593
                    return;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1594
            } else {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1595
                // Protected members can also be checked as if they were package-private.
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1596
                if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1597
                        && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1598
                    return;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1599
            }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1600
            throw m.makeAccessException(accessFailedMessage(refc, m), this);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1601
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1602
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1603
        String accessFailedMessage(Class<?> refc, MemberName m) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1604
            Class<?> defc = m.getDeclaringClass();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1605
            int mods = m.getModifiers();
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1606
            // check the class first:
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1607
            boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1608
                               (defc == refc ||
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1609
                                Modifier.isPublic(refc.getModifiers())));
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1610
            if (!classOK && (allowedModes & PACKAGE) != 0) {
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
  1611
                classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1612
                           (defc == refc ||
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
  1613
                            VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1614
            }
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1615
            if (!classOK)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1616
                return "class is not public";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1617
            if (Modifier.isPublic(mods))
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1618
                return "access to public member failed";  // (how?)
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1619
            if (Modifier.isPrivate(mods))
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1620
                return "member is private";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1621
            if (Modifier.isProtected(mods))
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1622
                return "member is protected";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1623
            return "member is private to package";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1624
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1625
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1626
        private static final boolean ALLOW_NESTMATE_ACCESS = false;
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1627
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1628
        private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1629
            int allowedModes = this.allowedModes;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1630
            if (allowedModes == TRUSTED)  return;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1631
            if (!hasPrivateAccess()
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1632
                || (specialCaller != lookupClass()
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1633
                       // ensure non-abstract methods in superinterfaces can be special-invoked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1634
                    && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1635
                    && !(ALLOW_NESTMATE_ACCESS &&
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1636
                         VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1637
                throw new MemberName(specialCaller).
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1638
                    makeAccessException("no private access for invokespecial", this);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1639
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1640
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1641
        private boolean restrictProtectedReceiver(MemberName method) {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1642
            // The accessing class only has the right to use a protected member
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1643
            // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1644
            if (!method.isProtected() || method.isStatic()
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1645
                || allowedModes == TRUSTED
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1646
                || method.getDeclaringClass() == lookupClass()
9731
d0f7a3e441c4 7044892: JSR 292: API entry points sometimes throw the wrong exceptions or doesn't throw the expected one
jrose
parents: 9730
diff changeset
  1647
                || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1648
                || (ALLOW_NESTMATE_ACCESS &&
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1649
                    VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1650
                return false;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1651
            return true;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1652
        }
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1653
        private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1654
            assert(!method.isStatic());
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1655
            // receiver type of mh is too wide; narrow to caller
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1656
            if (!method.getDeclaringClass().isAssignableFrom(caller)) {
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1657
                throw method.makeAccessException("caller class must be a subclass below the method", caller);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1658
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1659
            MethodType rawType = mh.type();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1660
            if (rawType.parameterType(0) == caller)  return mh;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1661
            MethodType narrowType = rawType.changeParameterType(0, caller);
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1662
            assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1663
            assert(mh.viewAsTypeChecks(narrowType, true));
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1664
            return mh.copyWith(narrowType, mh.form);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1665
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1666
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1667
        /** Check access and get the requested method. */
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1668
        private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1669
            final boolean doRestrict    = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1670
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1671
            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1672
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1673
        /** Check access and get the requested method, eliding receiver narrowing rules. */
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1674
        private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1675
            final boolean doRestrict    = false;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1676
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1677
            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1678
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1679
        /** Check access and get the requested method, eliding security manager checks. */
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1680
        private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1681
            final boolean doRestrict    = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1682
            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1683
            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1684
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1685
        /** Common code for all methods; do not call directly except from immediately above. */
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1686
        private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1687
                                                   boolean checkSecurity,
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1688
                                                   boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1689
            checkMethod(refKind, refc, method);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1690
            // Optionally check with the security manager; this isn't needed for unreflect* calls.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1691
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1692
                checkSecurityManager(refc, method);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1693
            assert(!method.isMethodHandleInvoke());
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1694
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1695
            if (refKind == REF_invokeSpecial &&
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1696
                refc != lookupClass() &&
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1697
                !refc.isInterface() &&
24860
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1698
                refc != lookupClass().getSuperclass() &&
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1699
                refc.isAssignableFrom(lookupClass())) {
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1700
                assert(!method.getName().equals("<init>"));  // not this code path
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1701
                // Per JVMS 6.5, desc. of invokespecial instruction:
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1702
                // If the method is in a superclass of the LC,
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1703
                // and if our original search was above LC.super,
24860
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1704
                // repeat the search (symbolic lookup) from LC.super
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1705
                // and continue with the direct superclass of that class,
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1706
                // and so forth, until a match is found or no further superclasses exist.
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1707
                // FIXME: MemberName.resolve should handle this instead.
24860
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1708
                Class<?> refcAsSuper = lookupClass();
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1709
                MemberName m2;
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1710
                do {
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1711
                    refcAsSuper = refcAsSuper.getSuperclass();
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1712
                    m2 = new MemberName(refcAsSuper,
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1713
                                        method.getName(),
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1714
                                        method.getMethodType(),
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1715
                                        REF_invokeSpecial);
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1716
                    m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1717
                } while (m2 == null &&         // no method is found yet
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1718
                         refc != refcAsSuper); // search up to refc
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1719
                if (m2 == null)  throw new InternalError(method.toString());
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1720
                method = m2;
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1721
                refc = refcAsSuper;
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1722
                // redo basic checks
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1723
                checkMethod(refKind, refc, method);
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1724
            }
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1725
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1726
            DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1727
            MethodHandle mh = dmh;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1728
            // Optionally narrow the receiver argument to refc using restrictReceiver.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1729
            if (doRestrict &&
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1730
                   (refKind == REF_invokeSpecial ||
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1731
                       (MethodHandleNatives.refKindHasReceiver(refKind) &&
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1732
                           restrictProtectedReceiver(method)))) {
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1733
                mh = restrictReceiver(method, dmh, lookupClass());
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1734
            }
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1735
            mh = maybeBindCaller(method, mh, callerClass);
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1736
            mh = mh.setVarargs(method);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1737
            return mh;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1738
        }
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1739
        private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1740
                                             Class<?> callerClass)
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1741
                                             throws IllegalAccessException {
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1742
            if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1743
                return mh;
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1744
            Class<?> hostClass = lookupClass;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1745
            if (!hasPrivateAccess())  // caller must have private access
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1746
                hostClass = callerClass;  // callerClass came from a security manager style stack walk
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1747
            MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1748
            // Note: caller will apply varargs after this step happens.
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1749
            return cbmh;
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1750
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1751
        /** Check access and get the requested field. */
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1752
        private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1753
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1754
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1755
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1756
        /** Check access and get the requested field, eliding security manager checks. */
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1757
        private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1758
            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1759
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1760
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1761
        /** Common code for all fields; do not call directly except from immediately above. */
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1762
        private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1763
                                                  boolean checkSecurity) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1764
            checkField(refKind, refc, field);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1765
            // Optionally check with the security manager; this isn't needed for unreflect* calls.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1766
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1767
                checkSecurityManager(refc, field);
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1768
            DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1769
            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1770
                                    restrictProtectedReceiver(field));
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1771
            if (doRestrict)
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1772
                return restrictReceiver(field, dmh, lookupClass());
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1773
            return dmh;
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1774
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1775
        /** Check access and get the requested constructor. */
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1776
        private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1777
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1778
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1779
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1780
        /** Check access and get the requested constructor, eliding security manager checks. */
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1781
        private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1782
            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1783
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1784
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1785
        /** Common code for all constructors; do not call directly except from immediately above. */
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1786
        private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1787
                                                  boolean checkSecurity) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1788
            assert(ctor.isConstructor());
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1789
            checkAccess(REF_newInvokeSpecial, refc, ctor);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1790
            // Optionally check with the security manager; this isn't needed for unreflect* calls.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1791
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1792
                checkSecurityManager(refc, ctor);
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1793
            assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1794
            return DirectMethodHandle.make(ctor).setVarargs(ctor);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1795
        }
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1796
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1797
        /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1798
         */
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1799
        /*non-public*/
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1800
        MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1801
            if (!(type instanceof Class || type instanceof MethodType))
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1802
                throw new InternalError("unresolved MemberName");
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1803
            MemberName member = new MemberName(refKind, defc, name, type);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1804
            MethodHandle mh = LOOKASIDE_TABLE.get(member);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1805
            if (mh != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1806
                checkSymbolicClass(defc);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1807
                return mh;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1808
            }
21362
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  1809
            // Treat MethodHandle.invoke and invokeExact specially.
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  1810
            if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  1811
                mh = findVirtualForMH(member.getName(), member.getMethodType());
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  1812
                if (mh != null) {
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  1813
                    return mh;
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  1814
                }
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  1815
            }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1816
            MemberName resolved = resolveOrFail(refKind, member);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1817
            mh = getDirectMethodForConstant(refKind, defc, resolved);
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1818
            if (mh instanceof DirectMethodHandle
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1819
                    && canBeCached(refKind, defc, resolved)) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1820
                MemberName key = mh.internalMemberName();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1821
                if (key != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1822
                    key = key.asNormalOriginal();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1823
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1824
                if (member.equals(key)) {  // better safe than sorry
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1825
                    LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1826
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1827
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1828
            return mh;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1829
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1830
        private
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1831
        boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1832
            if (refKind == REF_invokeSpecial) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1833
                return false;
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1834
            }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1835
            if (!Modifier.isPublic(defc.getModifiers()) ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1836
                    !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1837
                    !member.isPublic() ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1838
                    member.isCallerSensitive()) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1839
                return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1840
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1841
            ClassLoader loader = defc.getClassLoader();
34882
ce2a8ec851c1 8145544: Move sun.misc.VM to jdk.internal.misc
chegar
parents: 34720
diff changeset
  1842
            if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1843
                ClassLoader sysl = ClassLoader.getSystemClassLoader();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1844
                boolean found = false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1845
                while (sysl != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1846
                    if (loader == sysl) { found = true; break; }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1847
                    sysl = sysl.getParent();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1848
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1849
                if (!found) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1850
                    return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1851
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1852
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1853
            try {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1854
                MemberName resolved2 = publicLookup().resolveOrFail(refKind,
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1855
                    new MemberName(refKind, defc, member.getName(), member.getType()));
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1856
                checkSecurityManager(defc, resolved2);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1857
            } catch (ReflectiveOperationException | SecurityException ex) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1858
                return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1859
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1860
            return true;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1861
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1862
        private
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1863
        MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1864
                throws ReflectiveOperationException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1865
            if (MethodHandleNatives.refKindIsField(refKind)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1866
                return getDirectFieldNoSecurityManager(refKind, defc, member);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1867
            } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1868
                return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1869
            } else if (refKind == REF_newInvokeSpecial) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1870
                return getDirectConstructorNoSecurityManager(defc, member);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1871
            }
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1872
            // oops
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1873
            throw newIllegalArgumentException("bad MethodHandle constant #"+member);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1874
        }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1875
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1876
        static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1877
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1878
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1879
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1880
     * Produces a method handle giving read access to elements of an array.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1881
     * The type of the method handle will have a return type of the array's
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1882
     * element type.  Its first argument will be the array type,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1883
     * and the second will be {@code int}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1884
     * @param arrayClass an array type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1885
     * @return a method handle which can load values from the given array type
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1886
     * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1887
     * @throws  IllegalArgumentException if arrayClass is not an array type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1888
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1889
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1890
    MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1891
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1892
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1893
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1894
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1895
     * Produces a method handle giving write access to elements of an array.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1896
     * The type of the method handle will have a void return type.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1897
     * Its last argument will be the array's element type.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1898
     * The first and second arguments will be the array type and int.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  1899
     * @param arrayClass the class of an array
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1900
     * @return a method handle which can store values into the array type
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1901
     * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1902
     * @throws IllegalArgumentException if arrayClass is not an array type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1903
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1904
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1905
    MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1906
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1907
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1908
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1909
    /// method handle invocation (reflective style)
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1910
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1911
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1912
     * Produces a method handle which will invoke any method handle of the
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1913
     * given {@code type}, with a given number of trailing arguments replaced by
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1914
     * a single trailing {@code Object[]} array.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1915
     * The resulting invoker will be a method handle with the following
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1916
     * arguments:
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1917
     * <ul>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1918
     * <li>a single {@code MethodHandle} target
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1919
     * <li>zero or more leading values (counted by {@code leadingArgCount})
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1920
     * <li>an {@code Object[]} array containing trailing arguments
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1921
     * </ul>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1922
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1923
     * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1924
     * the indicated {@code type}.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1925
     * That is, if the target is exactly of the given {@code type}, it will behave
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1926
     * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1927
     * is used to convert the target to the required {@code type}.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1928
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1929
     * The type of the returned invoker will not be the given {@code type}, but rather
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1930
     * will have all parameters except the first {@code leadingArgCount}
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1931
     * replaced by a single array of type {@code Object[]}, which will be
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1932
     * the final parameter.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1933
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1934
     * Before invoking its target, the invoker will spread the final array, apply
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1935
     * reference casts as necessary, and unbox and widen primitive arguments.
20530
b54a1f5cd35f 8001109: arity mismatch on a call to spreader method handle should elicit IllegalArgumentException
jrose
parents: 20529
diff changeset
  1936
     * If, when the invoker is called, the supplied array argument does
b54a1f5cd35f 8001109: arity mismatch on a call to spreader method handle should elicit IllegalArgumentException
jrose
parents: 20529
diff changeset
  1937
     * not have the correct number of elements, the invoker will throw
b54a1f5cd35f 8001109: arity mismatch on a call to spreader method handle should elicit IllegalArgumentException
jrose
parents: 20529
diff changeset
  1938
     * an {@link IllegalArgumentException} instead of invoking the target.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1939
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1940
     * This method is equivalent to the following code (though it may be more efficient):
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1941
     * <blockquote><pre>{@code
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  1942
MethodHandle invoker = MethodHandles.invoker(type);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1943
int spreadArgCount = type.parameterCount() - leadingArgCount;
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1944
invoker = invoker.asSpreader(Object[].class, spreadArgCount);
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1945
return invoker;
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1946
     * }</pre></blockquote>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1947
     * This method throws no reflective or security exceptions.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1948
     * @param type the desired target type
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1949
     * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1950
     * @return a method handle suitable for invoking any method handle of the given type
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1951
     * @throws NullPointerException if {@code type} is null
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1952
     * @throws IllegalArgumentException if {@code leadingArgCount} is not in
20529
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  1953
     *                  the range from 0 to {@code type.parameterCount()} inclusive,
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  1954
     *                  or if the resulting method handle's type would have
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  1955
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1956
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  1957
    public static
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1958
    MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1959
        if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
  1960
            throw newIllegalArgumentException("bad argument count", leadingArgCount);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1961
        type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1962
        return type.invokers().spreadInvoker(leadingArgCount);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1963
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1964
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1965
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1966
     * Produces a special <em>invoker method handle</em> which can be used to
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  1967
     * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1968
     * The resulting invoker will have a type which is
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1969
     * exactly equal to the desired type, except that it will accept
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1970
     * an additional leading argument of type {@code MethodHandle}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1971
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1972
     * This method is equivalent to the following code (though it may be more efficient):
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1973
     * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1974
     *
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1975
     * <p style="font-size:smaller;">
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1976
     * <em>Discussion:</em>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1977
     * Invoker method handles can be useful when working with variable method handles
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1978
     * of unknown types.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1979
     * For example, to emulate an {@code invokeExact} call to a variable method
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1980
     * handle {@code M}, extract its type {@code T},
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1981
     * look up the invoker method {@code X} for {@code T},
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  1982
     * and call the invoker method, as {@code X.invoke(T, A...)}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1983
     * (It would not work to call {@code X.invokeExact}, since the type {@code T}
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1984
     * is unknown.)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1985
     * If spreading, collecting, or other argument transformations are required,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1986
     * they can be applied once to the invoker {@code X} and reused on many {@code M}
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1987
     * method handle values, as long as they are compatible with the type of {@code X}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1988
     * <p style="font-size:smaller;">
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1989
     * <em>(Note:  The invoker method is not available via the Core Reflection API.
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1990
     * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  1991
     * on the declared {@code invokeExact} or {@code invoke} method will raise an
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1992
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1993
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1994
     * This method throws no reflective or security exceptions.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1995
     * @param type the desired target type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1996
     * @return a method handle suitable for invoking any method handle of the given type
20529
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  1997
     * @throws IllegalArgumentException if the resulting method handle's type would have
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  1998
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1999
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2000
    public static
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2001
    MethodHandle exactInvoker(MethodType type) {
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2002
        return type.invokers().exactInvoker();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2003
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2004
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2005
    /**
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2006
     * Produces a special <em>invoker method handle</em> which can be used to
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2007
     * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2008
     * The resulting invoker will have a type which is
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2009
     * exactly equal to the desired type, except that it will accept
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2010
     * an additional leading argument of type {@code MethodHandle}.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2011
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2012
     * Before invoking its target, if the target differs from the expected type,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2013
     * the invoker will apply reference casts as
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2014
     * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2015
     * Similarly, the return value will be converted as necessary.
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2016
     * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2017
     * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2018
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2019
     * This method is equivalent to the following code (though it may be more efficient):
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2020
     * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2021
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2022
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2023
     * A {@linkplain MethodType#genericMethodType general method type} is one which
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2024
     * mentions only {@code Object} arguments and return values.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2025
     * An invoker for such a type is capable of calling any method handle
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2026
     * of the same arity as the general type.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2027
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2028
     * <em>(Note:  The invoker method is not available via the Core Reflection API.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2029
     * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2030
     * on the declared {@code invokeExact} or {@code invoke} method will raise an
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2031
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2032
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2033
     * This method throws no reflective or security exceptions.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2034
     * @param type the desired target type
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2035
     * @return a method handle suitable for invoking any method handle convertible to the given type
20529
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  2036
     * @throws IllegalArgumentException if the resulting method handle's type would have
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  2037
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2038
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2039
    public static
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2040
    MethodHandle invoker(MethodType type) {
26468
2d57604f9299 8050053: Improve caching of different invokers
vlivanov
parents: 26467
diff changeset
  2041
        return type.invokers().genericInvoker();
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2042
    }
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2043
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2044
    static /*non-public*/
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2045
    MethodHandle basicInvoker(MethodType type) {
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
  2046
        return type.invokers().basicInvoker();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2047
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2048
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2049
     /// method handle modification (creation from other method handles)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2050
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2051
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2052
     * Produces a method handle which adapts the type of the
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2053
     * given method handle to a new type by pairwise argument and return type conversion.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2054
     * The original type and new type must have the same number of arguments.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2055
     * The resulting method handle is guaranteed to report a type
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2056
     * which is equal to the desired new type.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2057
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2058
     * If the original type and new type are equal, returns target.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2059
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2060
     * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2061
     * and some additional conversions are also applied if those conversions fail.
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2062
     * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2063
     * if possible, before or instead of any conversions done by {@code asType}:
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2064
     * <ul>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2065
     * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2066
     *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2067
     *     (This treatment of interfaces follows the usage of the bytecode verifier.)
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2068
     * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2069
     *     the boolean is converted to a byte value, 1 for true, 0 for false.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2070
     *     (This treatment follows the usage of the bytecode verifier.)
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2071
     * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2072
     *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2073
     *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2074
     * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2075
     *     then a Java casting conversion (JLS 5.5) is applied.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2076
     *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2077
     *     widening and/or narrowing.)
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2078
     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2079
     *     conversion will be applied at runtime, possibly followed
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2080
     *     by a Java casting conversion (JLS 5.5) on the primitive value,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2081
     *     possibly followed by a conversion from byte to boolean by testing
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2082
     *     the low-order bit.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2083
     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2084
     *     and if the reference is null at runtime, a zero value is introduced.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2085
     * </ul>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2086
     * @param target the method handle to invoke after arguments are retyped
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2087
     * @param newType the expected type of the new method handle
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2088
     * @return a method handle which delegates to the target after performing
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2089
     *           any necessary argument conversions, and arranges for any
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2090
     *           necessary return value conversions
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2091
     * @throws NullPointerException if either argument is null
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2092
     * @throws WrongMethodTypeException if the conversion cannot be made
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2093
     * @see MethodHandle#asType
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2094
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2095
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2096
    MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2097
        explicitCastArgumentsChecks(target, newType);
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2098
        // use the asTypeCache when possible:
26478
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  2099
        MethodType oldType = target.type();
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  2100
        if (oldType == newType)  return target;
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  2101
        if (oldType.explicitCastEquivalentToAsType(newType)) {
27947
dba3bc0c087e 8066746: MHs.explicitCastArguments does incorrect type checks for VarargsCollector
vlivanov
parents: 27755
diff changeset
  2102
            return target.asFixedArity().asType(newType);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2103
        }
26474
655d08549e43 8050877: Improve code for pairwise argument conversions and value boxing/unboxing
vlivanov
parents: 26470
diff changeset
  2104
        return MethodHandleImpl.makePairwiseConvert(target, newType, false);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2105
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2106
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2107
    private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2108
        if (target.type().parameterCount() != newType.parameterCount()) {
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2109
            throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2110
        }
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2111
    }
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2112
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2113
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2114
     * Produces a method handle which adapts the calling sequence of the
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2115
     * given method handle to a new type, by reordering the arguments.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2116
     * The resulting method handle is guaranteed to report a type
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2117
     * which is equal to the desired new type.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2118
     * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2119
     * The given array controls the reordering.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2120
     * Call {@code #I} the number of incoming parameters (the value
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2121
     * {@code newType.parameterCount()}, and call {@code #O} the number
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2122
     * of outgoing parameters (the value {@code target.type().parameterCount()}).
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2123
     * Then the length of the reordering array must be {@code #O},
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2124
     * and each element must be a non-negative number less than {@code #I}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2125
     * For every {@code N} less than {@code #O}, the {@code N}-th
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2126
     * outgoing argument will be taken from the {@code I}-th incoming
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2127
     * argument, where {@code I} is {@code reorder[N]}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2128
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2129
     * No argument or return value conversions are applied.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2130
     * The type of each incoming argument, as determined by {@code newType},
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2131
     * must be identical to the type of the corresponding outgoing parameter
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2132
     * or parameters in the target method handle.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2133
     * The return type of {@code newType} must be identical to the return
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2134
     * type of the original target.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2135
     * <p>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2136
     * The reordering array need not specify an actual permutation.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2137
     * An incoming argument will be duplicated if its index appears
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2138
     * more than once in the array, and an incoming argument will be dropped
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2139
     * if its index does not appear in the array.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2140
     * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2141
     * incoming arguments which are not mentioned in the reordering array
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2142
     * may be of any type, as determined only by {@code newType}.
18156
edb590d448c5 8016217: More javadoc warnings
alanb
parents: 16906
diff changeset
  2143
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2144
import static java.lang.invoke.MethodHandles.*;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2145
import static java.lang.invoke.MethodType.*;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2146
...
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2147
MethodType intfn1 = methodType(int.class, int.class);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2148
MethodType intfn2 = methodType(int.class, int.class, int.class);
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  2149
MethodHandle sub = ... (int x, int y) -> (x-y) ...;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2150
assert(sub.type().equals(intfn2));
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2151
MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2152
MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2153
assert((int)rsub.invokeExact(1, 100) == 99);
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  2154
MethodHandle add = ... (int x, int y) -> (x+y) ...;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2155
assert(add.type().equals(intfn2));
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2156
MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2157
assert(twice.type().equals(intfn1));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2158
assert((int)twice.invokeExact(21) == 42);
18156
edb590d448c5 8016217: More javadoc warnings
alanb
parents: 16906
diff changeset
  2159
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2160
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2161
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2162
     * variable-arity method handle}, even if the original target method handle was.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2163
     * @param target the method handle to invoke after arguments are reordered
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2164
     * @param newType the expected type of the new method handle
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2165
     * @param reorder an index array which controls the reordering
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2166
     * @return a method handle which delegates to the target after it
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2167
     *           drops unused arguments and moves and/or duplicates the other arguments
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2168
     * @throws NullPointerException if any argument is null
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2169
     * @throws IllegalArgumentException if the index array length is not equal to
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2170
     *                  the arity of the target, or if any index array element
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2171
     *                  not a valid index for a parameter of {@code newType},
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2172
     *                  or if two corresponding parameter types in
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2173
     *                  {@code target.type()} and {@code newType} are not identical,
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2174
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2175
    public static
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2176
    MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2177
        reorder = reorder.clone();  // get a private copy
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2178
        MethodType oldType = target.type();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2179
        permuteArgumentChecks(reorder, newType, oldType);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2180
        // first detect dropped arguments and handle them separately
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2181
        int[] originalReorder = reorder;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2182
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2183
        LambdaForm form = result.form;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2184
        int newArity = newType.parameterCount();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2185
        // Normalize the reordering into a real permutation,
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2186
        // by removing duplicates and adding dropped elements.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2187
        // This somewhat improves lambda form caching, as well
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2188
        // as simplifying the transform by breaking it up into steps.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2189
        for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2190
            if (ddIdx > 0) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2191
                // We found a duplicated entry at reorder[ddIdx].
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2192
                // Example:  (x,y,z)->asList(x,y,z)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2193
                // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2194
                // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2195
                // The starred element corresponds to the argument
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2196
                // deleted by the dupArgumentForm transform.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2197
                int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2198
                boolean killFirst = false;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2199
                for (int val; (val = reorder[--dstPos]) != dupVal; ) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2200
                    // Set killFirst if the dup is larger than an intervening position.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2201
                    // This will remove at least one inversion from the permutation.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2202
                    if (dupVal > val) killFirst = true;
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2203
                }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2204
                if (!killFirst) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2205
                    srcPos = dstPos;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2206
                    dstPos = ddIdx;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2207
                }
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2208
                form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2209
                assert (reorder[srcPos] == reorder[dstPos]);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2210
                oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2211
                // contract the reordering by removing the element at dstPos
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2212
                int tailPos = dstPos + 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2213
                System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2214
                reorder = Arrays.copyOf(reorder, reorder.length - 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2215
            } else {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2216
                int dropVal = ~ddIdx, insPos = 0;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2217
                while (insPos < reorder.length && reorder[insPos] < dropVal) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2218
                    // Find first element of reorder larger than dropVal.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2219
                    // This is where we will insert the dropVal.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2220
                    insPos += 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2221
                }
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2222
                Class<?> ptype = newType.parameterType(dropVal);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2223
                form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2224
                oldType = oldType.insertParameterTypes(insPos, ptype);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2225
                // expand the reordering by inserting an element at insPos
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2226
                int tailPos = insPos + 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2227
                reorder = Arrays.copyOf(reorder, reorder.length + 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2228
                System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2229
                reorder[insPos] = dropVal;
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2230
            }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2231
            assert (permuteArgumentChecks(reorder, newType, oldType));
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2232
        }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2233
        assert (reorder.length == newArity);  // a perfect permutation
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2234
        // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2235
        form = form.editor().permuteArgumentsForm(1, reorder);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2236
        if (newType == result.type() && form == result.internalForm())
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2237
            return result;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2238
        return result.copyWith(newType, form);
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2239
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2240
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2241
    /**
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2242
     * Return an indication of any duplicate or omission in reorder.
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2243
     * If the reorder contains a duplicate entry, return the index of the second occurrence.
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2244
     * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2245
     * Otherwise, return zero.
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2246
     * If an element not in [0..newArity-1] is encountered, return reorder.length.
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2247
     */
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2248
    private static int findFirstDupOrDrop(int[] reorder, int newArity) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2249
        final int BIT_LIMIT = 63;  // max number of bits in bit mask
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2250
        if (newArity < BIT_LIMIT) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2251
            long mask = 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2252
            for (int i = 0; i < reorder.length; i++) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2253
                int arg = reorder[i];
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2254
                if (arg >= newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2255
                    return reorder.length;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2256
                }
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2257
                long bit = 1L << arg;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2258
                if ((mask & bit) != 0) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2259
                    return i;  // >0 indicates a dup
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2260
                }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2261
                mask |= bit;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2262
            }
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2263
            if (mask == (1L << newArity) - 1) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2264
                assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2265
                return 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2266
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2267
            // find first zero
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2268
            long zeroBit = Long.lowestOneBit(~mask);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2269
            int zeroPos = Long.numberOfTrailingZeros(zeroBit);
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2270
            assert(zeroPos <= newArity);
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2271
            if (zeroPos == newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2272
                return 0;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2273
            }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2274
            return ~zeroPos;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2275
        } else {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2276
            // same algorithm, different bit set
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2277
            BitSet mask = new BitSet(newArity);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2278
            for (int i = 0; i < reorder.length; i++) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2279
                int arg = reorder[i];
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2280
                if (arg >= newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2281
                    return reorder.length;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2282
                }
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2283
                if (mask.get(arg)) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2284
                    return i;  // >0 indicates a dup
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2285
                }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2286
                mask.set(arg);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2287
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2288
            int zeroPos = mask.nextClearBit(0);
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2289
            assert(zeroPos <= newArity);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2290
            if (zeroPos == newArity) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2291
                return 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2292
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2293
            return ~zeroPos;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2294
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2295
    }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2296
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2297
    private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2298
        if (newType.returnType() != oldType.returnType())
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2299
            throw newIllegalArgumentException("return types do not match",
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2300
                    oldType, newType);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2301
        if (reorder.length == oldType.parameterCount()) {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2302
            int limit = newType.parameterCount();
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2303
            boolean bad = false;
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2304
            for (int j = 0; j < reorder.length; j++) {
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2305
                int i = reorder[j];
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2306
                if (i < 0 || i >= limit) {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2307
                    bad = true; break;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2308
                }
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2309
                Class<?> src = newType.parameterType(i);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2310
                Class<?> dst = oldType.parameterType(j);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2311
                if (src != dst)
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2312
                    throw newIllegalArgumentException("parameter types do not match after reorder",
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2313
                            oldType, newType);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2314
            }
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2315
            if (!bad)  return true;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2316
        }
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2317
        throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2318
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2319
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2320
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2321
     * Produces a method handle of the requested return type which returns the given
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2322
     * constant value every time it is invoked.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2323
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2324
     * Before the method handle is returned, the passed-in value is converted to the requested type.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2325
     * If the requested type is primitive, widening primitive conversions are attempted,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2326
     * else reference conversions are attempted.
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2327
     * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2328
     * @param type the return type of the desired method handle
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2329
     * @param value the value to return
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2330
     * @return a method handle of the given return type and no arguments, which always returns the given value
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2331
     * @throws NullPointerException if the {@code type} argument is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2332
     * @throws ClassCastException if the value cannot be converted to the required return type
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2333
     * @throws IllegalArgumentException if the given type is {@code void.class}
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2334
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2335
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2336
    MethodHandle constant(Class<?> type, Object value) {
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2337
        if (type.isPrimitive()) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2338
            if (type == void.class)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2339
                throw newIllegalArgumentException("void type");
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2340
            Wrapper w = Wrapper.forPrimitiveType(type);
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2341
            value = w.convert(value, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2342
            if (w.zero().equals(value))
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2343
                return zero(w, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2344
            return insertArguments(identity(type), 0, value);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2345
        } else {
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2346
            if (value == null)
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2347
                return zero(Wrapper.OBJECT, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2348
            return identity(type).bindTo(value);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2349
        }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2350
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2351
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2352
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2353
     * Produces a method handle which returns its sole argument when invoked.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2354
     * @param type the type of the sole parameter and return value of the desired method handle
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2355
     * @return a unary method handle which accepts and returns the given type
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2356
     * @throws NullPointerException if the argument is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2357
     * @throws IllegalArgumentException if the given type is {@code void.class}
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2358
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2359
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2360
    MethodHandle identity(Class<?> type) {
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2361
        Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2362
        int pos = btw.ordinal();
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2363
        MethodHandle ident = IDENTITY_MHS[pos];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2364
        if (ident == null) {
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2365
            ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2366
        }
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2367
        if (ident.type().returnType() == type)
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2368
            return ident;
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2369
        // something like identity(Foo.class); do not bother to intern these
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2370
        assert(btw == Wrapper.OBJECT);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2371
        return makeIdentity(type);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2372
    }
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2373
    private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2374
    private static MethodHandle makeIdentity(Class<?> ptype) {
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2375
        MethodType mtype = MethodType.methodType(ptype, ptype);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2376
        LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2377
        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2378
    }
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2379
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2380
    private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2381
        int pos = btw.ordinal();
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2382
        MethodHandle zero = ZERO_MHS[pos];
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2383
        if (zero == null) {
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2384
            zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2385
        }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2386
        if (zero.type().returnType() == rtype)
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2387
            return zero;
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2388
        assert(btw == Wrapper.OBJECT);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2389
        return makeZero(rtype);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2390
    }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2391
    private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length];
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2392
    private static MethodHandle makeZero(Class<?> rtype) {
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2393
        MethodType mtype = MethodType.methodType(rtype);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2394
        LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2395
        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2396
    }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2397
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2398
    private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2399
        // Simulate a CAS, to avoid racy duplication of results.
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2400
        MethodHandle prev = cache[pos];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2401
        if (prev != null) return prev;
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2402
        return cache[pos] = value;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2403
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2404
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2405
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2406
     * Provides a target method handle with one or more <em>bound arguments</em>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2407
     * in advance of the method handle's invocation.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2408
     * The formal parameters to the target corresponding to the bound
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2409
     * arguments are called <em>bound parameters</em>.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2410
     * Returns a new method handle which saves away the bound arguments.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2411
     * When it is invoked, it receives arguments for any non-bound parameters,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2412
     * binds the saved arguments to their corresponding parameters,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2413
     * and calls the original target.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2414
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2415
     * The type of the new method handle will drop the types for the bound
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2416
     * parameters from the original target type, since the new method handle
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2417
     * will no longer require those arguments to be supplied by its callers.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2418
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2419
     * Each given argument object must match the corresponding bound parameter type.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2420
     * If a bound parameter type is a primitive, the argument object
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2421
     * must be a wrapper, and will be unboxed to produce the primitive value.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2422
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2423
     * The {@code pos} argument selects which parameters are to be bound.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2424
     * It may range between zero and <i>N-L</i> (inclusively),
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2425
     * where <i>N</i> is the arity of the target method handle
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2426
     * and <i>L</i> is the length of the values array.
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2427
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2428
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2429
     * variable-arity method handle}, even if the original target method handle was.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2430
     * @param target the method handle to invoke after the argument is inserted
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2431
     * @param pos where to insert the argument (zero for the first)
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2432
     * @param values the series of arguments to insert
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2433
     * @return a method handle which inserts an additional argument,
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2434
     *         before calling the original method handle
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2435
     * @throws NullPointerException if the target or the {@code values} array is null
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2436
     * @see MethodHandle#bindTo
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2437
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2438
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2439
    MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2440
        int insCount = values.length;
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2441
        Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2442
        if (insCount == 0)  return target;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2443
        BoundMethodHandle result = target.rebind();
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2444
        for (int i = 0; i < insCount; i++) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2445
            Object value = values[i];
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2446
            Class<?> ptype = ptypes[pos+i];
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2447
            if (ptype.isPrimitive()) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2448
                result = insertArgumentPrimitive(result, pos, ptype, value);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2449
            } else {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2450
                value = ptype.cast(value);  // throw CCE if needed
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2451
                result = result.bindArgumentL(pos, value);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2452
            }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2453
        }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2454
        return result;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2455
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2456
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2457
    private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2458
                                                             Class<?> ptype, Object value) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2459
        Wrapper w = Wrapper.forPrimitiveType(ptype);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2460
        // perform unboxing and/or primitive conversion
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2461
        value = w.convert(value, ptype);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2462
        switch (w) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2463
        case INT:     return result.bindArgumentI(pos, (int)value);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2464
        case LONG:    return result.bindArgumentJ(pos, (long)value);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2465
        case FLOAT:   return result.bindArgumentF(pos, (float)value);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2466
        case DOUBLE:  return result.bindArgumentD(pos, (double)value);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2467
        default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2468
        }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2469
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2470
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2471
    private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2472
        MethodType oldType = target.type();
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2473
        int outargs = oldType.parameterCount();
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2474
        int inargs  = outargs - insCount;
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2475
        if (inargs < 0)
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2476
            throw newIllegalArgumentException("too many values to insert");
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2477
        if (pos < 0 || pos > inargs)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2478
            throw newIllegalArgumentException("no argument type to append");
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2479
        return oldType.ptypes();
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2480
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2481
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2482
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2483
     * Produces a method handle which will discard some dummy arguments
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2484
     * before calling some other specified <i>target</i> method handle.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2485
     * The type of the new method handle will be the same as the target's type,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2486
     * except it will also include the dummy argument types,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2487
     * at some given position.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2488
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2489
     * The {@code pos} argument may range between zero and <i>N</i>,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2490
     * where <i>N</i> is the arity of the target.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2491
     * If {@code pos} is zero, the dummy arguments will precede
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2492
     * the target's real arguments; if {@code pos} is <i>N</i>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2493
     * they will come after.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2494
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2495
     * <b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2496
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2497
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2498
import static java.lang.invoke.MethodType.*;
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2499
...
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2500
MethodHandle cat = lookup().findVirtual(String.class,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2501
  "concat", methodType(String.class, String.class));
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2502
assertEquals("xy", (String) cat.invokeExact("x", "y"));
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2503
MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2504
MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2505
assertEquals(bigType, d0.type());
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2506
assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2507
     * }</pre></blockquote>
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2508
     * <p>
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2509
     * This method is also equivalent to the following code:
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2510
     * <blockquote><pre>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2511
     * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2512
     * </pre></blockquote>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2513
     * @param target the method handle to invoke after the arguments are dropped
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2514
     * @param valueTypes the type(s) of the argument(s) to drop
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2515
     * @param pos position of first argument to drop (zero for the leftmost)
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2516
     * @return a method handle which drops arguments of the given types,
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2517
     *         before calling the original method handle
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2518
     * @throws NullPointerException if the target is null,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2519
     *                              or if the {@code valueTypes} list or any of its elements is null
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2520
     * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2521
     *                  or if {@code pos} is negative or greater than the arity of the target,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2522
     *                  or if the new method handle's type would have too many parameters
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2523
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2524
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2525
    MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2526
        MethodType oldType = target.type();  // get NPE
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2527
        int dropped = dropArgumentChecks(oldType, pos, valueTypes);
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2528
        MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2529
        if (dropped == 0)  return target;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2530
        BoundMethodHandle result = target.rebind();
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2531
        LambdaForm lform = result.form;
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2532
        int insertFormArg = 1 + pos;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2533
        for (Class<?> ptype : valueTypes) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2534
            lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2535
        }
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2536
        result = result.copyWith(newType, lform);
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2537
        return result;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2538
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2539
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2540
    private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2541
        int dropped = valueTypes.size();
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2542
        MethodType.checkSlotCount(dropped);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2543
        int outargs = oldType.parameterCount();
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2544
        int inargs  = outargs + dropped;
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2545
        if (pos < 0 || pos > outargs)
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2546
            throw newIllegalArgumentException("no argument type to remove"
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2547
                    + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2548
                    );
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2549
        return dropped;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2550
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2551
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2552
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2553
     * Produces a method handle which will discard some dummy arguments
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2554
     * before calling some other specified <i>target</i> method handle.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2555
     * The type of the new method handle will be the same as the target's type,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2556
     * except it will also include the dummy argument types,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2557
     * at some given position.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2558
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2559
     * The {@code pos} argument may range between zero and <i>N</i>,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2560
     * where <i>N</i> is the arity of the target.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2561
     * If {@code pos} is zero, the dummy arguments will precede
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2562
     * the target's real arguments; if {@code pos} is <i>N</i>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2563
     * they will come after.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2564
     * <p>
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2565
     * <b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2566
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2567
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2568
import static java.lang.invoke.MethodType.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2569
...
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2570
MethodHandle cat = lookup().findVirtual(String.class,
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2571
  "concat", methodType(String.class, String.class));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2572
assertEquals("xy", (String) cat.invokeExact("x", "y"));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2573
MethodHandle d0 = dropArguments(cat, 0, String.class);
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2574
assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2575
MethodHandle d1 = dropArguments(cat, 1, String.class);
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2576
assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2577
MethodHandle d2 = dropArguments(cat, 2, String.class);
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2578
assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2579
MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2580
assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2581
     * }</pre></blockquote>
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2582
     * <p>
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2583
     * This method is also equivalent to the following code:
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2584
     * <blockquote><pre>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2585
     * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2586
     * </pre></blockquote>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2587
     * @param target the method handle to invoke after the arguments are dropped
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2588
     * @param valueTypes the type(s) of the argument(s) to drop
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2589
     * @param pos position of first argument to drop (zero for the leftmost)
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2590
     * @return a method handle which drops arguments of the given types,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2591
     *         before calling the original method handle
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2592
     * @throws NullPointerException if the target is null,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2593
     *                              or if the {@code valueTypes} array or any of its elements is null
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2594
     * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2595
     *                  or if {@code pos} is negative or greater than the arity of the target,
20529
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  2596
     *                  or if the new method handle's type would have
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  2597
     *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2598
     */
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2599
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2600
    MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2601
        return dropArguments(target, pos, Arrays.asList(valueTypes));
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2602
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2603
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2604
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2605
     * Adapts a target method handle by pre-processing
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2606
     * one or more of its arguments, each with its own unary filter function,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2607
     * and then calling the target with each pre-processed argument
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2608
     * replaced by the result of its corresponding filter function.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2609
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2610
     * The pre-processing is performed by one or more method handles,
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2611
     * specified in the elements of the {@code filters} array.
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2612
     * The first element of the filter array corresponds to the {@code pos}
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2613
     * argument of the target, and so on in sequence.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2614
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2615
     * Null arguments in the array are treated as identity functions,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2616
     * and the corresponding arguments left unchanged.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2617
     * (If there are no non-null elements in the array, the original target is returned.)
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2618
     * Each filter is applied to the corresponding argument of the adapter.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2619
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2620
     * If a filter {@code F} applies to the {@code N}th argument of
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2621
     * the target, then {@code F} must be a method handle which
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2622
     * takes exactly one argument.  The type of {@code F}'s sole argument
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2623
     * replaces the corresponding argument type of the target
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2624
     * in the resulting adapted method handle.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2625
     * The return type of {@code F} must be identical to the corresponding
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2626
     * parameter type of the target.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2627
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2628
     * It is an error if there are elements of {@code filters}
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2629
     * (null or not)
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2630
     * which do not correspond to argument positions in the target.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2631
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2632
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2633
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2634
import static java.lang.invoke.MethodType.*;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2635
...
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2636
MethodHandle cat = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2637
  "concat", methodType(String.class, String.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2638
MethodHandle upcase = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2639
  "toUpperCase", methodType(String.class));
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2640
assertEquals("xy", (String) cat.invokeExact("x", "y"));
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2641
MethodHandle f0 = filterArguments(cat, 0, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2642
assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2643
MethodHandle f1 = filterArguments(cat, 1, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2644
assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2645
MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2646
assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2647
     * }</pre></blockquote>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2648
     * <p> Here is pseudocode for the resulting adapter:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2649
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2650
     * V target(P... p, A[i]... a[i], B... b);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2651
     * A[i] filter[i](V[i]);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2652
     * T adapter(P... p, V[i]... v[i], B... b) {
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2653
     *   return target(p..., f[i](v[i])..., b...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2654
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2655
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2656
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2657
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2658
     * variable-arity method handle}, even if the original target method handle was.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2659
     *
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2660
     * @param target the method handle to invoke after arguments are filtered
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2661
     * @param pos the position of the first argument to filter
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2662
     * @param filters method handles to call initially on filtered arguments
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2663
     * @return method handle which incorporates the specified argument filtering logic
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2664
     * @throws NullPointerException if the target is null
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2665
     *                              or if the {@code filters} array is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2666
     * @throws IllegalArgumentException if a non-null element of {@code filters}
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2667
     *          does not match a corresponding argument type of target as described above,
20529
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  2668
     *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  2669
     *          or if the resulting method handle's type would have
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
  2670
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2671
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2672
    public static
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2673
    MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2674
        filterArgumentsCheckArity(target, pos, filters);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2675
        MethodHandle adapter = target;
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2676
        int curPos = pos-1;  // pre-incremented
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2677
        for (MethodHandle filter : filters) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2678
            curPos += 1;
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2679
            if (filter == null)  continue;  // ignore null elements of filters
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2680
            adapter = filterArgument(adapter, curPos, filter);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2681
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2682
        return adapter;
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2683
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2684
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2685
    /*non-public*/ static
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2686
    MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2687
        filterArgumentChecks(target, pos, filter);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2688
        MethodType targetType = target.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2689
        MethodType filterType = filter.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2690
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2691
        Class<?> newParamType = filterType.parameterType(0);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2692
        LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2693
        MethodType newType = targetType.changeParameterType(pos, newParamType);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2694
        result = result.copyWithExtendL(newType, lform, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2695
        return result;
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2696
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2697
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2698
    private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2699
        MethodType targetType = target.type();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2700
        int maxPos = targetType.parameterCount();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2701
        if (pos + filters.length > maxPos)
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2702
            throw newIllegalArgumentException("too many filters");
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2703
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2704
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2705
    private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2706
        MethodType targetType = target.type();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2707
        MethodType filterType = filter.type();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2708
        if (filterType.parameterCount() != 1
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2709
            || filterType.returnType() != targetType.parameterType(pos))
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2710
            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2711
    }
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2712
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2713
    /**
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2714
     * Adapts a target method handle by pre-processing
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2715
     * a sub-sequence of its arguments with a filter (another method handle).
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2716
     * The pre-processed arguments are replaced by the result (if any) of the
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2717
     * filter function.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2718
     * The target is then called on the modified (usually shortened) argument list.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2719
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2720
     * If the filter returns a value, the target must accept that value as
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2721
     * its argument in position {@code pos}, preceded and/or followed by
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2722
     * any arguments not passed to the filter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2723
     * If the filter returns void, the target must accept all arguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2724
     * not passed to the filter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2725
     * No arguments are reordered, and a result returned from the filter
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2726
     * replaces (in order) the whole subsequence of arguments originally
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2727
     * passed to the adapter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2728
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2729
     * The argument types (if any) of the filter
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2730
     * replace zero or one argument types of the target, at position {@code pos},
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2731
     * in the resulting adapted method handle.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2732
     * The return type of the filter (if any) must be identical to the
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2733
     * argument type of the target at position {@code pos}, and that target argument
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2734
     * is supplied by the return value of the filter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2735
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2736
     * In all cases, {@code pos} must be greater than or equal to zero, and
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2737
     * {@code pos} must also be less than or equal to the target's arity.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2738
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2739
     * <blockquote><pre>{@code
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2740
import static java.lang.invoke.MethodHandles.*;
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2741
import static java.lang.invoke.MethodType.*;
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2742
...
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2743
MethodHandle deepToString = publicLookup()
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2744
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2745
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2746
MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2747
assertEquals("[strange]", (String) ts1.invokeExact("strange"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2748
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2749
MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2750
assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2751
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2752
MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2753
MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2754
assertEquals("[top, [up, down], strange]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2755
             (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2756
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2757
MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2758
assertEquals("[top, [up, down], [strange]]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2759
             (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2760
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2761
MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2762
assertEquals("[top, [[up, down, strange], charm], bottom]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2763
             (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2764
     * }</pre></blockquote>
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2765
     * <p> Here is pseudocode for the resulting adapter:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2766
     * <blockquote><pre>{@code
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2767
     * T target(A...,V,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2768
     * V filter(B...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2769
     * T adapter(A... a,B... b,C... c) {
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2770
     *   V v = filter(b...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2771
     *   return target(a...,v,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2772
     * }
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2773
     * // and if the filter has no arguments:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2774
     * T target2(A...,V,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2775
     * V filter2();
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2776
     * T adapter2(A... a,C... c) {
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2777
     *   V v = filter2();
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2778
     *   return target2(a...,v,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2779
     * }
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2780
     * // and if the filter has a void return:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2781
     * T target3(A...,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2782
     * void filter3(B...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2783
     * void adapter3(A... a,B... b,C... c) {
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2784
     *   filter3(b...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2785
     *   return target3(a...,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2786
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2787
     * }</pre></blockquote>
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2788
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2789
     * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2790
     * one which first "folds" the affected arguments, and then drops them, in separate
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2791
     * steps as follows:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2792
     * <blockquote><pre>{@code
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2793
     * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2794
     * mh = MethodHandles.foldArguments(mh, coll); //step 1
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2795
     * }</pre></blockquote>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2796
     * If the target method handle consumes no arguments besides than the result
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2797
     * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2798
     * is equivalent to {@code filterReturnValue(coll, mh)}.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2799
     * If the filter method handle {@code coll} consumes one argument and produces
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2800
     * a non-void result, then {@code collectArguments(mh, N, coll)}
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2801
     * is equivalent to {@code filterArguments(mh, N, coll)}.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2802
     * Other equivalences are possible but would require argument permutation.
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2803
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2804
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2805
     * variable-arity method handle}, even if the original target method handle was.
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2806
     *
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2807
     * @param target the method handle to invoke after filtering the subsequence of arguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2808
     * @param pos the position of the first adapter argument to pass to the filter,
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2809
     *            and/or the target argument which receives the result of the filter
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2810
     * @param filter method handle to call on the subsequence of arguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2811
     * @return method handle which incorporates the specified argument subsequence filtering logic
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2812
     * @throws NullPointerException if either argument is null
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2813
     * @throws IllegalArgumentException if the return type of {@code filter}
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2814
     *          is non-void and is not the same as the {@code pos} argument of the target,
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2815
     *          or if {@code pos} is not between 0 and the target's arity, inclusive,
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2816
     *          or if the resulting method handle's type would have
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2817
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2818
     * @see MethodHandles#foldArguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2819
     * @see MethodHandles#filterArguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2820
     * @see MethodHandles#filterReturnValue
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2821
     */
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2822
    public static
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2823
    MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2824
        MethodType newType = collectArgumentsChecks(target, pos, filter);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2825
        MethodType collectorType = filter.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2826
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2827
        LambdaForm lform;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2828
        if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2829
            lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2830
            if (lform != null) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2831
                return result.copyWith(newType, lform);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2832
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2833
        }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2834
        lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2835
        return result.copyWithExtendL(newType, lform, filter);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2836
    }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2837
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2838
    private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
13610
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  2839
        MethodType targetType = target.type();
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  2840
        MethodType filterType = filter.type();
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2841
        Class<?> rtype = filterType.returnType();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2842
        List<Class<?>> filterArgs = filterType.parameterList();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2843
        if (rtype == void.class) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2844
            return targetType.insertParameterTypes(pos, filterArgs);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2845
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2846
        if (rtype != targetType.parameterType(pos)) {
13610
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  2847
            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2848
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2849
        return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
13610
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  2850
    }
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  2851
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  2852
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2853
     * Adapts a target method handle by post-processing
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2854
     * its return value (if any) with a filter (another method handle).
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2855
     * The result of the filter is returned from the adapter.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2856
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2857
     * If the target returns a value, the filter must accept that value as
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2858
     * its only argument.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2859
     * If the target returns void, the filter must accept no arguments.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2860
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2861
     * The return type of the filter
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2862
     * replaces the return type of the target
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2863
     * in the resulting adapted method handle.
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2864
     * The argument type of the filter (if any) must be identical to the
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2865
     * return type of the target.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2866
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2867
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2868
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  2869
import static java.lang.invoke.MethodType.*;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2870
...
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2871
MethodHandle cat = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2872
  "concat", methodType(String.class, String.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2873
MethodHandle length = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2874
  "length", methodType(int.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2875
System.out.println((String) cat.invokeExact("x", "y")); // xy
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2876
MethodHandle f0 = filterReturnValue(cat, length);
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2877
System.out.println((int) f0.invokeExact("x", "y")); // 2
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2878
     * }</pre></blockquote>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2879
     * <p> Here is pseudocode for the resulting adapter:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2880
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2881
     * V target(A...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2882
     * T filter(V);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2883
     * T adapter(A... a) {
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2884
     *   V v = target(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2885
     *   return filter(v);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2886
     * }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2887
     * // and if the target has a void return:
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2888
     * void target2(A...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2889
     * T filter2();
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2890
     * T adapter2(A... a) {
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2891
     *   target2(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2892
     *   return filter2();
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2893
     * }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2894
     * // and if the filter has a void return:
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2895
     * V target3(A...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2896
     * void filter3(V);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2897
     * void adapter3(A... a) {
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2898
     *   V v = target3(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2899
     *   filter3(v);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2900
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2901
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2902
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2903
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2904
     * variable-arity method handle}, even if the original target method handle was.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2905
     * @param target the method handle to invoke before filtering the return value
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2906
     * @param filter method handle to call on the return value
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2907
     * @return method handle which incorporates the specified return value filtering logic
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2908
     * @throws NullPointerException if either argument is null
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2909
     * @throws IllegalArgumentException if the argument list of {@code filter}
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2910
     *          does not match the return type of target as described above
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  2911
     */
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2912
    public static
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  2913
    MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  2914
        MethodType targetType = target.type();
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  2915
        MethodType filterType = filter.type();
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2916
        filterReturnValueChecks(targetType, filterType);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2917
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2918
        BasicType rtype = BasicType.basicType(filterType.returnType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2919
        LambdaForm lform = result.editor().filterReturnForm(rtype, false);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2920
        MethodType newType = targetType.changeReturnType(filterType.returnType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2921
        result = result.copyWithExtendL(newType, lform, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2922
        return result;
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2923
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2924
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2925
    private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2926
        Class<?> rtype = targetType.returnType();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2927
        int filterValues = filterType.parameterCount();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2928
        if (filterValues == 0
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2929
                ? (rtype != void.class)
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2930
                : (rtype != filterType.parameterType(0)))
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  2931
            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  2932
    }
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  2933
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2934
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2935
     * Adapts a target method handle by pre-processing
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2936
     * some of its arguments, and then calling the target with
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2937
     * the result of the pre-processing, inserted into the original
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2938
     * sequence of arguments.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2939
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2940
     * The pre-processing is performed by {@code combiner}, a second method handle.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2941
     * Of the arguments passed to the adapter, the first {@code N} arguments
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2942
     * are copied to the combiner, which is then called.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2943
     * (Here, {@code N} is defined as the parameter count of the combiner.)
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2944
     * After this, control passes to the target, with any result
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2945
     * from the combiner inserted before the original {@code N} incoming
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2946
     * arguments.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2947
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2948
     * If the combiner returns a value, the first parameter type of the target
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2949
     * must be identical with the return type of the combiner, and the next
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2950
     * {@code N} parameter types of the target must exactly match the parameters
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2951
     * of the combiner.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2952
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2953
     * If the combiner has a void return, no result will be inserted,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2954
     * and the first {@code N} parameter types of the target
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2955
     * must exactly match the parameters of the combiner.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2956
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2957
     * The resulting adapter is the same type as the target, except that the
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2958
     * first parameter type is dropped,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2959
     * if it corresponds to the result of the combiner.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2960
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2961
     * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2962
     * that either the combiner or the target does not wish to receive.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2963
     * If some of the incoming arguments are destined only for the combiner,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2964
     * consider using {@link MethodHandle#asCollector asCollector} instead, since those
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2965
     * arguments will not need to be live on the stack on entry to the
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2966
     * target.)
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2967
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  2968
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2969
import static java.lang.invoke.MethodHandles.*;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2970
import static java.lang.invoke.MethodType.*;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2971
...
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2972
MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2973
  "println", methodType(void.class, String.class))
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2974
    .bindTo(System.out);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2975
MethodHandle cat = lookup().findVirtual(String.class,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2976
  "concat", methodType(String.class, String.class));
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2977
assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2978
MethodHandle catTrace = foldArguments(cat, trace);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2979
// also prints "boo":
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2980
assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2981
     * }</pre></blockquote>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2982
     * <p> Here is pseudocode for the resulting adapter:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2983
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2984
     * // there are N arguments in A...
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2985
     * T target(V, A[N]..., B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2986
     * V combiner(A...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2987
     * T adapter(A... a, B... b) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2988
     *   V v = combiner(a...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2989
     *   return target(v, a..., b...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2990
     * }
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2991
     * // and if the combiner has a void return:
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2992
     * T target2(A[N]..., B...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2993
     * void combiner2(A...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2994
     * T adapter2(A... a, B... b) {
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2995
     *   combiner2(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2996
     *   return target2(a..., b...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2997
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2998
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2999
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3000
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3001
     * variable-arity method handle}, even if the original target method handle was.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3002
     * @param target the method handle to invoke after arguments are combined
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3003
     * @param combiner method handle to call initially on the incoming arguments
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3004
     * @return method handle which incorporates the specified argument folding logic
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3005
     * @throws NullPointerException if either argument is null
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3006
     * @throws IllegalArgumentException if {@code combiner}'s return type
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3007
     *          is non-void and not the same as the first argument type of
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3008
     *          the target, or if the initial {@code N} argument types
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3009
     *          of the target
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3010
     *          (skipping one matching the {@code combiner}'s return type)
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3011
     *          are not identical with the argument types of {@code combiner}
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3012
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3013
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3014
    MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3015
        return foldArguments(target, 0, combiner);
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3016
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3017
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3018
    private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3019
        int foldArgs   = combinerType.parameterCount();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3020
        Class<?> rtype = combinerType.returnType();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3021
        int foldVals = rtype == void.class ? 0 : 1;
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3022
        int afterInsertPos = foldPos + foldVals;
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3023
        boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3024
        if (ok && !(combinerType.parameterList()
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3025
                    .equals(targetType.parameterList().subList(afterInsertPos,
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3026
                                                               afterInsertPos + foldArgs))))
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  3027
            ok = false;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3028
        if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  3029
            ok = false;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3030
        if (!ok)
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3031
            throw misMatchedTypes("target and combiner types", targetType, combinerType);
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3032
        return rtype;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3033
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3034
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3035
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3036
     * Makes a method handle which adapts a target method handle,
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3037
     * by guarding it with a test, a boolean-valued method handle.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3038
     * If the guard fails, a fallback handle is called instead.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3039
     * All three method handles must have the same corresponding
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3040
     * argument and return types, except that the return type
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3041
     * of the test must be boolean, and the test is allowed
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3042
     * to have fewer arguments than the other two method handles.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3043
     * <p> Here is pseudocode for the resulting adapter:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3044
     * <blockquote><pre>{@code
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3045
     * boolean test(A...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3046
     * T target(A...,B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3047
     * T fallback(A...,B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3048
     * T adapter(A... a,B... b) {
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3049
     *   if (test(a...))
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3050
     *     return target(a..., b...);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3051
     *   else
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3052
     *     return fallback(a..., b...);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3053
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3054
     * }</pre></blockquote>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3055
     * Note that the test arguments ({@code a...} in the pseudocode) cannot
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3056
     * be modified by execution of the test, and so are passed unchanged
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3057
     * from the caller to the target or fallback as appropriate.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3058
     * @param test method handle used for test, must return boolean
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3059
     * @param target method handle to call if test passes
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3060
     * @param fallback method handle to call if test fails
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3061
     * @return method handle which incorporates the specified if/then/else logic
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3062
     * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3063
     * @throws IllegalArgumentException if {@code test} does not return boolean,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3064
     *          or if all three method types do not match (with the return
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3065
     *          type of {@code test} changed to match that of the target).
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3066
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3067
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3068
    MethodHandle guardWithTest(MethodHandle test,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3069
                               MethodHandle target,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3070
                               MethodHandle fallback) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3071
        MethodType gtype = test.type();
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3072
        MethodType ttype = target.type();
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3073
        MethodType ftype = fallback.type();
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3074
        if (!ttype.equals(ftype))
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3075
            throw misMatchedTypes("target and fallback types", ttype, ftype);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3076
        if (gtype.returnType() != boolean.class)
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3077
            throw newIllegalArgumentException("guard type is not a predicate "+gtype);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3078
        List<Class<?>> targs = ttype.parameterList();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3079
        List<Class<?>> gargs = gtype.parameterList();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3080
        if (!targs.equals(gargs)) {
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3081
            int gpc = gargs.size(), tpc = targs.size();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3082
            if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3083
                throw misMatchedTypes("target and test types", ttype, gtype);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3084
            test = dropArguments(test, gpc, targs.subList(gpc, tpc));
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3085
            gtype = test.type();
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3086
        }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  3087
        return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3088
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3089
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3090
    static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3091
        return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3092
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3093
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3094
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3095
     * Makes a method handle which adapts a target method handle,
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3096
     * by running it inside an exception handler.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3097
     * If the target returns normally, the adapter returns that value.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3098
     * If an exception matching the specified type is thrown, the fallback
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3099
     * handle is called instead on the exception, plus the original arguments.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3100
     * <p>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3101
     * The target and handler must have the same corresponding
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3102
     * argument and return types, except that handler may omit trailing arguments
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3103
     * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3104
     * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3105
     * <p> Here is pseudocode for the resulting adapter:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3106
     * <blockquote><pre>{@code
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3107
     * T target(A..., B...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3108
     * T handler(ExType, A...);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3109
     * T adapter(A... a, B... b) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3110
     *   try {
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3111
     *     return target(a..., b...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3112
     *   } catch (ExType ex) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3113
     *     return handler(ex, a...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3114
     *   }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3115
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3116
     * }</pre></blockquote>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3117
     * Note that the saved arguments ({@code a...} in the pseudocode) cannot
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3118
     * be modified by execution of the target, and so are passed unchanged
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3119
     * from the caller to the handler, if the handler is invoked.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3120
     * <p>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3121
     * The target and handler must return the same type, even if the handler
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3122
     * always throws.  (This might happen, for instance, because the handler
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3123
     * is simulating a {@code finally} clause).
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3124
     * To create such a throwing handler, compose the handler creation logic
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3125
     * with {@link #throwException throwException},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3126
     * in order to create a method handle of the correct return type.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3127
     * @param target method handle to call
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3128
     * @param exType the type of exception which the handler will catch
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3129
     * @param handler method handle to call if a matching exception is thrown
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3130
     * @return method handle which incorporates the specified try/catch logic
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3131
     * @throws NullPointerException if any argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3132
     * @throws IllegalArgumentException if {@code handler} does not accept
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3133
     *          the given exception type, or if the method handle types do
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3134
     *          not match in their return types and their
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3135
     *          corresponding parameters
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3136
     * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3137
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3138
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3139
    MethodHandle catchException(MethodHandle target,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3140
                                Class<? extends Throwable> exType,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3141
                                MethodHandle handler) {
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3142
        MethodType ttype = target.type();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3143
        MethodType htype = handler.type();
34959
4e7903220c89 8147078: MethodHandles.catchException does not enforce Throwable subtype
mhaupt
parents: 34882
diff changeset
  3144
        if (!Throwable.class.isAssignableFrom(exType))
4e7903220c89 8147078: MethodHandles.catchException does not enforce Throwable subtype
mhaupt
parents: 34882
diff changeset
  3145
            throw new ClassCastException(exType.getName());
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3146
        if (htype.parameterCount() < 1 ||
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3147
            !htype.parameterType(0).isAssignableFrom(exType))
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3148
            throw newIllegalArgumentException("handler does not accept exception type "+exType);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3149
        if (htype.returnType() != ttype.returnType())
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3150
            throw misMatchedTypes("target and handler return types", ttype, htype);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3151
        List<Class<?>> targs = ttype.parameterList();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3152
        List<Class<?>> hargs = htype.parameterList();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3153
        hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3154
        if (!targs.equals(hargs)) {
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3155
            int hpc = hargs.size(), tpc = targs.size();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3156
            if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3157
                throw misMatchedTypes("target and handler types", ttype, htype);
9730
e4b334d47f4b 7032850: MethodHandle.invokeGeneric throws unspecified RuntimeException if parameterized method is called
jrose
parents: 9646
diff changeset
  3158
            handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3159
            htype = handler.type();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3160
        }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  3161
        return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3162
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3163
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3164
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3165
     * Produces a method handle which will throw exceptions of the given {@code exType}.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3166
     * The method handle will accept a single argument of {@code exType},
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3167
     * and immediately throw it as an exception.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3168
     * The method type will nominally specify a return of {@code returnType}.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3169
     * The return type may be anything convenient:  It doesn't matter to the
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3170
     * method handle's behavior, since it will never return normally.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  3171
     * @param returnType the return type of the desired method handle
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  3172
     * @param exType the parameter type of the desired method handle
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3173
     * @return method handle which can throw the given exceptions
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3174
     * @throws NullPointerException if either argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3175
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3176
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3177
    MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3178
        if (!Throwable.class.isAssignableFrom(exType))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3179
            throw new ClassCastException(exType.getName());
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  3180
        return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3181
    }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3182
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3183
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3184
     * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3185
     * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3186
     * delivers the loop's result, which is the return value of the resulting handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3187
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3188
     * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3189
     * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3190
     * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3191
     * terms of method handles, each clause will determine four actions:<ul>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3192
     * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3193
     * <li>When a clause executes, an update step for the iteration variable.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3194
     * <li>When a clause executes, a predicate execution to test for loop exit.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3195
     * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3196
     * </ul>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3197
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3198
     * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3199
     * this case. See below for a detailed description.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3200
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3201
     * Each clause function, with the exception of clause initializers, is able to observe the entire loop state,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3202
     * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3203
     * parameters. Most clause functions will not need all of this information, but they will be formally connected as
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3204
     * if by {@link #dropArguments}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3205
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3206
     * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3207
     * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3208
     * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3209
     * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3210
     * that they must be identical, or else one list must be a proper prefix of the other.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3211
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3212
     * <em>Step 0: Determine clause structure.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3213
     * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3214
     * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3215
     * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3216
     * four. Padding takes place by appending elements to the array.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3217
     * <li>Clauses with all {@code null}s are disregarded.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3218
     * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3219
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3220
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3221
     * <em>Step 1A: Determine iteration variables.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3222
     * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3223
     * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3224
     * use the common return type (they must be identical).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3225
     * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3226
     * <li>This list of types is called the "common prefix".
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3227
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3228
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3229
     * <em>Step 1B: Determine loop parameters.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3230
     * <li>Examine init function parameter lists.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3231
     * <li>Omitted init functions are deemed to have {@code null} parameter lists.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3232
     * <li>All init function parameter lists must be effectively identical.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3233
     * <li>The longest parameter list (which is necessarily unique) is called the "common suffix".
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3234
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3235
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3236
     * <em>Step 1C: Determine loop return type.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3237
     * <li>Examine fini function return types, disregarding omitted fini functions.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3238
     * <li>If there are no fini functions, use {@code void} as the loop return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3239
     * <li>Otherwise, use the common return type of the fini functions; they must all be identical.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3240
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3241
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3242
     * <em>Step 1D: Check other types.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3243
     * <li>There must be at least one non-omitted pred function.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3244
     * <li>Every non-omitted pred function must have a {@code boolean} return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3245
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3246
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3247
     * (Implementation Note: Steps 1A, 1B, 1C, 1D are logically independent of each other, and may be performed in any
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3248
     * order.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3249
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3250
     * <em>Step 2: Determine parameter lists.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3251
     * <li>The parameter list for the resulting loop handle will be the "common suffix".
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3252
     * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3253
     * lists are already effectively identical to the common suffix.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3254
     * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3255
     * followed by the common suffix, called the "common parameter sequence".
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3256
     * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3257
     * sequence.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3258
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3259
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3260
     * <em>Step 3: Fill in omitted functions.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3261
     * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3262
     * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3263
     * function which does nothing and returns {@code void}; it can be obtained from another constant function by
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3264
     * {@linkplain MethodHandle#asType type conversion}.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3265
     * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3266
     * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3267
     * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3268
     * <li>If a pred function is omitted, the corresponding fini function must also be omitted.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3269
     * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3270
     * as this clause is concerned.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3271
     * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3272
     * loop return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3273
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3274
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3275
     * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3276
     * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3277
     * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3278
     * {@linkplain #dropArguments dropping arguments}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3279
     * <li>At this point, every non-init function parameter list is effectively identical to the common parameter
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3280
     * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3281
     * of the list by {@linkplain #dropArguments dropping arguments}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3282
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3283
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3284
     * <em>Final observations.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3285
     * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3286
     * <li>All init functions have a common parameter type list, which the final loop handle will also have.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3287
     * <li>All fini functions have a common return type, which the final loop handle will also have.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3288
     * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3289
     * (non-{@code void}) iteration variables followed by loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3290
     * <li>Each pair of init and step functions agrees in their return types.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3291
     * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3292
     * common prefix.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3293
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3294
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3295
     * <em>Loop execution.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3296
     * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3297
     * every clause function. These locals are loop invariant.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3298
     * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3299
     * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3300
     * functions, as noted above).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3301
     * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3302
     * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3303
     * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3304
     * returns {@code false}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3305
     * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3306
     * updated value is immediately visible to all subsequent function calls.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3307
     * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3308
     * is returned from the loop as a whole.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3309
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3310
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3311
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3312
     * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3313
     * result types of finalizers as well as of the resulting loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3314
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3315
     * V... init...(A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3316
     * boolean pred...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3317
     * V... step...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3318
     * R fini...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3319
     * R loop(A... a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3320
     *   V... v... = init...(a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3321
     *   for (;;) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3322
     *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3323
     *       v = s(v..., a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3324
     *       if (!p(v..., a...)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3325
     *         return f(v..., a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3326
     *       }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3327
     *     }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3328
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3329
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3330
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3331
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3332
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3333
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3334
     * // iterative implementation of the factorial function as a loop handle
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3335
     * static int one(int k) { return 1; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3336
     * int inc(int i, int acc, int k) { return i + 1; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3337
     * int mult(int i, int acc, int k) { return i * acc; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3338
     * boolean pred(int i, int acc, int k) { return i < k; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3339
     * int fin(int i, int acc, int k) { return acc; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3340
     * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3341
     * // null initializer for counter, should initialize to 0
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3342
     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3343
     * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3344
     * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3345
     * assertEquals(120, loop.invoke(5));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3346
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3347
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3348
     * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3349
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3350
     * @return a method handle embodying the looping behavior as defined by the arguments.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3351
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3352
     * @throws IllegalArgumentException in case any of the constraints described above is violated.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3353
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3354
     * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3355
     * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3356
     * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3357
     * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3358
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3359
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3360
    public static MethodHandle loop(MethodHandle[]... clauses) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3361
        // Step 0: determine clause structure.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3362
        checkLoop0(clauses);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3363
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3364
        List<MethodHandle> init = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3365
        List<MethodHandle> step = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3366
        List<MethodHandle> pred = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3367
        List<MethodHandle> fini = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3368
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3369
        Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3370
            init.add(clause[0]); // all clauses have at least length 1
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3371
            step.add(clause.length <= 1 ? null : clause[1]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3372
            pred.add(clause.length <= 2 ? null : clause[2]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3373
            fini.add(clause.length <= 3 ? null : clause[3]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3374
        });
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3375
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3376
        assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3377
        final int nclauses = init.size();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3378
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3379
        // Step 1A: determine iteration variables.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3380
        final List<Class<?>> iterationVariableTypes = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3381
        for (int i = 0; i < nclauses; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3382
            MethodHandle in = init.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3383
            MethodHandle st = step.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3384
            if (in == null && st == null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3385
                iterationVariableTypes.add(void.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3386
            } else if (in != null && st != null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3387
                checkLoop1a(i, in, st);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3388
                iterationVariableTypes.add(in.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3389
            } else {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3390
                iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3391
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3392
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3393
        final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3394
                collect(Collectors.toList());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3395
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3396
        // Step 1B: determine loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3397
        final List<Class<?>> empty = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3398
        final List<Class<?>> commonSuffix = init.stream().filter(Objects::nonNull).map(MethodHandle::type).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3399
                map(MethodType::parameterList).reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3400
        checkLoop1b(init, commonSuffix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3401
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3402
        // Step 1C: determine loop return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3403
        // Step 1D: check other types.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3404
        final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3405
                map(MethodType::returnType).findFirst().orElse(void.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3406
        checkLoop1cd(pred, fini, loopReturnType);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3407
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3408
        // Step 2: determine parameter lists.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3409
        final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3410
        commonParameterSequence.addAll(commonSuffix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3411
        checkLoop2(step, pred, fini, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3412
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3413
        // Step 3: fill in omitted functions.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3414
        for (int i = 0; i < nclauses; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3415
            Class<?> t = iterationVariableTypes.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3416
            if (init.get(i) == null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3417
                init.set(i, zeroHandle(t));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3418
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3419
            if (step.get(i) == null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3420
                step.set(i, dropArguments(t == void.class ? zeroHandle(t) : identity(t), 0, commonPrefix.subList(0, i)));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3421
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3422
            if (pred.get(i) == null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3423
                pred.set(i, constant(boolean.class, true));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3424
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3425
            if (fini.get(i) == null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3426
                fini.set(i, zeroHandle(t));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3427
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3428
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3429
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3430
        // Step 4: fill in missing parameter types.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3431
        List<MethodHandle> finit = fillParameterTypes(init, commonSuffix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3432
        List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3433
        List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3434
        List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3435
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3436
        assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3437
                allMatch(pl -> pl.equals(commonSuffix));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3438
        assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3439
                allMatch(pl -> pl.equals(commonParameterSequence));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3440
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3441
        return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3442
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3443
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3444
    private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3445
        return hs.stream().map(h -> {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3446
            int pc = h.type().parameterCount();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3447
            int tpsize = targetParams.size();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3448
            return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3449
        }).collect(Collectors.toList());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3450
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3451
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3452
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3453
     * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3454
     * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3455
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3456
     * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3457
     * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3458
     * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3459
     * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3460
     * generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3461
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3462
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3463
     * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3464
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3465
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3466
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3467
     * boolean pred(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3468
     * V body(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3469
     * V whileLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3470
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3471
     *   while (pred(v, a)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3472
     *     v = body(v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3473
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3474
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3475
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3476
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3477
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3478
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3479
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3480
     * // implement the zip function for lists as a loop handle
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3481
     * List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3482
     * boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3483
     * List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3484
     *   zip.add(a.next());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3485
     *   zip.add(b.next());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3486
     *   return zip;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3487
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3488
     * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
34430
8e29bd2b5e0e 8143343: add JEP 274 Javadoc tests to JavaDocExamplesTest
mhaupt
parents: 33874
diff changeset
  3489
     * MethodHandle loop = MethodHandles.doWhileLoop(MH_initZip, MH_zipStep, MH_zipPred);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3490
     * List<String> a = Arrays.asList("a", "b", "c", "d");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3491
     * List<String> b = Arrays.asList("e", "f", "g", "h");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3492
     * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3493
     * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3494
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3495
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3496
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3497
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3498
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3499
     * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3500
     *     MethodHandle[]
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3501
     *         checkExit = {null, null, pred, identity(init.type().returnType())},
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3502
     *         varBody = {init, body};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3503
     *     return loop(checkExit, varBody);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3504
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3505
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3506
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3507
     * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3508
     *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3509
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3510
     * @param pred condition for the loop, which may not be {@code null}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3511
     * @param body body of the loop, which may not be {@code null}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3512
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3513
     * @return the value of the loop variable as the loop terminates.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3514
     * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3515
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3516
     * @see MethodHandles#loop(MethodHandle[][])
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3517
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3518
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3519
    public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3520
        MethodHandle fin = init == null ? zeroHandle(void.class) : identity(init.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3521
        MethodHandle[] checkExit = {null, null, pred, fin};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3522
        MethodHandle[] varBody = {init, body};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3523
        return loop(checkExit, varBody);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3524
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3525
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3526
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3527
     * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3528
     * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3529
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3530
     * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3531
     * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3532
     * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3533
     * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3534
     * generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3535
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3536
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3537
     * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3538
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3539
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3540
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3541
     * boolean pred(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3542
     * V body(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3543
     * V doWhileLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3544
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3545
     *   do {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3546
     *     v = body(v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3547
     *   } while (pred(v, a));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3548
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3549
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3550
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3551
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3552
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3553
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3554
     * // int i = 0; while (i < limit) { ++i; } return i; => limit
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3555
     * int zero(int limit) { return 0; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3556
     * int step(int i, int limit) { return i + 1; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3557
     * boolean pred(int i, int limit) { return i < limit; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3558
     * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3559
     * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3560
     * assertEquals(23, loop.invoke(23));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3561
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3562
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3563
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3564
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3565
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3566
     * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3567
     *     MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) };
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3568
     *     return loop(clause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3569
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3570
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3571
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3572
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3573
     * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3574
     *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3575
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3576
     * @param pred condition for the loop, which may not be {@code null}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3577
     * @param body body of the loop, which may not be {@code null}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3578
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3579
     * @return the value of the loop variable as the loop terminates.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3580
     * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3581
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3582
     * @see MethodHandles#loop(MethodHandle[][])
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3583
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3584
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3585
    public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3586
        MethodHandle fin = init == null ? zeroHandle(void.class) : identity(init.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3587
        MethodHandle[] clause = {init, body, pred, fin};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3588
        return loop(clause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3589
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3590
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3591
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3592
     * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3593
     * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3594
     * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3595
     * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3596
     * combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3597
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3598
     * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3599
     * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3600
     * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3601
     * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3602
     * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3603
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3604
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3605
     * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3606
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3607
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3608
     * int iterations(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3609
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3610
     * V body(int, V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3611
     * V countedLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3612
     *   int end = iterations(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3613
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3614
     *   for (int i = 0; i < end; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3615
     *     v = body(i, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3616
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3617
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3618
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3619
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3620
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3621
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3622
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3623
     * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3624
     * // => a variation on a well known theme
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3625
     * String start(String arg) { return arg; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3626
     * String step(int counter, String v, String arg) { return "na " + v; }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3627
     * // assume MH_start and MH_step are handles to the two methods above
34430
8e29bd2b5e0e 8143343: add JEP 274 Javadoc tests to JavaDocExamplesTest
mhaupt
parents: 33874
diff changeset
  3628
     * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
8e29bd2b5e0e 8143343: add JEP 274 Javadoc tests to JavaDocExamplesTest
mhaupt
parents: 33874
diff changeset
  3629
     * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3630
     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3631
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3632
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3633
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3634
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3635
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3636
     * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3637
     *     return countedLoop(null, iterations, init, body);  // null => constant zero
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3638
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3639
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3640
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3641
     * @param iterations a handle to return the number of iterations this loop should run.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3642
     * @param init initializer for additional loop state. This determines the loop's result type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3643
     *             Passing {@code null} or a {@code void} init function will make the loop's result type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3644
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3645
     * @param body the body of the loop, which must not be {@code null}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3646
     *             It must accept an initial {@code int} parameter (for the counter), and then any
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3647
     *             additional loop-local variable plus loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3648
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3649
     * @return a method handle representing the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3650
     * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3651
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3652
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3653
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3654
    public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3655
        return countedLoop(null, iterations, init, body);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3656
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3657
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3658
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3659
     * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3660
     * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3661
     * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3662
     * body} function in each iteration; it has to accept an initial {@code int} parameter
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3663
     * for that. The result of the loop execution is the final value of the additional local state
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3664
     * obtained by running {@code init}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3665
     * This is a
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3666
     * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3667
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3668
     * The constraints for the {@code init} and {@code body} handles are the same as for {@link
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3669
     * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3670
     * must return an {@code int} and accept the same parameters as {@code init}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3671
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3672
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3673
     * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3674
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3675
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3676
     * int start(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3677
     * int end(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3678
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3679
     * V body(int, V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3680
     * V countedLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3681
     *   int s = start(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3682
     *   int e = end(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3683
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3684
     *   for (int i = s; i < e; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3685
     *     v = body(i, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3686
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3687
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3688
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3689
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3690
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3691
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3692
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3693
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3694
     * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3695
     *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3696
     *     // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3697
     *     MethodHandle[]
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3698
     *         indexVar = {start, MH_increment}, // i = start; i = i+1
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3699
     *         loopLimit = {end, null, MH_lessThan, returnVar }, // i<end
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3700
     *         bodyClause = {init, dropArguments(body, 1, int.class)};  // v = body(i, v);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3701
     *     return loop(indexVar, loopLimit, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3702
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3703
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3704
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3705
     * @param start a handle to return the start value of the loop counter.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3706
     *              If it is {@code null}, a constant zero is assumed.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3707
     * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3708
     * @param init initializer for additional loop state. This determines the loop's result type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3709
     *             Passing {@code null} or a {@code void} init function will make the loop's result type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3710
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3711
     * @param body the body of the loop, which must not be {@code null}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3712
     *             It must accept an initial {@code int} parameter (for the counter), and then any
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3713
     *             additional loop-local variable plus loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3714
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3715
     * @return a method handle representing the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3716
     * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3717
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3718
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3719
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3720
    public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3721
        MethodHandle returnVar = dropArguments(init == null ? zeroHandle(void.class) : identity(init.type().returnType()),
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3722
                0, int.class, int.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3723
        MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3724
        MethodHandle[] loopLimit = {end, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3725
        MethodHandle[] bodyClause = {init, dropArguments(body, 1, int.class)};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3726
        return loop(indexVar, loopLimit, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3727
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3728
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3729
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3730
     * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3731
     * The iterator will be produced by the evaluation of the {@code iterator} handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3732
     * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3733
     * and will be applied to a leading argument of the loop handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3734
     * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3735
     * The result of the loop execution is the final value of the additional local state
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3736
     * obtained by running {@code init}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3737
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3738
     * This is a convenience wrapper for the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3739
     * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3740
     * handle follow directly from those described for the latter.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3741
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3742
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3743
     * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3744
     * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3745
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3746
     * Iterator<T> iterator(A);  // defaults to Iterable::iterator
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3747
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3748
     * V body(T,V,A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3749
     * V iteratedLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3750
     *   Iterator<T> it = iterator(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3751
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3752
     *   for (T t : it) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3753
     *     v = body(t, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3754
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3755
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3756
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3757
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3758
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3759
     * The type {@code T} may be either a primitive or reference.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3760
     * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3761
     * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3762
     * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3763
     * Therefore, if an iterator of the wrong type appears as the loop is executed,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3764
     * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3765
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3766
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3767
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3768
     * // reverse a list
34430
8e29bd2b5e0e 8143343: add JEP 274 Javadoc tests to JavaDocExamplesTest
mhaupt
parents: 33874
diff changeset
  3769
     * List<String> reverseStep(String e, List<String> r, List<String> l) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3770
     *   r.add(0, e);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3771
     *   return r;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3772
     * }
34430
8e29bd2b5e0e 8143343: add JEP 274 Javadoc tests to JavaDocExamplesTest
mhaupt
parents: 33874
diff changeset
  3773
     * List<String> newArrayList(List<String> l) { return new ArrayList<>(); }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3774
     * // assume MH_reverseStep, MH_newArrayList are handles to the above methods
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3775
     * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3776
     * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3777
     * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3778
     * assertEquals(reversedList, (List<String>) loop.invoke(list));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3779
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3780
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3781
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3782
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3783
     * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3784
     *     // assume MH_next and MH_hasNext are handles to methods of Iterator
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3785
     *     Class<?> itype = iterator.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3786
     *     Class<?> ttype = body.type().parameterType(0);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3787
     *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3788
     *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3789
     *     MethodHandle[]
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3790
     *         iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3791
     *         bodyClause = {init, filterArgument(body, 0, nextVal)};  // v = body(t, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3792
     *     return loop(iterVar, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3793
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3794
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3795
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3796
     * @param iterator a handle to return the iterator to start the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3797
     *             Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3798
     *             incoming value.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3799
     * @param init initializer for additional loop state. This determines the loop's result type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3800
     *             Passing {@code null} or a {@code void} init function will make the loop's result type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3801
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3802
     * @param body the body of the loop, which must not be {@code null}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3803
     *             It must accept an initial {@code T} parameter (for the iterated values), and then any
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3804
     *             additional loop-local variable plus loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3805
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3806
     * @return a method handle embodying the iteration loop functionality.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3807
     * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3808
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3809
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3810
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3811
    public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3812
        checkIteratedLoop(body);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3813
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3814
        MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3815
        MethodHandle initIterator = iterator == null ?
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3816
                initit.asType(initit.type().changeParameterType(0, body.type().parameterType(init == null ? 1 : 2))) :
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3817
                iterator;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3818
        Class<?> itype = initIterator.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3819
        Class<?> ttype = body.type().parameterType(0);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3820
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3821
        MethodHandle returnVar =
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3822
                dropArguments(init == null ? zeroHandle(void.class) : identity(init.type().returnType()), 0, itype);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3823
        MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3824
        MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3825
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3826
        MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), returnVar};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3827
        MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3828
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3829
        return loop(iterVar, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3830
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3831
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3832
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3833
     * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3834
     * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3835
     * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3836
     * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3837
     * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3838
     * {@code try-finally} handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3839
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3840
     * The {@code cleanup} handle will be passed one or two additional leading arguments.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3841
     * The first is the exception thrown during the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3842
     * execution of the {@code target} handle, or {@code null} if no exception was thrown.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3843
     * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3844
     * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3845
     * The second argument is not present if the {@code target} handle has a {@code void} return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3846
     * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3847
     * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3848
     * <p>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3849
     * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3850
     * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3851
     * two extra leading parameters:<ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3852
     * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3853
     * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3854
     * the result from the execution of the {@code target} handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3855
     * This parameter is not present if the {@code target} returns {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3856
     * </ul>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3857
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3858
     * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3859
     * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3860
     * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3861
     * the cleanup.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3862
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3863
     * V target(A..., B...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3864
     * V cleanup(Throwable, V, A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3865
     * V adapter(A... a, B... b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3866
     *   V result = (zero value for V);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3867
     *   Throwable throwable = null;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3868
     *   try {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3869
     *     result = target(a..., b...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3870
     *   } catch (Throwable t) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3871
     *     throwable = t;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3872
     *     throw t;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3873
     *   } finally {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3874
     *     result = cleanup(throwable, result, a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3875
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3876
     *   return result;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3877
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3878
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3879
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3880
     * Note that the saved arguments ({@code a...} in the pseudocode) cannot
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3881
     * be modified by execution of the target, and so are passed unchanged
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3882
     * from the caller to the cleanup, if it is invoked.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3883
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3884
     * The target and cleanup must return the same type, even if the cleanup
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3885
     * always throws.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3886
     * To create such a throwing cleanup, compose the cleanup logic
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3887
     * with {@link #throwException throwException},
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3888
     * in order to create a method handle of the correct return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3889
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3890
     * Note that {@code tryFinally} never converts exceptions into normal returns.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3891
     * In rare cases where exceptions must be converted in that way, first wrap
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3892
     * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3893
     * to capture an outgoing exception, and then wrap with {@code tryFinally}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3894
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3895
     * @param target the handle whose execution is to be wrapped in a {@code try} block.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3896
     * @param cleanup the handle that is invoked in the finally block.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3897
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3898
     * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3899
     * @throws NullPointerException if any argument is null
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3900
     * @throws IllegalArgumentException if {@code cleanup} does not accept
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3901
     *          the required leading arguments, or if the method handle types do
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3902
     *          not match in their return types and their
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3903
     *          corresponding trailing parameters
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3904
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3905
     * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3906
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3907
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3908
    public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3909
        List<Class<?>> targetParamTypes = target.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3910
        List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3911
        Class<?> rtype = target.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3912
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3913
        checkTryFinally(target, cleanup);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3914
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3915
        // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3916
        int tpSize = targetParamTypes.size();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3917
        int cpPrefixLength = rtype == void.class ? 1 : 2;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3918
        int cpSize = cleanupParamTypes.size();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3919
        MethodHandle aCleanup = cpSize - cpPrefixLength < tpSize ?
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3920
                dropArguments(cleanup, cpSize, targetParamTypes.subList(tpSize - (cpSize - cpPrefixLength), tpSize)) :
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3921
                cleanup;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3922
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3923
        MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3924
        aCleanup = aCleanup.asSpreader(Object[].class, tpSize);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3925
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3926
        return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3927
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3928
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3929
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3930
     * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3931
     * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3932
     * before the folded arguments.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3933
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3934
     * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3935
     * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3936
     * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3937
     * 0.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3938
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3939
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3940
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3941
    import static java.lang.invoke.MethodHandles.*;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3942
    import static java.lang.invoke.MethodType.*;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3943
    ...
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3944
    MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3945
    "println", methodType(void.class, String.class))
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3946
    .bindTo(System.out);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3947
    MethodHandle cat = lookup().findVirtual(String.class,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3948
    "concat", methodType(String.class, String.class));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3949
    assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3950
    MethodHandle catTrace = foldArguments(cat, 1, trace);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3951
    // also prints "jum":
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3952
    assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3953
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3954
     * <p> Here is pseudocode for the resulting adapter:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3955
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3956
     * // there are N arguments in A...
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3957
     * T target(Z..., V, A[N]..., B...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3958
     * V combiner(A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3959
     * T adapter(Z... z, A... a, B... b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3960
     *   V v = combiner(a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3961
     *   return target(z..., v, a..., b...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3962
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3963
     * // and if the combiner has a void return:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3964
     * T target2(Z..., A[N]..., B...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3965
     * void combiner2(A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3966
     * T adapter2(Z... z, A... a, B... b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3967
     *   combiner2(a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3968
     *   return target2(z..., a..., b...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3969
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3970
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3971
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3972
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3973
     * variable-arity method handle}, even if the original target method handle was.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3974
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3975
     * @param target the method handle to invoke after arguments are combined
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3976
     * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3977
     *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3978
     * @param combiner method handle to call initially on the incoming arguments
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3979
     * @return method handle which incorporates the specified argument folding logic
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3980
     * @throws NullPointerException if either argument is null
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3981
     * @throws IllegalArgumentException if {@code combiner}'s return type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3982
     *          is non-void and not the same as the argument type at position {@code pos} of
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3983
     *          the target signature, or if the {@code N} argument types at position {@code pos}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3984
     *          of the target signature
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3985
     *          (skipping one matching the {@code combiner}'s return type)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3986
     *          are not identical with the argument types of {@code combiner}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3987
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3988
     * @see #foldArguments(MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3989
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3990
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3991
    public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3992
        MethodType targetType = target.type();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3993
        MethodType combinerType = combiner.type();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3994
        Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3995
        BoundMethodHandle result = target.rebind();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3996
        boolean dropResult = rtype == void.class;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3997
        LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3998
        MethodType newType = targetType;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3999
        if (!dropResult) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4000
            newType = newType.dropParameterTypes(pos, pos + 1);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4001
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4002
        result = result.copyWithExtendL(newType, lform, combiner);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4003
        return result;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4004
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4005
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4006
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4007
     * Wrap creation of a proper zero handle for a given type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4008
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4009
     * @param type the type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4010
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4011
     * @return a zero value for the given type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4012
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4013
    static MethodHandle zeroHandle(Class<?> type) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4014
        return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4015
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4016
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4017
    private static void checkLoop0(MethodHandle[][] clauses) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4018
        if (clauses == null || clauses.length == 0) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4019
            throw newIllegalArgumentException("null or no clauses passed");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4020
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4021
        if (Stream.of(clauses).anyMatch(Objects::isNull)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4022
            throw newIllegalArgumentException("null clauses are not allowed");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4023
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4024
        if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4025
            throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4026
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4027
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4028
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4029
    private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4030
        if (in.type().returnType() != st.type().returnType()) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4031
            throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4032
                    st.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4033
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4034
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4035
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4036
    private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4037
        if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4038
                anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4039
            throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4040
                    " (common suffix: " + commonSuffix + ")");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4041
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4042
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4043
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4044
    private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4045
        if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4046
                anyMatch(t -> t != loopReturnType)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4047
            throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4048
                    loopReturnType + ")");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4049
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4050
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4051
        if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4052
            throw newIllegalArgumentException("no predicate found", pred);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4053
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4054
        if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4055
                anyMatch(t -> t != boolean.class)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4056
            throw newIllegalArgumentException("predicates must have boolean return type", pred);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4057
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4058
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4059
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4060
    private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4061
        if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4062
                map(MethodType::parameterList).anyMatch(pl -> !pl.equals(commonParameterSequence.subList(0, pl.size())))) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4063
            throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4064
                    "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4065
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4066
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4067
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4068
    private static void checkIteratedLoop(MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4069
        if (null == body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4070
            throw newIllegalArgumentException("iterated loop body must not be null");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4071
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4072
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4073
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4074
    private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4075
        Class<?> rtype = target.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4076
        if (rtype != cleanup.type().returnType()) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4077
            throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4078
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4079
        List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4080
        if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4081
            throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4082
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4083
        if (rtype != void.class && cleanupParamTypes.get(1) != rtype) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4084
            throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4085
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4086
        // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4087
        // target parameter list.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4088
        int cleanupArgIndex = rtype == void.class ? 1 : 2;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4089
        if (!cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4090
                equals(target.type().parameterList().subList(0, cleanupParamTypes.size() - cleanupArgIndex))) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4091
            throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4092
                    cleanup.type(), target.type());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4093
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4094
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4095
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4096
}