jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java
author shade
Wed, 08 Jun 2016 11:14:45 +0300
changeset 38861 e567cc17866d
parent 38785 dacdc5add5eb
child 39342 f66a89ed6fca
child 39473 44eb314f5b38
permissions -rw-r--r--
8158851: MH.publicLookup() init circularity, triggered by custom SecurityManager with String concat and -limitmods java.base Reviewed-by: alanb, redestad, jlaskey
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
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    28
import jdk.internal.org.objectweb.asm.ClassWriter;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    29
import jdk.internal.org.objectweb.asm.Opcodes;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    30
import jdk.internal.reflect.CallerSensitive;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    31
import jdk.internal.reflect.Reflection;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    32
import sun.invoke.util.ValueConversions;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    33
import sun.invoke.util.VerifyAccess;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    34
import sun.invoke.util.Wrapper;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    35
import sun.reflect.misc.ReflectUtil;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    36
import sun.security.util.SecurityConstants;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    37
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    38
import java.lang.invoke.LambdaForm.BasicType;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    39
import java.lang.reflect.Constructor;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    40
import java.lang.reflect.Field;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    41
import java.lang.reflect.Member;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    42
import java.lang.reflect.Method;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    43
import java.lang.reflect.Modifier;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    44
import java.lang.reflect.ReflectPermission;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    45
import java.nio.ByteOrder;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    46
import java.security.AccessController;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    47
import java.security.PrivilegedAction;
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    48
import java.util.ArrayList;
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    49
import java.util.Arrays;
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    50
import java.util.BitSet;
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
    51
import java.util.Iterator;
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    52
import java.util.List;
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    53
import java.util.Objects;
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
    54
import java.util.concurrent.ConcurrentHashMap;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    55
import java.util.stream.Collectors;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    56
import java.util.stream.Stream;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    57
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    58
import static java.lang.invoke.MethodHandleImpl.Intrinsic;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    59
import static java.lang.invoke.MethodHandleNatives.Constants.*;
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
    60
import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
    61
import static java.lang.invoke.MethodType.methodType;
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
    62
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    63
/**
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    64
 * 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
    65
 * method handles. They fall into several categories:
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
    66
 * <ul>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
    67
 * <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
    68
 * <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
    69
 * <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
    70
 * </ul>
24367
705490680527 8030709: Tidy warnings cleanup for java.lang package; minor cleanup in java.math, javax.script
yan
parents: 23898
diff changeset
    71
 *
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    72
 * @author John Rose, JSR 292 EG
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
    73
 * @since 1.7
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    74
 */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    75
public class MethodHandles {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    76
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    77
    private MethodHandles() { }  // do not instantiate
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    78
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
    79
    private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
34720
c2192aa0ab88 8144723: MethodHandleImpl.initStatics is no longer needed
redestad
parents: 34430
diff changeset
    80
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    81
    // See IMPL_LOOKUP below.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    82
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    83
    //// Method handle creation from ordinary methods.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    84
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    85
    /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    86
     * Returns a {@link Lookup lookup object} with
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    87
     * 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
    88
     * 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
    89
     * Factory methods on the lookup object can create
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    90
     * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    91
     * 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
    92
     * including protected and private fields and methods.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    93
     * 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
    94
     * 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
    95
     * <p>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    96
     * 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
    97
     * values to different callers.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    98
     * <p>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    99
     * 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
   100
     * has equivalent capabilities to any lookup object
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   101
     * 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
   102
     * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   103
     * executing in the same caller class {@code C}.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   104
     * @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
   105
     */
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   106
    @CallerSensitive
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   107
    public static Lookup lookup() {
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   108
        return new Lookup(Reflection.getCallerClass());
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   109
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   110
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   111
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   112
     * Returns a {@link Lookup lookup object} which is trusted minimally.
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   113
     * It can only be used to create method handles to public members in
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   114
     * public classes in packages that are exported unconditionally.
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   115
     * <p>
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   116
     * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   117
     * object is in an unnamed module.
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   118
     * Consequently, the lookup context of this lookup object will be the bootstrap
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   119
     * class loader, which means it cannot find user classes.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   120
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   121
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   122
     * <em>Discussion:</em>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   123
     * 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
   124
     * {@link Lookup#in publicLookup().in(C.class)}.
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   125
     * but may change the lookup context by virtue of changing the class loader.
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   126
     * 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
   127
     * <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
   128
     * Also, it cannot access
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   129
     * <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
   130
     * @return a lookup object which is trusted minimally
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   131
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   132
    public static Lookup publicLookup() {
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   133
        // During VM startup then only classes in the java.base module can be
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   134
        // loaded and linked. This is because java.base exports aren't setup until
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   135
        // the module system is initialized, hence types in the unnamed module
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   136
        // (or any named module) can't link to java/lang/Object.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   137
        if (!jdk.internal.misc.VM.isModuleSystemInited()) {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   138
            return new Lookup(Object.class, Lookup.PUBLIC);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   139
        } else {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   140
            return LookupHelper.PUBLIC_LOOKUP;
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   141
        }
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   142
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   143
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   144
    /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   145
     * Performs an unchecked "crack" of a
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   146
     * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   147
     * The result is as if the user had obtained a lookup object capable enough
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   148
     * to crack the target method handle, called
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   149
     * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   150
     * on the target to obtain its symbolic reference, and then called
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   151
     * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   152
     * to resolve the symbolic reference to a member.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   153
     * <p>
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   154
     * If there is a security manager, its {@code checkPermission} method
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   155
     * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   156
     * @param <T> the desired type of the result, either {@link Member} or a subtype
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   157
     * @param target a direct method handle to crack into symbolic reference components
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   158
     * @param expected a class object representing the desired result type {@code T}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   159
     * @return a reference to the method, constructor, or field object
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   160
     * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   161
     * @exception NullPointerException if either argument is {@code null}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   162
     * @exception IllegalArgumentException if the target is not a direct method handle
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   163
     * @exception ClassCastException if the member is not of the expected type
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   164
     * @since 1.8
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   165
     */
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   166
    public static <T extends Member> T
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   167
    reflectAs(Class<T> expected, MethodHandle target) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   168
        SecurityManager smgr = System.getSecurityManager();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   169
        if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   170
        Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   171
        return lookup.revealDirect(target).reflectAs(expected, lookup);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   172
    }
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   173
    // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
   174
    private static final java.security.Permission ACCESS_PERMISSION =
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   175
        new ReflectPermission("suppressAccessChecks");
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   176
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   177
    /**
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   178
     * 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
   179
     * when the creation requires access checking.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   180
     * Method handles do not perform
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   181
     * 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
   182
     * Therefore, method handle access
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   183
     * 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
   184
     * The caller class against which those restrictions are enforced
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   185
     * is known as the {@linkplain #lookupClass lookup class}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   186
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   187
     * 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
   188
     * {@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
   189
     * 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
   190
     * determined, and securely stored in the {@code Lookup} object.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   191
     * 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
   192
     * 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
   193
     * 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
   194
     * even private ones.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   195
     *
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   196
     * <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
   197
     * 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
   198
     * use cases for methods, constructors, and fields.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   199
     * 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
   200
     * equivalent of a particular <em>bytecode behavior</em>.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   201
     * (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
   202
     * 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
   203
     * the behavior of the resulting method handles:
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   204
     * <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
   205
     * <tr>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   206
     *     <th><a name="equiv"></a>lookup expression</th>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   207
     *     <th>member</th>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   208
     *     <th>bytecode behavior</th>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   209
     * </tr>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   210
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   211
     *     <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
   212
     *     <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
   213
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   214
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   215
     *     <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
   216
     *     <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
   217
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   218
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   219
     *     <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
   220
     *     <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
   221
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   222
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   223
     *     <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
   224
     *     <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
   225
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   226
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   227
     *     <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
   228
     *     <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
   229
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   230
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   231
     *     <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
   232
     *     <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
   233
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   234
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   235
     *     <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
   236
     *     <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
   237
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   238
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   239
     *     <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
   240
     *     <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
   241
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   242
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   243
     *     <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
   244
     *     <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
   245
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   246
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   247
     *     <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
   248
     *     <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
   249
     * </tr>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   250
     * <tr>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   251
     *     <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
   252
     *     <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
   253
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   254
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   255
     *     <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
   256
     *     <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
   257
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   258
     * <tr>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   259
     *     <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
   260
     *     <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
   261
     * </tr>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   262
     * <tr>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   263
     *     <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
   264
     *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   265
     * </tr>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   266
     * </table>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   267
     *
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   268
     * 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
   269
     * 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
   270
     * 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
   271
     * and the sequence of argument types {@code A*}.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   272
     * 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
   273
     * 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
   274
     * 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
   275
     * 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
   276
     * 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
   277
     * (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
   278
     * 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
   279
     * 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
   280
     * 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
   281
     * 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
   282
     * and {@code this} otherwise.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   283
     * 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
   284
     * for reflective objects corresponding to the given members.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   285
     * <p>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   286
     * 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
   287
     * as if by {@code ldc CONSTANT_Class}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   288
     * 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
   289
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   290
     * 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
   291
     * 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
   292
     * 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
   293
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   294
     * <em>Discussion:</em>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   295
     * 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
   296
     * class members and bytecode behaviors
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   297
     * can break down in a few ways:
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   298
     * <ul style="font-size:smaller;">
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   299
     * <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
   300
     * 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
   301
     * Java expression or bytecoded constant.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   302
     * <li>Likewise, if {@code T} or {@code MT}
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   303
     * 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
   304
     * the lookup can still succeed.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   305
     * 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
   306
     * {@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
   307
     * <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
   308
     * 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
   309
     * 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
   310
     * 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
   311
     * <li>If the looked-up method has a
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
   312
     * <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
   313
     * 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
   314
     * type having too many parameters.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   315
     * </ul>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   316
     *
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   317
     * <h1><a name="access"></a>Access checking</h1>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   318
     * 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
   319
     * when a method handle is created.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   320
     * 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
   321
     * {@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
   322
     * performs access checking against every caller, on every call.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   323
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   324
     * 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
   325
     * compares its recorded lookup class against all requests to
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   326
     * create method handles.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   327
     * 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
   328
     * 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
   329
     * lookup class.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   330
     * <p>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   331
     * 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
   332
     * such as a metaobject protocol.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   333
     * A shared {@code Lookup} object delegates the capability
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   334
     * 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
   335
     * Even if privileged code uses the {@code Lookup} object,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   336
     * 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
   337
     * original lookup class.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   338
     * <p>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   339
     * A lookup can fail, because
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   340
     * 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
   341
     * 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
   342
     * 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
   343
     * 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
   344
     * 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
   345
     * 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
   346
     * the following:
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   347
     * <ul>
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   348
     * <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
   349
     * <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
   350
     * <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
   351
     * </ul>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   352
     * <p>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   353
     * 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
   354
     * 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
   355
     * 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
   356
     * 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
   357
     * 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
   358
     * checked exception, such as {@code NoSuchMethodException}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   359
     * 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
   360
     * 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
   361
     * 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
   362
     * 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
   363
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   364
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   365
     * Access checks only apply to named and reflected methods,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   366
     * constructors, and fields.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   367
     * Other method handle creation methods, such as
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   368
     * {@link MethodHandle#asType MethodHandle.asType},
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   369
     * do not require any access checks, and are used
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   370
     * independently of any {@code Lookup} object.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   371
     * <p>
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   372
     * 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
   373
     * 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
   374
     * 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
   375
     * (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
   376
     * 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
   377
     * 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
   378
     * 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
   379
     * 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
   380
     * {@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
   381
     * (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
   382
     * to the lookup class itself.
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   383
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   384
     * 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
   385
     * 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
   386
     * 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
   387
     * 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
   388
     * (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
   389
     * <p>
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   390
     * 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
   391
     * 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
   392
     * 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
   393
     * 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
   394
     * 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
   395
     * <p>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   396
     * 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
   397
     * 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
   398
     * in the same top-level declaration.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   399
     * For example, a nested class {@code C.D}
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   400
     * 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
   401
     * {@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
   402
     * 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
   403
     * 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
   404
     * {@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
   405
     * 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
   406
     * 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
   407
     * classes, without special elevation of privilege.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   408
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   409
     * 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
   410
     * according to its set of {@link #lookupModes lookupModes},
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   411
     * 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
   412
     * For example, the {@link MethodHandles#publicLookup publicLookup}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   413
     * method produces a lookup object which is only allowed to access
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   414
     * public members in public classes of exported packages.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   415
     * The caller sensitive method {@link MethodHandles#lookup lookup}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   416
     * produces a lookup object with full capabilities relative to
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   417
     * its caller class, to emulate all supported bytecode behaviors.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   418
     * 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
   419
     * with fewer access modes than the original lookup object.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   420
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   421
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   422
     * <a name="privacc"></a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   423
     * <em>Discussion of private access:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   424
     * 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
   425
     * if its {@linkplain #lookupModes lookup modes}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   426
     * include the possibility of accessing {@code private} members.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   427
     * As documented in the relevant methods elsewhere,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   428
     * only lookups with private access possess the following capabilities:
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   429
     * <ul style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   430
     * <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
   431
     * <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
   432
     *     such as {@code Class.forName}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   433
     * <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
   434
     * <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
   435
     *     for classes accessible to the lookup class
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   436
     * <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
   437
     *     within the same package member
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   438
     * </ul>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   439
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   440
     * 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
   441
     * 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
   442
     * 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
   443
     * can be reliably determined and emulated by method handles.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   444
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   445
     * <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
   446
     * Although bytecode instructions can only refer to classes in
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   447
     * 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
   448
     * 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
   449
     * 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
   450
     * Core Reflection API, and are impossible to bytecode instructions
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   451
     * such as {@code invokestatic} or {@code getfield}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   452
     * 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
   453
     * to allow applications to check such cross-loader references.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   454
     * 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
   455
     * and the Core Reflection API
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   456
     * (as found on {@link java.lang.Class Class}).
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   457
     * <p>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   458
     * 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
   459
     * additional checks.
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   460
     * 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
   461
     * 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
   462
     * {@link java.lang.SecurityException SecurityException}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   463
     * Define {@code smgr} as the security manager,
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   464
     * {@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
   465
     * {@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
   466
     * 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
   467
     * member is actually defined.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   468
     * (If a class or other type is being accessed,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   469
     * 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
   470
     * 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
   471
     * if the current lookup object does not have
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   472
     * <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
   473
     * The calls are made according to the following rules:
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   474
     * <ul>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   475
     * <li><b>Step 1:</b>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   476
     *     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
   477
     *     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
   478
     *     then {@link SecurityManager#checkPackageAccess
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   479
     *     smgr.checkPackageAccess(refcPkg)} is called,
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   480
     *     where {@code refcPkg} is the package of {@code refc}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   481
     * <li><b>Step 2a:</b>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   482
     *     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
   483
     *     {@code lookc} is not present, then
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   484
     *     {@link SecurityManager#checkPermission smgr.checkPermission}
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   485
     *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   486
     * <li><b>Step 2b:</b>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   487
     *     If the retrieved class has a {@code null} class loader,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   488
     *     and {@code lookc} is not present, then
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   489
     *     {@link SecurityManager#checkPermission smgr.checkPermission}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   490
     *     with {@code RuntimePermission("getClassLoader")} is called.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   491
     * <li><b>Step 3:</b>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   492
     *     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
   493
     *     and if {@code lookc} is not present,
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   494
     *     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
   495
     *     then {@link SecurityManager#checkPackageAccess
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   496
     *     smgr.checkPackageAccess(defcPkg)} is called,
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   497
     *     where {@code defcPkg} is the package of {@code defc}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   498
     * </ul>
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   499
     * Security checks are performed after other access checks have passed.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   500
     * 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
   501
     * 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
   502
     * 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
   503
     *
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   504
     * <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
   505
     * 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
   506
     * 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
   507
     * identity of its immediate caller.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   508
     * <p>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   509
     * 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
   510
     * 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
   511
     * 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
   512
     * 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
   513
     * 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
   514
     * 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
   515
     * (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
   516
     * 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
   517
     * different lookup classes may give rise to
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   518
     * differently behaving method handles.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   519
     * <p>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   520
     * In cases where the lookup object is
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   521
     * {@link MethodHandles#publicLookup() publicLookup()},
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   522
     * or some other lookup object without
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   523
     * <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
   524
     * the lookup class is disregarded.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   525
     * 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
   526
     * 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
   527
     * {@code IllegalAccessException}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   528
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   529
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   530
     * For example, the caller-sensitive method
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   531
     * {@link java.lang.Class#forName(String) Class.forName(x)}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   532
     * can return varying classes or throw varying exceptions,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   533
     * 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
   534
     * 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
   535
     * 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
   536
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   537
     * If an application caches method handles for broad sharing,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   538
     * it should use {@code publicLookup()} to create them.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   539
     * 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
   540
     * 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
   541
     * 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
   542
     * bootstrap method, can incorporate the specific identity
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   543
     * of the caller, making the method accessible.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   544
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   545
     * The function {@code MethodHandles.lookup} is caller sensitive
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   546
     * 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
   547
     * 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
   548
     * objects to check access requests.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   549
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   550
    public static final
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   551
    class Lookup {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   552
        /** 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
   553
        private final Class<?> lookupClass;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   554
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   555
        /** 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
   556
        private final int allowedModes;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   557
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   558
        /** A single-bit mask representing {@code public} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   559
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   560
         *  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
   561
         *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   562
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   563
        public static final int PUBLIC = Modifier.PUBLIC;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   564
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   565
        /** A single-bit mask representing {@code private} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   566
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   567
         *  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
   568
         *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   569
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   570
        public static final int PRIVATE = Modifier.PRIVATE;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   571
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   572
        /** A single-bit mask representing {@code protected} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   573
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   574
         *  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
   575
         *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   576
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   577
        public static final int PROTECTED = Modifier.PROTECTED;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   578
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   579
        /** A single-bit mask representing {@code package} access (default access),
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   580
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   581
         *  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
   582
         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   583
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   584
        public static final int PACKAGE = Modifier.STATIC;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   585
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   586
        /** A single-bit mask representing {@code module} access (default access),
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   587
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   588
         *  The value is {@code 0x10}, which does not correspond meaningfully to
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   589
         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   590
         *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   591
         *  with this lookup mode can access all public types in the module of the
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   592
         *  lookup class and public types in packages exported by other modules
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   593
         *  to the module of the lookup class.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   594
         *  @since 9
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   595
         */
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   596
        public static final int MODULE = PACKAGE << 1;
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   597
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   598
        private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   599
        private static final int TRUSTED   = -1;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   600
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   601
        private static int fixmods(int mods) {
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   602
            mods &= (ALL_MODES - PACKAGE - MODULE);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   603
            return (mods != 0) ? mods : (PACKAGE | MODULE);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   604
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   605
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   606
        /** 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
   607
         *  which checks are performed for visibility and access permissions.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   608
         *  <p>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   609
         *  The class implies a maximum level of access permission,
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   610
         *  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
   611
         *  {@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
   612
         *  can be accessed.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   613
         *  @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
   614
         */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   615
        public Class<?> lookupClass() {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   616
            return lookupClass;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   617
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   618
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   619
        // This is just for calling out to MethodHandleImpl.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   620
        private Class<?> lookupClassOrNull() {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   621
            return (allowedModes == TRUSTED) ? null : lookupClass;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   622
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   623
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   624
        /** 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
   625
         *  The result is a bit-mask of the bits
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   626
         *  {@linkplain #PUBLIC PUBLIC (0x01)},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   627
         *  {@linkplain #PRIVATE PRIVATE (0x02)},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   628
         *  {@linkplain #PROTECTED PROTECTED (0x04)},
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   629
         *  {@linkplain #PACKAGE PACKAGE (0x08)},
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   630
         *  and {@linkplain #MODULE MODULE (0x10)}.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   631
         *  <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   632
         *  A freshly-created lookup object
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   633
         *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   634
         *  has all possible bits set, since the caller class can access all its own members,
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   635
         *  all public types in the caller's module, and all public types in packages exported
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   636
         *  by other modules to the caller's module.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   637
         *  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
   638
         *  {@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
   639
         *  may have some mode bits set to zero.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   640
         *  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
   641
         *  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
   642
         *  lookup object, and also by the new lookup class.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   643
         *  @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
   644
         */
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   645
        public int lookupModes() {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   646
            return allowedModes & ALL_MODES;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   647
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   648
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   649
        /** 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
   650
         * for method handle creation.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   651
         * 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
   652
         * 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
   653
         */
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   654
        Lookup(Class<?> lookupClass) {
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   655
            this(lookupClass, ALL_MODES);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   656
            // make sure we haven't accidentally picked up a privileged class:
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   657
            checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   658
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   659
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   660
        private Lookup(Class<?> lookupClass, int allowedModes) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   661
            this.lookupClass = lookupClass;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   662
            this.allowedModes = allowedModes;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   663
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   664
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   665
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   666
         * Creates a lookup on the specified new lookup class.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   667
         * The resulting object will report the specified
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   668
         * class as its own {@link #lookupClass lookupClass}.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   669
         * <p>
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   670
         * However, the resulting {@code Lookup} object is guaranteed
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   671
         * 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
   672
         * In particular, access capabilities can be lost as follows:<ul>
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   673
         * <li>If the lookup class for this {@code Lookup} is not in a named module,
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   674
         * and the new lookup class is in a named module {@code M}, then no members in
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   675
         * {@code M}'s non-exported packages will be accessible.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   676
         * <li>If the lookup for this {@code Lookup} is in a named module, and the
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   677
         * new lookup class is in a different module {@code M}, then no members, not even
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   678
         * public members in {@code M}'s exported packages, will be accessible.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   679
         * <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
   680
         * 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
   681
         * (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
   682
         * <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
   683
         * 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
   684
         * <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
   685
         * 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
   686
         * <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
   687
         * 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
   688
         * (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
   689
         * </ul>
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   690
         * <p>
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   691
         * The resulting lookup's capabilities for loading classes
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   692
         * (used during {@link #findClass} invocations)
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   693
         * are determined by the lookup class' loader,
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   694
         * which may change due to this operation.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   695
         *
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   696
         * @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
   697
         * @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
   698
         * @throws NullPointerException if the argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   699
         */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   700
        public Lookup in(Class<?> requestedLookupClass) {
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
   701
            Objects.requireNonNull(requestedLookupClass);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   702
            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
   703
                return new Lookup(requestedLookupClass, ALL_MODES);
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   704
            if (requestedLookupClass == this.lookupClass)
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   705
                return this;  // keep same capabilities
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   706
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   707
            int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   708
            if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   709
                // Allowed to teleport from an unnamed to a named module but resulting
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   710
                // Lookup has no access to module private members
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   711
                if (this.lookupClass.getModule().isNamed()) {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   712
                    newModes = 0;
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   713
                } else {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   714
                    newModes &= ~MODULE;
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   715
                }
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   716
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   717
            if ((newModes & PACKAGE) != 0
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   718
                && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   719
                newModes &= ~(PACKAGE|PRIVATE);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   720
            }
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   721
            // Allow nestmate lookups to be created without special privilege:
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   722
            if ((newModes & PRIVATE) != 0
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   723
                && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   724
                newModes &= ~PRIVATE;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   725
            }
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
   726
            if ((newModes & PUBLIC) != 0
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
   727
                && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   728
                // 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
   729
                // No permissions.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   730
                newModes = 0;
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   731
            }
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   732
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   733
            checkUnprivilegedlookupClass(requestedLookupClass, newModes);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   734
            return new Lookup(requestedLookupClass, newModes);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   735
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   736
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   737
        // Make sure outer class is initialized first.
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
   738
        static { IMPL_NAMES.getClass(); }
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   739
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   740
        /** Package-private version of lookup which is trusted. */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   741
        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
   742
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   743
        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
   744
            String name = lookupClass.getName();
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   745
            if (name.startsWith("java.lang.invoke."))
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   746
                throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   747
37669
6ba0f2bb6e30 8154447: Exempt classes under java.util.concurrent from MH.Lookup restrictions
psandoz
parents: 37668
diff changeset
   748
            // For caller-sensitive MethodHandles.lookup() disallow lookup from
6ba0f2bb6e30 8154447: Exempt classes under java.util.concurrent from MH.Lookup restrictions
psandoz
parents: 37668
diff changeset
   749
            // restricted packages.  This a fragile and blunt approach.
6ba0f2bb6e30 8154447: Exempt classes under java.util.concurrent from MH.Lookup restrictions
psandoz
parents: 37668
diff changeset
   750
            // TODO replace with a more formal and less fragile mechanism
6ba0f2bb6e30 8154447: Exempt classes under java.util.concurrent from MH.Lookup restrictions
psandoz
parents: 37668
diff changeset
   751
            // that does not bluntly restrict classes under packages within
6ba0f2bb6e30 8154447: Exempt classes under java.util.concurrent from MH.Lookup restrictions
psandoz
parents: 37668
diff changeset
   752
            // java.base from looking up MethodHandles or VarHandles.
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   753
            if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
37669
6ba0f2bb6e30 8154447: Exempt classes under java.util.concurrent from MH.Lookup restrictions
psandoz
parents: 37668
diff changeset
   754
                if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) ||
20825
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   755
                        (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   756
                    throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   757
                }
3d5429b4b601 8017196: Ensure Proxies are handled appropriately
mchung
parents: 18569
diff changeset
   758
            }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   759
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   760
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   761
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   762
         * 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
   763
         * (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
   764
         * 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
   765
         * 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
   766
         * 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
   767
         * allowed access, and is chosen as follows:
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   768
         * <ul>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   769
         * <li>If no access is allowed, the suffix is "/noaccess".
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   770
         * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   771
         * <li>If only public and module access are allowed, the suffix is "/module".
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   772
         * <li>If only public, module and package access are allowed, the suffix is "/package".
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   773
         * <li>If only public, module, package, and private access are allowed, the suffix is "/private".
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   774
         * </ul>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   775
         * If none of the above cases apply, it is the case that full
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   776
         * access (public, module, package, private, and protected) is allowed.
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   777
         * In this case, no suffix is added.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   778
         * 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
   779
         * {@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
   780
         * 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
   781
         * 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
   782
         * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   783
         * (It may seem strange that protected access should be
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   784
         * stronger than private access.  Viewed independently from
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   785
         * 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
   786
         * because it requires a direct subclass relationship between
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   787
         * caller and callee.)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   788
         * @see #in
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   789
         */
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   790
        @Override
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   791
        public String toString() {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   792
            String cname = lookupClass.getName();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   793
            switch (allowedModes) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   794
            case 0:  // no privileges
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   795
                return cname + "/noaccess";
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   796
            case PUBLIC:
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   797
                return cname + "/public";
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   798
            case PUBLIC|MODULE:
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   799
                return cname + "/module";
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   800
            case PUBLIC|MODULE|PACKAGE:
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   801
                return cname + "/package";
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   802
            case ALL_MODES & ~PROTECTED:
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   803
                return cname + "/private";
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   804
            case ALL_MODES:
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   805
                return cname;
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   806
            case TRUSTED:
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   807
                return "/trusted";  // internal only; not exported
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   808
            default:  // Should not happen, but it's a bitfield...
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   809
                cname = cname + "/" + Integer.toHexString(allowedModes);
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   810
                assert(false) : cname;
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   811
                return cname;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   812
            }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   813
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   814
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   815
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   816
         * Produces a method handle for a static method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   817
         * 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
   818
         * (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
   819
         * 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
   820
         * 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
   821
         * 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
   822
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   823
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   824
         * {@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
   825
         * 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
   826
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   827
         * 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
   828
         * 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
   829
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
   830
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   831
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
   832
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
   833
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   834
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
   835
  "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
   836
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
   837
         * }</pre></blockquote>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   838
         * @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
   839
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   840
         * @param type the type of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   841
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   842
         * @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
   843
         * @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
   844
         *                                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
   845
         *                                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
   846
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   847
         * @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
   848
         *                              <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
   849
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   850
         */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   851
        public
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   852
        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
   853
            MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
   854
            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
   855
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   856
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   857
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   858
         * Produces a method handle for a virtual method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   859
         * 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
   860
         * with the receiver type (usually {@code refc}) prepended.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   861
         * 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
   862
         * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   863
         * 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
   864
         * 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
   865
         * implementation to enter.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   866
         * (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
   867
         * {@code invokevirtual} or {@code invokeinterface} instruction.)
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   868
         * <p>
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   869
         * 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
   870
         * 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
   871
         * 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
   872
         * 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
   873
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   874
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   875
         * {@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
   876
         * 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
   877
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   878
         * 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
   879
         * instructions and method handles produced by {@code findVirtual},
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   880
         * 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
   881
         * {@code invokeExact} or {@code invoke}, the resulting
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   882
         * 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
   883
         * {@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
   884
         * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   885
         * with the same {@code type} argument.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   886
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   887
         * If the class is {@code VarHandle} and the name string corresponds to
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   888
         * the name of a signature-polymorphic access mode method, the resulting
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   889
         * method handle is equivalent to one produced by
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   890
         * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   891
         * the access mode corresponding to the name string and with the same
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   892
         * {@code type} arguments.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   893
         * <p>
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   894
         * <b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
   895
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   896
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
   897
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
   898
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   899
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
   900
  "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
   901
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
   902
  "hashCode", methodType(int.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   903
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
   904
  "hashCode", methodType(int.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   905
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
   906
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
   907
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
   908
// interface method:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   909
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
   910
  "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
   911
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
   912
// 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
   913
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
   914
try { assertEquals("impossible", lookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   915
        .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
   916
 } catch (NoSuchMethodException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   917
MethodHandle MH_newString = publicLookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   918
  .findConstructor(String.class, MT_newString);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   919
assertEquals("", (String) MH_newString.invokeExact());
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   920
         * }</pre></blockquote>
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   921
         *
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
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   923
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   924
         * @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
   925
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   926
         * @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
   927
         * @throws IllegalAccessException if access checking fails,
35772
044f660251cc 8138884: MethodHandles.Lookup.findVirtual() Javadoc fails to consider private interface methods
srastogi
parents: 35716
diff changeset
   928
         *                                or if the method is {@code static},
044f660251cc 8138884: MethodHandles.Lookup.findVirtual() Javadoc fails to consider private interface methods
srastogi
parents: 35716
diff changeset
   929
         *                                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
   930
         *                                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
   931
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   932
         * @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
   933
         *                              <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
   934
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   935
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   936
        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
   937
            if (refc == MethodHandle.class) {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   938
                MethodHandle mh = findVirtualForMH(name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   939
                if (mh != null)  return mh;
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   940
            } else if (refc == VarHandle.class) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   941
                MethodHandle mh = findVirtualForVH(name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   942
                if (mh != null)  return mh;
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   943
            }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   944
            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
   945
            MemberName method = resolveOrFail(refKind, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
   946
            return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
   947
        }
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   948
        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
   949
            // 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
   950
            if ("invoke".equals(name))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   951
                return invoker(type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   952
            if ("invokeExact".equals(name))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   953
                return exactInvoker(type);
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
   954
            if ("invokeBasic".equals(name))
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
   955
                return basicInvoker(type);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   956
            assert(!MemberName.isMethodHandleInvokeName(name));
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   957
            return null;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   958
        }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   959
        private MethodHandle findVirtualForVH(String name, MethodType type) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   960
            try {
37343
35a2231828a7 8151705: VarHandle.AccessMode enum names should conform to code style
psandoz
parents: 37340
diff changeset
   961
                return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   962
            } catch (IllegalArgumentException e) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   963
                return null;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   964
            }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
   965
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   966
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   967
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   968
         * 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
   969
         * the constructor of the specified type.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   970
         * 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
   971
         * 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
   972
         * 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
   973
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   974
         * 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
   975
         * (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
   976
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   977
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
   978
         * {@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
   979
         * 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
   980
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
   981
         * 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
   982
         * 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
   983
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
   984
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   985
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
   986
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
   987
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   988
MethodHandle MH_newArrayList = publicLookup().findConstructor(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   989
  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
   990
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
   991
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
   992
assert(orig != copy);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   993
assertEquals(orig, copy);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   994
// a variable-arity constructor:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   995
MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   996
  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
   997
ProcessBuilder pb = (ProcessBuilder)
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   998
  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
   999
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
  1000
         * }</pre></blockquote>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1001
         * @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
  1002
         * @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
  1003
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1004
         * @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
  1005
         * @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
  1006
         *                                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
  1007
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1008
         * @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
  1009
         *                              <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
  1010
         * @throws NullPointerException if any argument is null
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1011
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1012
        public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
37674
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  1013
            if (refc.isArray()) {
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  1014
                throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  1015
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1016
            String name = "<init>";
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1017
            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
  1018
            return getDirectConstructor(refc, ctor);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1019
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1020
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1021
        /**
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1022
         * 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
  1023
         * initializer of the class is not run.
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1024
         * <p>
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1025
         * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1026
         * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1027
         * load the requested class, and then determines whether the class is accessible to this lookup object.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1028
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1029
         * @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
  1030
         * @return the requested class.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1031
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1032
         *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1033
         * @throws LinkageError if the linkage fails
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1034
         * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1035
         * @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
  1036
         * modes.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1037
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1038
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1039
         * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1040
         */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1041
        public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1042
            Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1043
            return accessClass(targetClass);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1044
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1045
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1046
        /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1047
         * 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
  1048
         * static initializer of the class is not run.
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1049
         * <p>
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1050
         * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1051
         * {@linkplain #lookupModes() lookup modes}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1052
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1053
         * @param targetClass the class to be access-checked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1054
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1055
         * @return the class that has been access-checked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1056
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1057
         * @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
  1058
         * modes.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1059
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1060
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1061
         * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1062
         */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1063
        public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1064
            if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1065
                throw new MemberName(targetClass).makeAccessException("access violation", this);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1066
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1067
            checkSecurityManager(targetClass, null);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1068
            return targetClass;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1069
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1070
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1071
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1072
         * 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
  1073
         * 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
  1074
         * <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
  1075
         * 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
  1076
         * 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
  1077
         * with a suitably restricted receiver type prepended.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1078
         * (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
  1079
         * 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
  1080
         * to the lookup object.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1081
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1082
         * Before method resolution,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1083
         * 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
  1084
         * 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
  1085
         * <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
  1086
         * privileges, the access fails.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1087
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1088
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1089
         * {@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
  1090
         * 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
  1091
         * <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
  1092
         * <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
  1093
         * 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
  1094
         * 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
  1095
         * 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
  1096
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  1097
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1098
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
  1099
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
  1100
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1101
static class Listie extends ArrayList {
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1102
  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
  1103
  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
  1104
}
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1105
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1106
// 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
  1107
MethodHandle MH_newListie = Listie.lookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1108
  .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
  1109
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
  1110
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
  1111
        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
  1112
 } catch (NoSuchMethodException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1113
// 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
  1114
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
  1115
  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
  1116
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
  1117
  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
  1118
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
  1119
  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
  1120
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
  1121
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
  1122
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
  1123
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
  1124
        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
  1125
 } catch (IllegalAccessException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1126
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
  1127
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
  1128
         * }</pre></blockquote>
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1129
         *
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1130
         * @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
  1131
         * @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
  1132
         * @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
  1133
         * @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
  1134
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1135
         * @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
  1136
         * @throws IllegalAccessException if access checking fails,
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1137
         *                                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
  1138
         *                                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
  1139
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1140
         * @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
  1141
         *                              <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
  1142
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1143
         */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1144
        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
  1145
                                        Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1146
            checkSpecialCaller(specialCaller, refc);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1147
            Lookup specialLookup = this.in(specialCaller);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1148
            MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1149
            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
  1150
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1151
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1152
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1153
         * 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
  1154
         * 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
  1155
         * value type.
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1156
         * 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
  1157
         * the field.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1158
         * 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
  1159
         * @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
  1160
         * @param name the field's name
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1161
         * @param type the field's type
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1162
         * @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
  1163
         * @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
  1164
         * @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
  1165
         * @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
  1166
         *                              <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
  1167
         * @throws NullPointerException if any argument is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1168
         * @see #findVarHandle(Class, String, Class)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1169
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1170
        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
  1171
            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
  1172
            return getDirectField(REF_getField, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1173
        }
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1174
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1175
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1176
         * 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
  1177
         * 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
  1178
         * The method handle will take two arguments, the instance containing
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1179
         * the field, and the value to be stored.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1180
         * The second argument will be of the field's value type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1181
         * 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
  1182
         * @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
  1183
         * @param name the field's name
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1184
         * @param type the field's type
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1185
         * @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
  1186
         * @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
  1187
         * @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
  1188
         * @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
  1189
         *                              <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
  1190
         * @throws NullPointerException if any argument is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1191
         * @see #findVarHandle(Class, String, Class)
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1192
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1193
        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
  1194
            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
  1195
            return getDirectField(REF_putField, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1196
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1197
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1198
        /**
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1199
         * Produces a VarHandle giving access to non-static fields of type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1200
         * {@code T} declared by a receiver class of type {@code R}, supporting
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1201
         * shape {@code (R : T)}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1202
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1203
         * Access checking is performed immediately on behalf of the lookup
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1204
         * class.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1205
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1206
         * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1207
         * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1208
         * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1209
         * <li>if the field is declared {@code final}, then the write, atomic
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1210
         *     update, and numeric atomic update access modes are unsupported.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1211
         * <li>if the field type is anything other than {@code int},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1212
         *     {@code long} or a reference type, then atomic update access modes
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1213
         *     are unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1214
         *     support additional types for certain currently unsupported access
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1215
         *     modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1216
         * <li>if the field type is anything other than {@code int} or
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1217
         *     {@code long}, then numeric atomic update access modes are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1218
         *     unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1219
         *     support additional numeric types for certain currently
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1220
         *     unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1221
         * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1222
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1223
         * If the field is declared {@code volatile} then the returned VarHandle
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1224
         * will override access to the field (effectively ignore the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1225
         * {@code volatile} declaration) in accordance to it's specified
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1226
         * access modes.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1227
         * @param recv the receiver class, of type {@code R}, that declares the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1228
         * non-static field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1229
         * @param name the field's name
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1230
         * @param type the field's type, of type {@code T}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1231
         * @return a VarHandle giving access to non-static fields.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1232
         * @throws NoSuchFieldException if the field does not exist
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1233
         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1234
         * @exception SecurityException if a security manager is present and it
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1235
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1236
         * @throws NullPointerException if any argument is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1237
         * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1238
         */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1239
        public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1240
            MemberName getField = resolveOrFail(REF_getField, recv, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1241
            MemberName putField = resolveOrFail(REF_putField, recv, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1242
            return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1243
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1244
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1245
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1246
         * 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
  1247
         * 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
  1248
         * value type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1249
         * The method handle will take no arguments.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1250
         * 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
  1251
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1252
         * 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
  1253
         * 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
  1254
         * @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
  1255
         * @param name the field's name
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1256
         * @param type the field's type
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1257
         * @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
  1258
         * @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
  1259
         * @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
  1260
         * @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
  1261
         *                              <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
  1262
         * @throws NullPointerException if any argument is null
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1263
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1264
        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
  1265
            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
  1266
            return getDirectField(REF_getStatic, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1267
        }
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1268
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1269
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1270
         * 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
  1271
         * 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
  1272
         * The method handle will take a single
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1273
         * 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
  1274
         * 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
  1275
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1276
         * 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
  1277
         * 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
  1278
         * @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
  1279
         * @param name the field's name
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1280
         * @param type the field's type
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1281
         * @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
  1282
         * @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
  1283
         * @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
  1284
         * @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
  1285
         *                              <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
  1286
         * @throws NullPointerException if any argument is null
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1287
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1288
        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
  1289
            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
  1290
            return getDirectField(REF_putStatic, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1291
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1292
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1293
        /**
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1294
         * Produces a VarHandle giving access to a static field of type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1295
         * {@code T} declared by a given declaring class, supporting shape
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1296
         * {@code ((empty) : T)}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1297
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1298
         * Access checking is performed immediately on behalf of the lookup
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1299
         * class.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1300
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1301
         * If the returned VarHandle is operated on, the declaring class will be
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1302
         * initialized, if it has not already been initialized.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1303
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1304
         * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1305
         * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1306
         * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1307
         * <li>if the field is declared {@code final}, then the write, atomic
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1308
         *     update, and numeric atomic update access modes are unsupported.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1309
         * <li>if the field type is anything other than {@code int},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1310
         *     {@code long} or a reference type, then atomic update access modes
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1311
         *     are unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1312
         *     support additional types for certain currently unsupported access
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1313
         *     modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1314
         * <li>if the field type is anything other than {@code int} or
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1315
         *     {@code long}, then numeric atomic update access modes are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1316
         *     unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1317
         *     support additional numeric types for certain currently
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1318
         *     unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1319
         * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1320
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1321
         * If the field is declared {@code volatile} then the returned VarHandle
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1322
         * will override access to the field (effectively ignore the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1323
         * {@code volatile} declaration) in accordance to it's specified
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1324
         * access modes.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1325
         * @param decl the class that declares the static field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1326
         * @param name the field's name
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1327
         * @param type the field's type, of type {@code T}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1328
         * @return a VarHandle giving access to a static field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1329
         * @throws NoSuchFieldException if the field does not exist
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1330
         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1331
         * @exception SecurityException if a security manager is present and it
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1332
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1333
         * @throws NullPointerException if any argument is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1334
         * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1335
         */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1336
        public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1337
            MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1338
            MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1339
            return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1340
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1341
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1342
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1343
         * 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
  1344
         * 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
  1345
         * 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
  1346
         * 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
  1347
         * 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
  1348
         * without any insertion of an additional receiver parameter.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1349
         * 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
  1350
         * 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
  1351
         * requested method on the given receiver.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1352
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1353
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1354
         * {@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
  1355
         * 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
  1356
         * <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
  1357
         * (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
  1358
         * 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
  1359
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1360
         * This is equivalent to the following code:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1361
         * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1362
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
  1363
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
  1364
...
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1365
MethodHandle mh0 = lookup().findVirtual(defc, name, type);
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1366
MethodHandle mh1 = mh0.bindTo(receiver);
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  1367
mh1 = mh1.withVarargs(mh0.isVarargsCollector());
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1368
return mh1;
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1369
         * }</pre></blockquote>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1370
         * 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
  1371
         * 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
  1372
         * to the lookup class.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1373
         * (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
  1374
         * @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
  1375
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1376
         * @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
  1377
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1378
         * @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
  1379
         * @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
  1380
         *                                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
  1381
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1382
         * @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
  1383
         *                              <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
  1384
         * @throws NullPointerException if any argument is null
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1385
         * @see MethodHandle#bindTo
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1386
         * @see #findVirtual
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1387
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1388
        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
  1389
            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
  1390
            MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1391
            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
  1392
            return mh.bindArgumentL(0, receiver).setVarargs(method);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1393
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1394
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1395
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1396
         * 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
  1397
         * 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
  1398
         * 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
  1399
         * 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
  1400
         * 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
  1401
         * 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
  1402
         * 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
  1403
         * 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
  1404
         * 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
  1405
         * 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
  1406
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1407
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1408
         * {@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
  1409
         * 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
  1410
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1411
         * 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
  1412
         * 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
  1413
         * 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
  1414
         * @param m the reflected method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1415
         * @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
  1416
         * @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
  1417
         *                                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
  1418
         *                                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
  1419
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1420
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1421
        public MethodHandle unreflect(Method m) throws IllegalAccessException {
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1422
            if (m.getDeclaringClass() == MethodHandle.class) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1423
                MethodHandle mh = unreflectForMH(m);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1424
                if (mh != null)  return mh;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1425
            }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1426
            if (m.getDeclaringClass() == VarHandle.class) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1427
                MethodHandle mh = unreflectForVH(m);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1428
                if (mh != null)  return mh;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1429
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1430
            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
  1431
            byte refKind = method.getReferenceKind();
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1432
            if (refKind == REF_invokeSpecial)
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1433
                refKind = REF_invokeVirtual;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1434
            assert(method.isMethod());
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1435
            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
  1436
            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
  1437
        }
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1438
        private MethodHandle unreflectForMH(Method m) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1439
            // these names require special lookups because they throw UnsupportedOperationException
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1440
            if (MemberName.isMethodHandleInvokeName(m.getName()))
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1441
                return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1442
            return null;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1443
        }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1444
        private MethodHandle unreflectForVH(Method m) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1445
            // these names require special lookups because they throw UnsupportedOperationException
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1446
            if (MemberName.isVarHandleMethodInvokeName(m.getName()))
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1447
                return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1448
            return null;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1449
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1450
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1451
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1452
         * Produces a method handle for a reflected method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1453
         * 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
  1454
         * <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
  1455
         * instruction from within the explicitly specified {@code specialCaller}.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1456
         * 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
  1457
         * with a suitably restricted receiver type prepended.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1458
         * (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
  1459
         * 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
  1460
         * 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
  1461
         * 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
  1462
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1463
         * Before method resolution,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1464
         * 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
  1465
         * 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
  1466
         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1467
         * privileges, the access fails.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1468
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1469
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1470
         * {@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
  1471
         * 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
  1472
         * @param m the reflected method
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1473
         * @param specialCaller the class nominally calling the method
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1474
         * @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
  1475
         * @throws IllegalAccessException if access checking fails,
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1476
         *                                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
  1477
         *                                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
  1478
         *                                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
  1479
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1480
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1481
        public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1482
            checkSpecialCaller(specialCaller, null);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1483
            Lookup specialLookup = this.in(specialCaller);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1484
            MemberName method = new MemberName(m, true);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1485
            assert(method.isMethod());
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1486
            // 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
  1487
            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
  1488
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1489
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1490
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1491
         * Produces a method handle for a reflected constructor.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1492
         * 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
  1493
         * 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
  1494
         * The method handle will perform a {@code newInstance} operation,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1495
         * 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
  1496
         * arguments passed to the method handle.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1497
         * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1498
         * 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
  1499
         * 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
  1500
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1501
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1502
         * {@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
  1503
         * 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
  1504
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1505
         * 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
  1506
         * be initialized, if it has not already been initialized.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1507
         * @param c the reflected constructor
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1508
         * @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
  1509
         * @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
  1510
         *                                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
  1511
         *                                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
  1512
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1513
         */
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1514
        public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1515
            MemberName ctor = new MemberName(c);
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1516
            assert(ctor.isConstructor());
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1517
            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
  1518
            return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1519
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1520
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1521
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1522
         * 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
  1523
         * 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
  1524
         * value type.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1525
         * 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
  1526
         * Otherwise, its single argument will be the instance containing
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1527
         * the field.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  1528
         * 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
  1529
         * 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
  1530
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1531
         * 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
  1532
         * 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
  1533
         * 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
  1534
         * @param f the reflected field
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1535
         * @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
  1536
         * @throws IllegalAccessException if access checking fails
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1537
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1538
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1539
        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
  1540
            return unreflectField(f, false);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1541
        }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1542
        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
  1543
            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
  1544
            assert(isSetter
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1545
                    ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1546
                    : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1547
            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
  1548
            return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1549
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1550
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1551
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1552
         * 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
  1553
         * 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
  1554
         * 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
  1555
         * 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
  1556
         * Otherwise, the two arguments will be the instance containing
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1557
         * 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
  1558
         * 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
  1559
         * 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
  1560
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1561
         * 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
  1562
         * 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
  1563
         * 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
  1564
         * @param f the reflected field
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1565
         * @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
  1566
         * @throws IllegalAccessException if access checking fails
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1567
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1568
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1569
        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
  1570
            return unreflectField(f, true);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1571
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1572
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1573
        /**
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1574
         * Produces a VarHandle that accesses fields of type {@code T} declared
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1575
         * by a class of type {@code R}, as described by the given reflected
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1576
         * field.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1577
         * If the field is non-static the VarHandle supports a shape of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1578
         * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1579
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1580
         * Access checking is performed immediately on behalf of the lookup
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1581
         * class, regardless of the value of the field's {@code accessible}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1582
         * flag.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1583
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1584
         * If the field is static, and if the returned VarHandle is operated
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1585
         * on, the field's declaring class will be initialized, if it has not
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1586
         * already been initialized.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1587
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1588
         * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1589
         * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1590
         * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1591
         * <li>if the field is declared {@code final}, then the write, atomic
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1592
         *     update, and numeric atomic update access modes are unsupported.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1593
         * <li>if the field type is anything other than {@code int},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1594
         *     {@code long} or a reference type, then atomic update access modes
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1595
         *     are unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1596
         *     support additional types for certain currently unsupported access
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1597
         *     modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1598
         * <li>if the field type is anything other than {@code int} or
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1599
         *     {@code long}, then numeric atomic update access modes are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1600
         *     unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1601
         *     support additional numeric types for certain currently
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1602
         *     unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1603
         * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1604
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1605
         * If the field is declared {@code volatile} then the returned VarHandle
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1606
         * will override access to the field (effectively ignore the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1607
         * {@code volatile} declaration) in accordance to it's specified
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1608
         * access modes.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1609
         * @param f the reflected field, with a field of type {@code T}, and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1610
         * a declaring class of type {@code R}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1611
         * @return a VarHandle giving access to non-static fields or a static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1612
         * field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1613
         * @throws IllegalAccessException if access checking fails
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1614
         * @throws NullPointerException if the argument is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1615
         * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1616
         */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1617
        public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1618
            MemberName getField = new MemberName(f, false);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1619
            MemberName putField = new MemberName(f, true);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1620
            return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1621
                                                      f.getDeclaringClass(), getField, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1622
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1623
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1624
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1625
         * 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
  1626
         * created by this lookup object or a similar one.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1627
         * Security and access checks are performed to ensure that this lookup object
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1628
         * is capable of reproducing the target method handle.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1629
         * This means that the cracking may fail if target is a direct method handle
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1630
         * 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
  1631
         * 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
  1632
         * and was created by a lookup object for a different class.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1633
         * @param target a direct method handle to crack into symbolic reference components
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1634
         * @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
  1635
         * @exception SecurityException if a security manager is present and it
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1636
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1637
         * @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
  1638
         * @exception NullPointerException if the target is {@code null}
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1639
         * @see MethodHandleInfo
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1640
         * @since 1.8
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1641
         */
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1642
        public MethodHandleInfo revealDirect(MethodHandle target) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1643
            MemberName member = target.internalMemberName();
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1644
            if (member == null || (!member.isResolved() &&
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1645
                                   !member.isMethodHandleInvoke() &&
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1646
                                   !member.isVarHandleMethodInvoke()))
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1647
                throw newIllegalArgumentException("not a direct method handle");
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1648
            Class<?> defc = member.getDeclaringClass();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1649
            byte refKind = member.getReferenceKind();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1650
            assert(MethodHandleNatives.refKindIsValid(refKind));
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1651
            if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1652
                // Devirtualized method invocation is usually formally virtual.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1653
                // To avoid creating extra MemberName objects for this common case,
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1654
                // we encode this extra degree of freedom using MH.isInvokeSpecial.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1655
                refKind = REF_invokeVirtual;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1656
            if (refKind == REF_invokeVirtual && defc.isInterface())
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1657
                // Symbolic reference is through interface but resolves to Object method (toString, etc.)
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1658
                refKind = REF_invokeInterface;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1659
            // Check SM permissions and member access before cracking.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1660
            try {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1661
                checkAccess(refKind, defc, member);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1662
                checkSecurityManager(defc, member);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1663
            } catch (IllegalAccessException ex) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1664
                throw new IllegalArgumentException(ex);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1665
            }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1666
            if (allowedModes != TRUSTED && member.isCallerSensitive()) {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1667
                Class<?> callerClass = target.internalCallerClass();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1668
                if (!hasPrivateAccess() || callerClass != lookupClass())
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1669
                    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
  1670
            }
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1671
            // Produce the handle to the results.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1672
            return new InfoFromMemberName(this, member, refKind);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1673
        }
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1674
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1675
        /// Helper methods, all package-private.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1676
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1677
        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
  1678
            checkSymbolicClass(refc);  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1679
            Objects.requireNonNull(name);
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1680
            Objects.requireNonNull(type);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1681
            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
  1682
                                            NoSuchFieldException.class);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1683
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1684
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1685
        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
  1686
            checkSymbolicClass(refc);  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1687
            Objects.requireNonNull(name);
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1688
            Objects.requireNonNull(type);
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1689
            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
  1690
            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
  1691
                                            NoSuchMethodException.class);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1692
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1693
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1694
        MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1695
            checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1696
            Objects.requireNonNull(member.getName());
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1697
            Objects.requireNonNull(member.getType());
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1698
            return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1699
                                            ReflectiveOperationException.class);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1700
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  1701
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1702
        void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  1703
            Objects.requireNonNull(refc);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1704
            Class<?> caller = lookupClassOrNull();
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
  1705
            if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1706
                throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1707
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1708
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1709
        /** 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
  1710
        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
  1711
            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
  1712
                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
  1713
        }
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1714
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1715
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1716
        /**
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1717
         * Find my trustable caller class if m is a caller sensitive method.
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1718
         * 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
  1719
         * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1720
         */
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1721
        Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1722
            Class<?> callerClass = null;
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1723
            if (MethodHandleNatives.isCallerSensitive(m)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1724
                // 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
  1725
                if (hasPrivateAccess()) {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1726
                    callerClass = lookupClass;
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1727
                } else {
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1728
                    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
  1729
                }
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1730
            }
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1731
            return callerClass;
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1732
        }
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1733
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1734
        private boolean hasPrivateAccess() {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1735
            return (allowedModes & PRIVATE) != 0;
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1736
        }
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1737
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1738
        /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1739
         * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1740
         * Determines a trustable caller class to compare with refc, the symbolic reference class.
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1741
         * 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
  1742
         */
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1743
        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
  1744
            SecurityManager smgr = System.getSecurityManager();
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1745
            if (smgr == null)  return;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1746
            if (allowedModes == TRUSTED)  return;
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1747
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1748
            // Step 1:
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1749
            boolean fullPowerLookup = hasPrivateAccess();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1750
            if (!fullPowerLookup ||
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1751
                !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1752
                ReflectUtil.checkPackageAccess(refc);
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1753
            }
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1754
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1755
            if (m == null) {  // findClass or accessClass
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1756
                // Step 2b:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1757
                if (!fullPowerLookup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1758
                    smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1759
                }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1760
                return;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1761
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1762
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1763
            // Step 2a:
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1764
            if (m.isPublic()) return;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1765
            if (!fullPowerLookup) {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1766
                smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1767
            }
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  1768
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
  1769
            // Step 3:
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1770
            Class<?> defc = m.getDeclaringClass();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1771
            if (!fullPowerLookup && defc != refc) {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1772
                ReflectUtil.checkPackageAccess(defc);
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1773
            }
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1774
        }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1775
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1776
        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
  1777
            boolean wantStatic = (refKind == REF_invokeStatic);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1778
            String message;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1779
            if (m.isConstructor())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1780
                message = "expected a method, not a constructor";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1781
            else if (!m.isMethod())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1782
                message = "expected a method";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1783
            else if (wantStatic != m.isStatic())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1784
                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
  1785
            else
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1786
                { checkAccess(refKind, refc, m); return; }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1787
            throw m.makeAccessException(message, this);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1788
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1789
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1790
        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
  1791
            boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1792
            String message;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1793
            if (wantStatic != m.isStatic())
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1794
                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
  1795
            else
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1796
                { checkAccess(refKind, refc, m); return; }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1797
            throw m.makeAccessException(message, this);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1798
        }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1799
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1800
        /** 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
  1801
        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
  1802
            assert(m.referenceKindIsConsistentWith(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1803
                   MethodHandleNatives.refKindIsValid(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1804
                   (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1805
            int allowedModes = this.allowedModes;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1806
            if (allowedModes == TRUSTED)  return;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1807
            int mods = m.getModifiers();
20528
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1808
            if (Modifier.isProtected(mods) &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1809
                    refKind == REF_invokeVirtual &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1810
                    m.getDeclaringClass() == Object.class &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1811
                    m.getName().equals("clone") &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1812
                    refc.isArray()) {
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1813
                // The JVM does this hack also.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1814
                // (See ClassVerifier::verify_invoke_instructions
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1815
                // and LinkResolver::check_method_accessability.)
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1816
                // 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
  1817
                // there is no separate method for int[].clone.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1818
                // All arrays simply inherit Object.clone.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1819
                // But for access checking logic, we make Object.clone
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1820
                // (normally protected) appear to be public.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1821
                // Later on, when the DirectMethodHandle is created,
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1822
                // its leading argument will be restricted to the
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1823
                // requested array type.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1824
                // N.B. The return type is not adjusted, because
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1825
                // that is *not* the bytecode behavior.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1826
                mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  1827
            }
25537
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1828
            if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1829
                // cannot "new" a protected ctor in a different package
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1830
                mods ^= Modifier.PROTECTED;
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  1831
            }
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1832
            if (Modifier.isFinal(mods) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1833
                    MethodHandleNatives.refKindIsSetter(refKind))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1834
                throw m.makeAccessException("unexpected set of a final field", this);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1835
            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
  1836
            if ((requestedModes & allowedModes) != 0) {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1837
                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
  1838
                                                    mods, lookupClass(), allowedModes))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1839
                    return;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1840
            } else {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1841
                // 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
  1842
                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
  1843
                        && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1844
                    return;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1845
            }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1846
            throw m.makeAccessException(accessFailedMessage(refc, m), this);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1847
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1848
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1849
        String accessFailedMessage(Class<?> refc, MemberName m) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1850
            Class<?> defc = m.getDeclaringClass();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1851
            int mods = m.getModifiers();
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1852
            // check the class first:
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1853
            boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1854
                               (defc == refc ||
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1855
                                Modifier.isPublic(refc.getModifiers())));
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1856
            if (!classOK && (allowedModes & PACKAGE) != 0) {
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
  1857
                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
  1858
                           (defc == refc ||
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
  1859
                            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
  1860
            }
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1861
            if (!classOK)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1862
                return "class is not public";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1863
            if (Modifier.isPublic(mods))
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1864
                return "access to public member failed";  // (how?, module not readable?)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1865
            if (Modifier.isPrivate(mods))
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1866
                return "member is private";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1867
            if (Modifier.isProtected(mods))
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1868
                return "member is protected";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1869
            return "member is private to package";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1870
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1871
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1872
        private static final boolean ALLOW_NESTMATE_ACCESS = false;
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1873
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1874
        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
  1875
            int allowedModes = this.allowedModes;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1876
            if (allowedModes == TRUSTED)  return;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1877
            if (!hasPrivateAccess()
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1878
                || (specialCaller != lookupClass()
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1879
                       // ensure non-abstract methods in superinterfaces can be special-invoked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1880
                    && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1881
                    && !(ALLOW_NESTMATE_ACCESS &&
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1882
                         VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1883
                throw new MemberName(specialCaller).
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1884
                    makeAccessException("no private access for invokespecial", this);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1885
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1886
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1887
        private boolean restrictProtectedReceiver(MemberName method) {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1888
            // 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
  1889
            // 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
  1890
            if (!method.isProtected() || method.isStatic()
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1891
                || allowedModes == TRUSTED
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1892
                || 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
  1893
                || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1894
                || (ALLOW_NESTMATE_ACCESS &&
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  1895
                    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
  1896
                return false;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1897
            return true;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1898
        }
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1899
        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
  1900
            assert(!method.isStatic());
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1901
            // 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
  1902
            if (!method.getDeclaringClass().isAssignableFrom(caller)) {
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  1903
                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
  1904
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1905
            MethodType rawType = mh.type();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1906
            if (rawType.parameterType(0) == caller)  return mh;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1907
            MethodType narrowType = rawType.changeParameterType(0, caller);
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1908
            assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1909
            assert(mh.viewAsTypeChecks(narrowType, true));
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1910
            return mh.copyWith(narrowType, mh.form);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1911
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1912
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1913
        /** Check access and get the requested method. */
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1914
        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
  1915
            final boolean doRestrict    = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1916
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1917
            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
  1918
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1919
        /** 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
  1920
        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
  1921
            final boolean doRestrict    = false;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1922
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1923
            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
  1924
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1925
        /** 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
  1926
        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
  1927
            final boolean doRestrict    = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1928
            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
  1929
            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
  1930
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1931
        /** 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
  1932
        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
  1933
                                                   boolean checkSecurity,
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1934
                                                   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
  1935
            checkMethod(refKind, refc, method);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1936
            // 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
  1937
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1938
                checkSecurityManager(refc, method);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1939
            assert(!method.isMethodHandleInvoke());
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1940
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1941
            if (refKind == REF_invokeSpecial &&
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1942
                refc != lookupClass() &&
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1943
                !refc.isInterface() &&
24860
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1944
                refc != lookupClass().getSuperclass() &&
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1945
                refc.isAssignableFrom(lookupClass())) {
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1946
                assert(!method.getName().equals("<init>"));  // not this code path
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1947
                // Per JVMS 6.5, desc. of invokespecial instruction:
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1948
                // If the method is in a superclass of the LC,
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1949
                // 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
  1950
                // repeat the search (symbolic lookup) from LC.super
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1951
                // and continue with the direct superclass of that class,
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1952
                // 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
  1953
                // FIXME: MemberName.resolve should handle this instead.
24860
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1954
                Class<?> refcAsSuper = lookupClass();
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1955
                MemberName m2;
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1956
                do {
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1957
                    refcAsSuper = refcAsSuper.getSuperclass();
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1958
                    m2 = new MemberName(refcAsSuper,
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1959
                                        method.getName(),
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1960
                                        method.getMethodType(),
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1961
                                        REF_invokeSpecial);
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1962
                    m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1963
                } while (m2 == null &&         // no method is found yet
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  1964
                         refc != refcAsSuper); // search up to refc
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1965
                if (m2 == null)  throw new InternalError(method.toString());
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1966
                method = m2;
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1967
                refc = refcAsSuper;
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1968
                // redo basic checks
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1969
                checkMethod(refKind, refc, method);
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1970
            }
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  1971
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1972
            DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1973
            MethodHandle mh = dmh;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1974
            // 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
  1975
            if (doRestrict &&
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1976
                   (refKind == REF_invokeSpecial ||
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1977
                       (MethodHandleNatives.refKindHasReceiver(refKind) &&
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1978
                           restrictProtectedReceiver(method)))) {
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1979
                mh = restrictReceiver(method, dmh, lookupClass());
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1980
            }
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1981
            mh = maybeBindCaller(method, mh, callerClass);
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  1982
            mh = mh.setVarargs(method);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1983
            return mh;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1984
        }
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1985
        private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1986
                                             Class<?> callerClass)
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1987
                                             throws IllegalAccessException {
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1988
            if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1989
                return mh;
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1990
            Class<?> hostClass = lookupClass;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1991
            if (!hasPrivateAccess())  // caller must have private access
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  1992
                hostClass = callerClass;  // callerClass came from a security manager style stack walk
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1993
            MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1994
            // Note: caller will apply varargs after this step happens.
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1995
            return cbmh;
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  1996
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1997
        /** 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
  1998
        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
  1999
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2000
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2001
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2002
        /** 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
  2003
        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
  2004
            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
  2005
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2006
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2007
        /** 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
  2008
        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
  2009
                                                  boolean checkSecurity) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2010
            checkField(refKind, refc, field);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2011
            // 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
  2012
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2013
                checkSecurityManager(refc, field);
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2014
            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
  2015
            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2016
                                    restrictProtectedReceiver(field));
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2017
            if (doRestrict)
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2018
                return restrictReceiver(field, dmh, lookupClass());
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2019
            return dmh;
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2020
        }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2021
        private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2022
                                            Class<?> refc, MemberName getField, MemberName putField)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2023
                throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2024
            final boolean checkSecurity = true;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2025
            return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2026
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2027
        private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2028
                                                             Class<?> refc, MemberName getField, MemberName putField)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2029
                throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2030
            final boolean checkSecurity = false;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2031
            return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2032
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2033
        private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2034
                                                  Class<?> refc, MemberName getField, MemberName putField,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2035
                                                  boolean checkSecurity) throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2036
            assert getField.isStatic() == putField.isStatic();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2037
            assert getField.isGetter() && putField.isSetter();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2038
            assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2039
            assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2040
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2041
            checkField(getRefKind, refc, getField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2042
            if (checkSecurity)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2043
                checkSecurityManager(refc, getField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2044
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2045
            if (!putField.isFinal()) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2046
                // A VarHandle does not support updates to final fields, any
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2047
                // such VarHandle to a final field will be read-only and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2048
                // therefore the following write-based accessibility checks are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2049
                // only required for non-final fields
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2050
                checkField(putRefKind, refc, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2051
                if (checkSecurity)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2052
                    checkSecurityManager(refc, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2053
            }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2054
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2055
            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2056
                                  restrictProtectedReceiver(getField));
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2057
            if (doRestrict) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2058
                assert !getField.isStatic();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2059
                // receiver type of VarHandle is too wide; narrow to caller
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2060
                if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2061
                    throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2062
                }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2063
                refc = lookupClass();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2064
            }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2065
            return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2066
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2067
        /** 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
  2068
        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
  2069
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2070
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2071
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2072
        /** 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
  2073
        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
  2074
            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
  2075
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2076
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2077
        /** 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
  2078
        private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2079
                                                  boolean checkSecurity) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2080
            assert(ctor.isConstructor());
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2081
            checkAccess(REF_newInvokeSpecial, refc, ctor);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2082
            // 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
  2083
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2084
                checkSecurityManager(refc, ctor);
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2085
            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
  2086
            return DirectMethodHandle.make(ctor).setVarargs(ctor);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2087
        }
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2088
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2089
        /** 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
  2090
         */
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2091
        /*non-public*/
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2092
        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
  2093
            if (!(type instanceof Class || type instanceof MethodType))
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2094
                throw new InternalError("unresolved MemberName");
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2095
            MemberName member = new MemberName(refKind, defc, name, type);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2096
            MethodHandle mh = LOOKASIDE_TABLE.get(member);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2097
            if (mh != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2098
                checkSymbolicClass(defc);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2099
                return mh;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2100
            }
21362
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2101
            // Treat MethodHandle.invoke and invokeExact specially.
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2102
            if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2103
                mh = findVirtualForMH(member.getName(), member.getMethodType());
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2104
                if (mh != null) {
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2105
                    return mh;
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2106
                }
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2107
            }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2108
            MemberName resolved = resolveOrFail(refKind, member);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2109
            mh = getDirectMethodForConstant(refKind, defc, resolved);
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2110
            if (mh instanceof DirectMethodHandle
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2111
                    && canBeCached(refKind, defc, resolved)) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2112
                MemberName key = mh.internalMemberName();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2113
                if (key != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2114
                    key = key.asNormalOriginal();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2115
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2116
                if (member.equals(key)) {  // better safe than sorry
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2117
                    LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2118
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2119
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2120
            return mh;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2121
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2122
        private
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2123
        boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2124
            if (refKind == REF_invokeSpecial) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2125
                return false;
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2126
            }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2127
            if (!Modifier.isPublic(defc.getModifiers()) ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2128
                    !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2129
                    !member.isPublic() ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2130
                    member.isCallerSensitive()) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2131
                return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2132
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2133
            ClassLoader loader = defc.getClassLoader();
34882
ce2a8ec851c1 8145544: Move sun.misc.VM to jdk.internal.misc
chegar
parents: 34720
diff changeset
  2134
            if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2135
                ClassLoader sysl = ClassLoader.getSystemClassLoader();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2136
                boolean found = false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2137
                while (sysl != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2138
                    if (loader == sysl) { found = true; break; }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2139
                    sysl = sysl.getParent();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2140
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2141
                if (!found) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2142
                    return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2143
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2144
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2145
            try {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2146
                MemberName resolved2 = publicLookup().resolveOrFail(refKind,
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2147
                    new MemberName(refKind, defc, member.getName(), member.getType()));
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2148
                checkSecurityManager(defc, resolved2);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2149
            } catch (ReflectiveOperationException | SecurityException ex) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2150
                return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2151
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2152
            return true;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2153
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2154
        private
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2155
        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
  2156
                throws ReflectiveOperationException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2157
            if (MethodHandleNatives.refKindIsField(refKind)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2158
                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
  2159
            } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2160
                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
  2161
            } else if (refKind == REF_newInvokeSpecial) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2162
                return getDirectConstructorNoSecurityManager(defc, member);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2163
            }
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2164
            // oops
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2165
            throw newIllegalArgumentException("bad MethodHandle constant #"+member);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2166
        }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2167
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2168
        static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2169
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2170
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2171
    /**
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2172
     * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2173
     * in an <em>unnamed module</em>.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2174
     *
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2175
     * @see Lookup#publicLookup
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2176
     */
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2177
    private static class LookupHelper {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2178
        private static final String UNNAMED = "Unnamed";
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2179
        private static final String OBJECT  = "java/lang/Object";
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2180
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2181
        private static Class<?> createClass() {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2182
            try {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2183
                ClassWriter cw = new ClassWriter(0);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2184
                cw.visit(Opcodes.V1_8,
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2185
                         Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2186
                         UNNAMED,
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2187
                         null,
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2188
                         OBJECT,
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2189
                         null);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2190
                cw.visitSource(UNNAMED, null);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2191
                cw.visitEnd();
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2192
                byte[] bytes = cw.toByteArray();
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2193
                ClassLoader loader = new ClassLoader(null) {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2194
                    @Override
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2195
                    protected Class<?> findClass(String cn) throws ClassNotFoundException {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2196
                        if (cn.equals(UNNAMED))
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2197
                            return super.defineClass(UNNAMED, bytes, 0, bytes.length);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2198
                        throw new ClassNotFoundException(cn);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2199
                    }
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2200
                };
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2201
                return loader.loadClass(UNNAMED);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2202
            } catch (Exception e) {
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2203
                throw new InternalError(e);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2204
            }
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2205
        }
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2206
38861
e567cc17866d 8158851: MH.publicLookup() init circularity, triggered by custom SecurityManager with String concat and -limitmods java.base
shade
parents: 38785
diff changeset
  2207
        private static final Class<?> PUBLIC_LOOKUP_CLASS = createClass();
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2208
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2209
        /**
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2210
         * Lookup that is trusted minimally. It can only be used to create
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2211
         * method handles to publicly accessible members in exported packages.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2212
         *
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2213
         * @see MethodHandles#publicLookup
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2214
         */
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2215
        static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC);
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2216
    }
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2217
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2218
    /**
37674
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2219
     * Produces a method handle constructing arrays of a desired type.
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2220
     * The return type of the method handle will be the array type.
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2221
     * The type of its sole argument will be {@code int}, which specifies the size of the array.
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2222
     * @param arrayClass an array type
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2223
     * @return a method handle which can create arrays of the given type
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2224
     * @throws NullPointerException if the argument is {@code null}
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2225
     * @throws IllegalArgumentException if {@code arrayClass} is not an array type
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2226
     * @see java.lang.reflect.Array#newInstance(Class, int)
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2227
     * @since 9
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2228
     */
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2229
    public static
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2230
    MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2231
        if (!arrayClass.isArray()) {
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2232
            throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2233
        }
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2234
        MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2235
                bindTo(arrayClass.getComponentType());
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2236
        return ani.asType(ani.type().changeReturnType(arrayClass));
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2237
    }
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2238
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2239
    /**
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2240
     * Produces a method handle returning the length of an array.
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2241
     * The type of the method handle will have {@code int} as return type,
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2242
     * and its sole argument will be the array type.
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2243
     * @param arrayClass an array type
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2244
     * @return a method handle which can retrieve the length of an array of the given array type
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2245
     * @throws NullPointerException if the argument is {@code null}
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2246
     * @throws IllegalArgumentException if arrayClass is not an array type
38472
6d7aed566bf3 8157590: MethodHandles.arrayLength() lacks @since tag, implementation throws wrong exception
mhaupt
parents: 38376
diff changeset
  2247
     * @since 9
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2248
     */
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2249
    public static
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2250
    MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2251
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2252
    }
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2253
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2254
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2255
     * 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
  2256
     * 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
  2257
     * 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
  2258
     * and the second will be {@code int}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2259
     * @param arrayClass an array type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2260
     * @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
  2261
     * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2262
     * @throws  IllegalArgumentException if arrayClass is not an array type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2263
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2264
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2265
    MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2266
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2267
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2268
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2269
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2270
     * 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
  2271
     * 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
  2272
     * 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
  2273
     * 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
  2274
     * @param arrayClass the class of an array
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2275
     * @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
  2276
     * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2277
     * @throws IllegalArgumentException if arrayClass is not an array type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2278
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2279
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2280
    MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2281
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2282
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2283
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2284
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2285
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2286
     * Produces a VarHandle giving access to elements of an array type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2287
     * {@code T[]}, supporting shape {@code (T[], int : T)}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2288
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2289
     * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2290
     * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2291
     * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2292
     * <li>if the component type is anything other than {@code int},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2293
     *     {@code long} or a reference type, then atomic update access modes
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2294
     *     are unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2295
     *     support additional types for certain currently unsupported access
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2296
     *     modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2297
     * <li>if the component type is anything other than {@code int} or
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2298
     *     {@code long}, then numeric atomic update access modes are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2299
     *     unsupported.  (Future major platform releases of the JDK may
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2300
     *     support additional numeric types for certain currently
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2301
     *     unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2302
     * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2303
     * @param arrayClass the class of an array, of type {@code T[]}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2304
     * @return a VarHandle giving access to elements of an array
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2305
     * @throws NullPointerException if the arrayClass is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2306
     * @throws IllegalArgumentException if arrayClass is not an array type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2307
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2308
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2309
    public static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2310
    VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2311
        return VarHandles.makeArrayElementHandle(arrayClass);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2312
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2313
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2314
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2315
     * Produces a VarHandle giving access to elements of a {@code byte[]} array
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2316
     * viewed as if it were a different primitive array type, such as
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2317
     * {@code int[]} or {@code long[]}.  The shape of the resulting VarHandle is
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2318
     * {@code (byte[], int : T)}, where the {@code int} coordinate type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2319
     * corresponds to an argument that is an index in a {@code byte[]} array,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2320
     * and {@code T} is the component type of the given view array class.  The
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2321
     * returned VarHandle accesses bytes at an index in a {@code byte[]} array,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2322
     * composing bytes to or from a value of {@code T} according to the given
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2323
     * endianness.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2324
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2325
     * The supported component types (variables types) are {@code short},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2326
     * {@code char}, {@code int}, {@code long}, {@code float} and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2327
     * {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2328
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2329
     * Access of bytes at a given index will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2330
     * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2331
     * or greater than the {@code byte[]} array length minus the size (in bytes)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2332
     * of {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2333
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2334
     * Access of bytes at an index may be aligned or misaligned for {@code T},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2335
     * with respect to the underlying memory address, {@code A} say, associated
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2336
     * with the array and index.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2337
     * If access is misaligned then access for anything other than the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2338
     * {@code get} and {@code set} access modes will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2339
     * {@code IllegalStateException}.  In such cases atomic access is only
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2340
     * guaranteed with respect to the largest power of two that divides the GCD
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2341
     * of {@code A} and the size (in bytes) of {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2342
     * If access is aligned then following access modes are supported and are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2343
     * guaranteed to support atomic access:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2344
     * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2345
     * <li>read write access modes for all {@code T};
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2346
     * <li>atomic update access modes for {@code int}, {@code long},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2347
     *     {@code float} or {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2348
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2349
     *     types for certain currently unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2350
     * <li>numeric atomic update access modes for {@code int} and {@code long}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2351
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2352
     *     numeric types for certain currently unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2353
     * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2354
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2355
     * Misaligned access, and therefore atomicity guarantees, may be determined
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2356
     * for {@code byte[]} arrays without operating on a specific array.  Given
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2357
     * an {@code index}, {@code T} and it's corresponding boxed type,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2358
     * {@code T_BOX}, misalignment may be determined as follows:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2359
     * <pre>{@code
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2360
     * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2361
     * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2362
     *     alignmentOffset(0, sizeOfT);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2363
     * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2364
     * boolean isMisaligned = misalignedAtIndex != 0;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2365
     * }</pre>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2366
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2367
     * @implNote
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2368
     * The variable types {@code float} and {@code double} are supported as if
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2369
     * by transformation to and access with the variable types {@code int} and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2370
     * {@code long} respectively.  For example, the transformation of a
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2371
     * {@code double} value to a long value is performed as if using
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2372
     * {@link Double#doubleToRawLongBits(double)}, and the reverse
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2373
     * transformation is performed as if using
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2374
     * {@link Double#longBitsToDouble(long)}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2375
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2376
     * @param viewArrayClass the view array class, with a component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2377
     * type {@code T}
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2378
     * @param byteOrder the endianness of the view array elements, as
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2379
     * stored in the underlying {@code byte} array
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2380
     * @return a VarHandle giving access to elements of a {@code byte[]} array
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2381
     * viewed as if elements corresponding to the components type of the view
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2382
     * array class
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2383
     * @throws NullPointerException if viewArrayClass or byteOrder is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2384
     * @throws IllegalArgumentException if viewArrayClass is not an array type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2385
     * @throws UnsupportedOperationException if the component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2386
     * viewArrayClass is not supported as a variable type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2387
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2388
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2389
    public static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2390
    VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2391
                                     ByteOrder byteOrder) throws IllegalArgumentException {
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2392
        Objects.requireNonNull(byteOrder);
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2393
        return VarHandles.byteArrayViewHandle(viewArrayClass,
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2394
                                              byteOrder == ByteOrder.BIG_ENDIAN);
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2395
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2396
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2397
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2398
     * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2399
     * viewed as if it were an array of elements of a different primitive
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2400
     * component type to that of {@code byte}, such as {@code int[]} or
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2401
     * {@code long[]}.  The shape of the resulting VarHandle is
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2402
     * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2403
     * corresponds to an argument that is an index in a {@code ByteBuffer}, and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2404
     * {@code T} is the component type of the given view array class.  The
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2405
     * returned VarHandle accesses bytes at an index in a {@code ByteBuffer},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2406
     * composing bytes to or from a value of {@code T} according to the given
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2407
     * endianness.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2408
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2409
     * The supported component types (variables types) are {@code short},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2410
     * {@code char}, {@code int}, {@code long}, {@code float} and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2411
     * {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2412
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2413
     * Access will result in a {@code ReadOnlyBufferException} for anything
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2414
     * other than the read access modes if the {@code ByteBuffer} is read-only.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2415
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2416
     * Access of bytes at a given index will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2417
     * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2418
     * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2419
     * {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2420
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2421
     * Access of bytes at an index may be aligned or misaligned for {@code T},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2422
     * with respect to the underlying memory address, {@code A} say, associated
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2423
     * with the {@code ByteBuffer} and index.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2424
     * If access is misaligned then access for anything other than the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2425
     * {@code get} and {@code set} access modes will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2426
     * {@code IllegalStateException}.  In such cases atomic access is only
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2427
     * guaranteed with respect to the largest power of two that divides the GCD
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2428
     * of {@code A} and the size (in bytes) of {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2429
     * If access is aligned then following access modes are supported and are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2430
     * guaranteed to support atomic access:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2431
     * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2432
     * <li>read write access modes for all {@code T};
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2433
     * <li>atomic update access modes for {@code int}, {@code long},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2434
     *     {@code float} or {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2435
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2436
     *     types for certain currently unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2437
     * <li>numeric atomic update access modes for {@code int} and {@code long}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2438
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2439
     *     numeric types for certain currently unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2440
     * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2441
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2442
     * Misaligned access, and therefore atomicity guarantees, may be determined
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2443
     * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2444
     * {@code index}, {@code T} and it's corresponding boxed type,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2445
     * {@code T_BOX}, as follows:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2446
     * <pre>{@code
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2447
     * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2448
     * ByteBuffer bb = ...
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2449
     * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2450
     * boolean isMisaligned = misalignedAtIndex != 0;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2451
     * }</pre>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2452
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2453
     * @implNote
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2454
     * The variable types {@code float} and {@code double} are supported as if
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2455
     * by transformation to and access with the variable types {@code int} and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2456
     * {@code long} respectively.  For example, the transformation of a
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2457
     * {@code double} value to a long value is performed as if using
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2458
     * {@link Double#doubleToRawLongBits(double)}, and the reverse
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2459
     * transformation is performed as if using
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2460
     * {@link Double#longBitsToDouble(long)}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2461
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2462
     * @param viewArrayClass the view array class, with a component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2463
     * type {@code T}
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2464
     * @param byteOrder the endianness of the view array elements, as
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2465
     * stored in the underlying {@code ByteBuffer} (Note this overrides the
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2466
     * endianness of a {@code ByteBuffer})
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2467
     * @return a VarHandle giving access to elements of a {@code ByteBuffer}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2468
     * viewed as if elements corresponding to the components type of the view
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2469
     * array class
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2470
     * @throws NullPointerException if viewArrayClass or byteOrder is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2471
     * @throws IllegalArgumentException if viewArrayClass is not an array type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2472
     * @throws UnsupportedOperationException if the component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2473
     * viewArrayClass is not supported as a variable type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2474
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2475
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2476
    public static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2477
    VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2478
                                      ByteOrder byteOrder) throws IllegalArgumentException {
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2479
        Objects.requireNonNull(byteOrder);
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2480
        return VarHandles.makeByteBufferViewHandle(viewArrayClass,
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2481
                                                   byteOrder == ByteOrder.BIG_ENDIAN);
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2482
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2483
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2484
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2485
    /// method handle invocation (reflective style)
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2486
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2487
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2488
     * 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
  2489
     * 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
  2490
     * a single trailing {@code Object[]} array.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2491
     * 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
  2492
     * arguments:
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2493
     * <ul>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2494
     * <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
  2495
     * <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
  2496
     * <li>an {@code Object[]} array containing trailing arguments
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2497
     * </ul>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2498
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2499
     * 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
  2500
     * the indicated {@code type}.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2501
     * 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
  2502
     * 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
  2503
     * 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
  2504
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2505
     * 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
  2506
     * 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
  2507
     * 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
  2508
     * the final parameter.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2509
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2510
     * 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
  2511
     * 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
  2512
     * 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
  2513
     * 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
  2514
     * an {@link IllegalArgumentException} instead of invoking the target.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2515
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2516
     * 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
  2517
     * <blockquote><pre>{@code
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2518
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
  2519
int spreadArgCount = type.parameterCount() - leadingArgCount;
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  2520
invoker = invoker.asSpreader(Object[].class, spreadArgCount);
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  2521
return invoker;
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2522
     * }</pre></blockquote>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2523
     * This method throws no reflective or security exceptions.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2524
     * @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
  2525
     * @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
  2526
     * @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
  2527
     * @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
  2528
     * @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
  2529
     *                  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
  2530
     *                  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
  2531
     *          <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
  2532
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2533
    public static
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2534
    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
  2535
        if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
  2536
            throw newIllegalArgumentException("bad argument count", leadingArgCount);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2537
        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
  2538
        return type.invokers().spreadInvoker(leadingArgCount);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2539
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2540
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2541
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2542
     * 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
  2543
     * 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
  2544
     * 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
  2545
     * 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
  2546
     * an additional leading argument of type {@code MethodHandle}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2547
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2548
     * 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
  2549
     * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2550
     *
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2551
     * <p style="font-size:smaller;">
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2552
     * <em>Discussion:</em>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2553
     * 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
  2554
     * of unknown types.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2555
     * 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
  2556
     * handle {@code M}, extract its type {@code T},
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2557
     * 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
  2558
     * 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
  2559
     * (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
  2560
     * is unknown.)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2561
     * If spreading, collecting, or other argument transformations are required,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2562
     * 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
  2563
     * 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
  2564
     * <p style="font-size:smaller;">
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2565
     * <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
  2566
     * 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
  2567
     * 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
  2568
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2569
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2570
     * This method throws no reflective or security exceptions.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2571
     * @param type the desired target type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2572
     * @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
  2573
     * @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
  2574
     *          <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
  2575
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2576
    public static
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2577
    MethodHandle exactInvoker(MethodType type) {
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2578
        return type.invokers().exactInvoker();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2579
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2580
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2581
    /**
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2582
     * 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
  2583
     * 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
  2584
     * The resulting invoker will have a type which is
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2585
     * 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
  2586
     * an additional leading argument of type {@code MethodHandle}.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2587
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2588
     * 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
  2589
     * the invoker will apply reference casts as
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2590
     * 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
  2591
     * 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
  2592
     * 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
  2593
     * 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
  2594
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2595
     * 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
  2596
     * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2597
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2598
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2599
     * 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
  2600
     * 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
  2601
     * 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
  2602
     * of the same arity as the general type.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2603
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2604
     * <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
  2605
     * 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
  2606
     * 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
  2607
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2608
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2609
     * This method throws no reflective or security exceptions.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2610
     * @param type the desired target type
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2611
     * @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
  2612
     * @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
  2613
     *          <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
  2614
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2615
    public static
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2616
    MethodHandle invoker(MethodType type) {
26468
2d57604f9299 8050053: Improve caching of different invokers
vlivanov
parents: 26467
diff changeset
  2617
        return type.invokers().genericInvoker();
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2618
    }
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2619
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2620
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2621
     * Produces a special <em>invoker method handle</em> which can be used to
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2622
     * invoke a signature-polymorphic access mode method on any VarHandle whose
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2623
     * associated access mode type is compatible with the given type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2624
     * The resulting invoker will have a type which is exactly equal to the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2625
     * desired given type, except that it will accept an additional leading
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2626
     * argument of type {@code VarHandle}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2627
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2628
     * @param accessMode the VarHandle access mode
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2629
     * @param type the desired target type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2630
     * @return a method handle suitable for invoking an access mode method of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2631
     *         any VarHandle whose access mode type is of the given type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2632
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2633
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2634
    static public
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2635
    MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2636
        return type.invokers().varHandleMethodExactInvoker(accessMode);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2637
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2638
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2639
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2640
     * Produces a special <em>invoker method handle</em> which can be used to
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2641
     * invoke a signature-polymorphic access mode method on any VarHandle whose
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2642
     * associated access mode type is compatible with the given type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2643
     * The resulting invoker will have a type which is exactly equal to the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2644
     * desired given type, except that it will accept an additional leading
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2645
     * argument of type {@code VarHandle}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2646
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2647
     * Before invoking its target, if the access mode type differs from the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2648
     * desired given type, the invoker will apply reference casts as necessary
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2649
     * and box, unbox, or widen primitive values, as if by
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2650
     * {@link MethodHandle#asType asType}.  Similarly, the return value will be
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2651
     * converted as necessary.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2652
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2653
     * This method is equivalent to the following code (though it may be more
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2654
     * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2655
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2656
     * @param accessMode the VarHandle access mode
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2657
     * @param type the desired target type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2658
     * @return a method handle suitable for invoking an access mode method of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2659
     *         any VarHandle whose access mode type is convertible to the given
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2660
     *         type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2661
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2662
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2663
    static public
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2664
    MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2665
        return type.invokers().varHandleMethodInvoker(accessMode);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2666
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2667
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2668
    static /*non-public*/
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2669
    MethodHandle basicInvoker(MethodType type) {
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
  2670
        return type.invokers().basicInvoker();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2671
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2672
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2673
     /// method handle modification (creation from other method handles)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2674
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2675
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2676
     * 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
  2677
     * 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
  2678
     * 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
  2679
     * 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
  2680
     * which is equal to the desired new type.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2681
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2682
     * 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
  2683
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2684
     * 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
  2685
     * 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
  2686
     * 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
  2687
     * 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
  2688
     * <ul>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2689
     * <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
  2690
     *     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
  2691
     *     (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
  2692
     * <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
  2693
     *     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
  2694
     *     (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
  2695
     * <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
  2696
     *     <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
  2697
     *     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
  2698
     * <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
  2699
     *     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
  2700
     *     (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
  2701
     *     widening and/or narrowing.)
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2702
     * <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
  2703
     *     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
  2704
     *     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
  2705
     *     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
  2706
     *     the low-order bit.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2707
     * <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
  2708
     *     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
  2709
     * </ul>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2710
     * @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
  2711
     * @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
  2712
     * @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
  2713
     *           any necessary argument conversions, and arranges for any
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2714
     *           necessary return value conversions
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2715
     * @throws NullPointerException if either argument is null
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2716
     * @throws WrongMethodTypeException if the conversion cannot be made
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2717
     * @see MethodHandle#asType
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2718
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2719
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2720
    MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2721
        explicitCastArgumentsChecks(target, newType);
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2722
        // use the asTypeCache when possible:
26478
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  2723
        MethodType oldType = target.type();
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  2724
        if (oldType == newType)  return target;
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  2725
        if (oldType.explicitCastEquivalentToAsType(newType)) {
27947
dba3bc0c087e 8066746: MHs.explicitCastArguments does incorrect type checks for VarargsCollector
vlivanov
parents: 27755
diff changeset
  2726
            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
  2727
        }
26474
655d08549e43 8050877: Improve code for pairwise argument conversions and value boxing/unboxing
vlivanov
parents: 26470
diff changeset
  2728
        return MethodHandleImpl.makePairwiseConvert(target, newType, false);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2729
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2730
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2731
    private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2732
        if (target.type().parameterCount() != newType.parameterCount()) {
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2733
            throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2734
        }
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2735
    }
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  2736
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2737
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2738
     * 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
  2739
     * 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
  2740
     * 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
  2741
     * which is equal to the desired new type.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2742
     * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2743
     * The given array controls the reordering.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2744
     * 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
  2745
     * {@code newType.parameterCount()}, and call {@code #O} the number
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2746
     * of outgoing parameters (the value {@code target.type().parameterCount()}).
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2747
     * 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
  2748
     * 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
  2749
     * 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
  2750
     * 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
  2751
     * argument, where {@code I} is {@code reorder[N]}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2752
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2753
     * No argument or return value conversions are applied.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2754
     * 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
  2755
     * 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
  2756
     * or parameters in the target method handle.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2757
     * 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
  2758
     * type of the original target.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2759
     * <p>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2760
     * The reordering array need not specify an actual permutation.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2761
     * 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
  2762
     * 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
  2763
     * 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
  2764
     * 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
  2765
     * incoming arguments which are not mentioned in the reordering array
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2766
     * may be of any type, as determined only by {@code newType}.
18156
edb590d448c5 8016217: More javadoc warnings
alanb
parents: 16906
diff changeset
  2767
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2768
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
  2769
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
  2770
...
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2771
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
  2772
MethodType intfn2 = methodType(int.class, int.class, int.class);
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  2773
MethodHandle sub = ... (int x, int y) -> (x-y) ...;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2774
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
  2775
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
  2776
MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2777
assert((int)rsub.invokeExact(1, 100) == 99);
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  2778
MethodHandle add = ... (int x, int y) -> (x+y) ...;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2779
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
  2780
MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2781
assert(twice.type().equals(intfn1));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2782
assert((int)twice.invokeExact(21) == 42);
18156
edb590d448c5 8016217: More javadoc warnings
alanb
parents: 16906
diff changeset
  2783
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2784
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2785
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  2786
     * 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
  2787
     * @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
  2788
     * @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
  2789
     * @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
  2790
     * @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
  2791
     *           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
  2792
     * @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
  2793
     * @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
  2794
     *                  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
  2795
     *                  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
  2796
     *                  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
  2797
     *                  {@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
  2798
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2799
    public static
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2800
    MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2801
        reorder = reorder.clone();  // get a private copy
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2802
        MethodType oldType = target.type();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2803
        permuteArgumentChecks(reorder, newType, oldType);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2804
        // first detect dropped arguments and handle them separately
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2805
        int[] originalReorder = reorder;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2806
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2807
        LambdaForm form = result.form;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2808
        int newArity = newType.parameterCount();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2809
        // Normalize the reordering into a real permutation,
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2810
        // by removing duplicates and adding dropped elements.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2811
        // This somewhat improves lambda form caching, as well
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2812
        // as simplifying the transform by breaking it up into steps.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2813
        for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2814
            if (ddIdx > 0) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2815
                // We found a duplicated entry at reorder[ddIdx].
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2816
                // Example:  (x,y,z)->asList(x,y,z)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2817
                // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2818
                // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2819
                // The starred element corresponds to the argument
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2820
                // deleted by the dupArgumentForm transform.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2821
                int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2822
                boolean killFirst = false;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2823
                for (int val; (val = reorder[--dstPos]) != dupVal; ) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2824
                    // Set killFirst if the dup is larger than an intervening position.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2825
                    // This will remove at least one inversion from the permutation.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2826
                    if (dupVal > val) killFirst = true;
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2827
                }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2828
                if (!killFirst) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2829
                    srcPos = dstPos;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2830
                    dstPos = ddIdx;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2831
                }
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2832
                form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2833
                assert (reorder[srcPos] == reorder[dstPos]);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2834
                oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2835
                // contract the reordering by removing the element at dstPos
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2836
                int tailPos = dstPos + 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2837
                System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2838
                reorder = Arrays.copyOf(reorder, reorder.length - 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2839
            } else {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2840
                int dropVal = ~ddIdx, insPos = 0;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2841
                while (insPos < reorder.length && reorder[insPos] < dropVal) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2842
                    // Find first element of reorder larger than dropVal.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2843
                    // This is where we will insert the dropVal.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2844
                    insPos += 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2845
                }
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2846
                Class<?> ptype = newType.parameterType(dropVal);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2847
                form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2848
                oldType = oldType.insertParameterTypes(insPos, ptype);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2849
                // expand the reordering by inserting an element at insPos
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2850
                int tailPos = insPos + 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2851
                reorder = Arrays.copyOf(reorder, reorder.length + 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2852
                System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2853
                reorder[insPos] = dropVal;
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2854
            }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2855
            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
  2856
        }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2857
        assert (reorder.length == newArity);  // a perfect permutation
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2858
        // 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
  2859
        form = form.editor().permuteArgumentsForm(1, reorder);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2860
        if (newType == result.type() && form == result.internalForm())
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2861
            return result;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  2862
        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
  2863
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2864
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2865
    /**
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2866
     * 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
  2867
     * 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
  2868
     * 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
  2869
     * Otherwise, return zero.
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2870
     * 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
  2871
     */
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2872
    private static int findFirstDupOrDrop(int[] reorder, int newArity) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2873
        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
  2874
        if (newArity < BIT_LIMIT) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2875
            long mask = 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2876
            for (int i = 0; i < reorder.length; i++) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2877
                int arg = reorder[i];
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2878
                if (arg >= newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2879
                    return reorder.length;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2880
                }
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2881
                long bit = 1L << arg;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2882
                if ((mask & bit) != 0) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2883
                    return i;  // >0 indicates a dup
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2884
                }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2885
                mask |= bit;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2886
            }
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2887
            if (mask == (1L << newArity) - 1) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2888
                assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2889
                return 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2890
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2891
            // find first zero
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2892
            long zeroBit = Long.lowestOneBit(~mask);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2893
            int zeroPos = Long.numberOfTrailingZeros(zeroBit);
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2894
            assert(zeroPos <= newArity);
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2895
            if (zeroPos == newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2896
                return 0;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2897
            }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2898
            return ~zeroPos;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2899
        } else {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2900
            // same algorithm, different bit set
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2901
            BitSet mask = new BitSet(newArity);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2902
            for (int i = 0; i < reorder.length; i++) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2903
                int arg = reorder[i];
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2904
                if (arg >= newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2905
                    return reorder.length;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2906
                }
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2907
                if (mask.get(arg)) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2908
                    return i;  // >0 indicates a dup
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2909
                }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2910
                mask.set(arg);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2911
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2912
            int zeroPos = mask.nextClearBit(0);
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  2913
            assert(zeroPos <= newArity);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2914
            if (zeroPos == newArity) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2915
                return 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2916
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2917
            return ~zeroPos;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2918
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2919
    }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  2920
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2921
    private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2922
        if (newType.returnType() != oldType.returnType())
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2923
            throw newIllegalArgumentException("return types do not match",
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2924
                    oldType, newType);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2925
        if (reorder.length == oldType.parameterCount()) {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2926
            int limit = newType.parameterCount();
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2927
            boolean bad = false;
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2928
            for (int j = 0; j < reorder.length; j++) {
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2929
                int i = reorder[j];
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2930
                if (i < 0 || i >= limit) {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2931
                    bad = true; break;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2932
                }
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2933
                Class<?> src = newType.parameterType(i);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2934
                Class<?> dst = oldType.parameterType(j);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2935
                if (src != dst)
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2936
                    throw newIllegalArgumentException("parameter types do not match after reorder",
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2937
                            oldType, newType);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2938
            }
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  2939
            if (!bad)  return true;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2940
        }
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  2941
        throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2942
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2943
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2944
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2945
     * 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
  2946
     * constant value every time it is invoked.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2947
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2948
     * 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
  2949
     * 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
  2950
     * 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
  2951
     * <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
  2952
     * @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
  2953
     * @param value the value to return
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2954
     * @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
  2955
     * @throws NullPointerException if the {@code type} argument is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2956
     * @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
  2957
     * @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
  2958
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2959
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2960
    MethodHandle constant(Class<?> type, Object value) {
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2961
        if (type.isPrimitive()) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2962
            if (type == void.class)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2963
                throw newIllegalArgumentException("void type");
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2964
            Wrapper w = Wrapper.forPrimitiveType(type);
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2965
            value = w.convert(value, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2966
            if (w.zero().equals(value))
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2967
                return zero(w, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2968
            return insertArguments(identity(type), 0, value);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2969
        } else {
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2970
            if (value == null)
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2971
                return zero(Wrapper.OBJECT, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  2972
            return identity(type).bindTo(value);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2973
        }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2974
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2975
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2976
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2977
     * 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
  2978
     * @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
  2979
     * @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
  2980
     * @throws NullPointerException if the argument is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2981
     * @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
  2982
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2983
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2984
    MethodHandle identity(Class<?> type) {
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2985
        Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2986
        int pos = btw.ordinal();
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2987
        MethodHandle ident = IDENTITY_MHS[pos];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2988
        if (ident == null) {
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2989
            ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2990
        }
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2991
        if (ident.type().returnType() == type)
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2992
            return ident;
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2993
        // something like identity(Foo.class); do not bother to intern these
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  2994
        assert (btw == Wrapper.OBJECT);
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2995
        return makeIdentity(type);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  2996
    }
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  2997
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  2998
    /**
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  2999
     * Produces a constant method handle of the requested return type which
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3000
     * returns the default value for that type every time it is invoked.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3001
     * The resulting constant method handle will have no side effects.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3002
     * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3003
     * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3004
     * since {@code explicitCastArguments} converts {@code null} to default values.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3005
     * @param type the expected return type of the desired method handle
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3006
     * @return a constant method handle that takes no arguments
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3007
     *         and returns the default value of the given type (or void, if the type is void)
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3008
     * @throws NullPointerException if the argument is null
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3009
     * @see MethodHandles#constant
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3010
     * @see MethodHandles#empty
38774
b2ca0c2ec115 8156868: MethodHandles.zero(Class) doc issues
mhaupt
parents: 38472
diff changeset
  3011
     * @see MethodHandles#explicitCastArguments
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3012
     * @since 9
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3013
     */
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3014
    public static  MethodHandle zero(Class<?> type) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3015
        Objects.requireNonNull(type);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3016
        return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3017
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3018
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3019
    private static MethodHandle identityOrVoid(Class<?> type) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3020
        return type == void.class ? zero(type) : identity(type);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3021
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3022
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3023
    /**
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3024
     * Produces a method handle of the requested type which ignores any arguments, does nothing,
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3025
     * and returns a suitable default depending on the return type.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3026
     * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3027
     * <p>The returned method handle is equivalent to
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3028
     * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3029
     * <p>
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3030
     * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3031
     * {@code guardWithTest(pred, target, empty(target.type())}.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3032
     * @param type the type of the desired method handle
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3033
     * @return a constant method handle of the given type, which returns a default value of the given return type
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3034
     * @throws NullPointerException if the argument is null
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3035
     * @see MethodHandles#zero
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3036
     * @see MethodHandles#constant
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3037
     * @since 9
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3038
     */
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3039
    public static  MethodHandle empty(MethodType type) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3040
        Objects.requireNonNull(type);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3041
        return dropArguments(zero(type.returnType()), 0, type.parameterList());
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3042
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3043
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3044
    private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3045
    private static MethodHandle makeIdentity(Class<?> ptype) {
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  3046
        MethodType mtype = methodType(ptype, ptype);
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3047
        LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3048
        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3049
    }
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3050
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3051
    private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3052
        int pos = btw.ordinal();
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3053
        MethodHandle zero = ZERO_MHS[pos];
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3054
        if (zero == null) {
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3055
            zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3056
        }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3057
        if (zero.type().returnType() == rtype)
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3058
            return zero;
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3059
        assert(btw == Wrapper.OBJECT);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3060
        return makeZero(rtype);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3061
    }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3062
    private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length];
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3063
    private static MethodHandle makeZero(Class<?> rtype) {
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  3064
        MethodType mtype = methodType(rtype);
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3065
        LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3066
        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3067
    }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3068
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  3069
    private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3070
        // Simulate a CAS, to avoid racy duplication of results.
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3071
        MethodHandle prev = cache[pos];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3072
        if (prev != null) return prev;
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3073
        return cache[pos] = value;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3074
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3075
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3076
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3077
     * 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
  3078
     * 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
  3079
     * 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
  3080
     * 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
  3081
     * 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
  3082
     * 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
  3083
     * 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
  3084
     * and calls the original target.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3085
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3086
     * 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
  3087
     * 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
  3088
     * 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
  3089
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3090
     * 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
  3091
     * 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
  3092
     * 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
  3093
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3094
     * 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
  3095
     * 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
  3096
     * 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
  3097
     * and <i>L</i> is the length of the values array.
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3098
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3099
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3100
     * 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
  3101
     * @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
  3102
     * @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
  3103
     * @param values the series of arguments to insert
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3104
     * @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
  3105
     *         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
  3106
     * @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
  3107
     * @see MethodHandle#bindTo
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3108
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3109
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3110
    MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3111
        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
  3112
        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
  3113
        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
  3114
        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
  3115
        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
  3116
            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
  3117
            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
  3118
            if (ptype.isPrimitive()) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3119
                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
  3120
            } else {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3121
                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
  3122
                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
  3123
            }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3124
        }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3125
        return result;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3126
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3127
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3128
    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
  3129
                                                             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
  3130
        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
  3131
        // 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
  3132
        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
  3133
        switch (w) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3134
        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
  3135
        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
  3136
        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
  3137
        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
  3138
        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
  3139
        }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3140
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3141
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3142
    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
  3143
        MethodType oldType = target.type();
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3144
        int outargs = oldType.parameterCount();
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3145
        int inargs  = outargs - insCount;
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3146
        if (inargs < 0)
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3147
            throw newIllegalArgumentException("too many values to insert");
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3148
        if (pos < 0 || pos > inargs)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3149
            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
  3150
        return oldType.ptypes();
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3151
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3152
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3153
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3154
     * 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
  3155
     * 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
  3156
     * 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
  3157
     * 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
  3158
     * at some given position.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3159
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3160
     * 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
  3161
     * 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
  3162
     * 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
  3163
     * 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
  3164
     * they will come after.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3165
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3166
     * <b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3167
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3168
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3169
import static java.lang.invoke.MethodType.*;
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3170
...
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3171
MethodHandle cat = lookup().findVirtual(String.class,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3172
  "concat", methodType(String.class, String.class));
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3173
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
  3174
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
  3175
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
  3176
assertEquals(bigType, d0.type());
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3177
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
  3178
     * }</pre></blockquote>
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3179
     * <p>
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3180
     * This method is also equivalent to the following code:
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3181
     * <blockquote><pre>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3182
     * {@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
  3183
     * </pre></blockquote>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3184
     * @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
  3185
     * @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
  3186
     * @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
  3187
     * @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
  3188
     *         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
  3189
     * @throws NullPointerException if the target is null,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3190
     *                              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
  3191
     * @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
  3192
     *                  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
  3193
     *                  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
  3194
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3195
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3196
    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
  3197
        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
  3198
        int dropped = dropArgumentChecks(oldType, pos, valueTypes);
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3199
        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
  3200
        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
  3201
        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
  3202
        LambdaForm lform = result.form;
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3203
        int insertFormArg = 1 + pos;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3204
        for (Class<?> ptype : valueTypes) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3205
            lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3206
        }
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3207
        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
  3208
        return result;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3209
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3210
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3211
    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
  3212
        int dropped = valueTypes.size();
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3213
        MethodType.checkSlotCount(dropped);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3214
        int outargs = oldType.parameterCount();
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3215
        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
  3216
        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
  3217
            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
  3218
                    + 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
  3219
                    );
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3220
        return dropped;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3221
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3222
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3223
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3224
     * 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
  3225
     * 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
  3226
     * 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
  3227
     * 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
  3228
     * at some given position.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3229
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3230
     * 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
  3231
     * 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
  3232
     * 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
  3233
     * 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
  3234
     * they will come after.
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3235
     * @apiNote
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3236
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3237
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3238
import static java.lang.invoke.MethodType.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3239
...
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3240
MethodHandle cat = lookup().findVirtual(String.class,
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3241
  "concat", methodType(String.class, String.class));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3242
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
  3243
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
  3244
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
  3245
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
  3246
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
  3247
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
  3248
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
  3249
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
  3250
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
  3251
     * }</pre></blockquote>
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3252
     * <p>
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3253
     * This method is also equivalent to the following code:
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3254
     * <blockquote><pre>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3255
     * {@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
  3256
     * </pre></blockquote>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3257
     * @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
  3258
     * @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
  3259
     * @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
  3260
     * @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
  3261
     *         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
  3262
     * @throws NullPointerException if the target is null,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3263
     *                              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
  3264
     * @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
  3265
     *                  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
  3266
     *                  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
  3267
     *                  <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
  3268
     */
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3269
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3270
    MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3271
        return dropArguments(target, pos, Arrays.asList(valueTypes));
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3272
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3273
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3274
    // private version which allows caller some freedom with error handling
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3275
    private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3276
                                      boolean nullOnFailure) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3277
        List<Class<?>> oldTypes = target.type().parameterList();
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3278
        int match = oldTypes.size();
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3279
        if (skip != 0) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3280
            if (skip < 0 || skip > match) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3281
                throw newIllegalArgumentException("illegal skip", skip, target);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3282
            }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3283
            oldTypes = oldTypes.subList(skip, match);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3284
            match -= skip;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3285
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3286
        List<Class<?>> addTypes = newTypes;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3287
        int add = addTypes.size();
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3288
        if (pos != 0) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3289
            if (pos < 0 || pos > add) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3290
                throw newIllegalArgumentException("illegal pos", pos, newTypes);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3291
            }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3292
            addTypes = addTypes.subList(pos, add);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3293
            add -= pos; assert(addTypes.size() == add);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3294
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3295
        // Do not add types which already match the existing arguments.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3296
        if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3297
            if (nullOnFailure) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3298
                return null;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3299
            }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3300
            throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3301
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3302
        addTypes = addTypes.subList(match, add);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3303
        add -= match; assert(addTypes.size() == add);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3304
        // newTypes:     (   P*[pos], M*[match], A*[add] )
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3305
        // target: ( S*[skip],        M*[match]  )
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3306
        MethodHandle adapter = target;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3307
        if (add > 0) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3308
            adapter = dropArguments(adapter, skip+ match, addTypes);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3309
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3310
        // adapter: (S*[skip],        M*[match], A*[add] )
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3311
        if (pos > 0) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3312
            adapter = dropArguments(adapter, skip, newTypes.subList(0, pos));
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3313
       }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3314
        // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3315
        return adapter;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3316
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3317
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3318
    /**
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3319
     * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3320
     * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3321
     * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list,
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3322
     * at the given position.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3323
     * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3324
     * positions of the target method handle's parameters, as if by {@link #dropArguments}.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3325
     * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip},
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3326
     * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3327
     * target list.)
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3328
     * The target's return type will be unchanged.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3329
     * @apiNote
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3330
     * Two method handles whose argument lists are "effectively identical" (i.e., identical
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3331
     * in a common prefix) may be mutually converted to a common type
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3332
     * by two calls to {@code dropArgumentsToMatch}, as follows:
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3333
     * <blockquote><pre>{@code
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3334
import static java.lang.invoke.MethodHandles.*;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3335
import static java.lang.invoke.MethodType.*;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3336
...
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3337
...
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3338
MethodHandle h0 = constant(boolean.class, true);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3339
MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3340
MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3341
MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3342
if (h1.type().parameterCount() < h2.type().parameterCount())
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3343
    h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3344
else
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3345
    h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3346
MethodHandle h3 = guardWithTest(h0, h1, h2);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3347
assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3348
     * }</pre></blockquote>
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3349
     * @param target the method handle to adapt
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3350
     * @param skip number of targets parameters to disregard (they will be unchanged)
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3351
     * @param newTypes the desired argument list of the method handle
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3352
     * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3353
     * @return a possibly adapted method handle
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3354
     * @throws NullPointerException if either argument is null
38785
dacdc5add5eb 8158171: MethodHandles.dropArgumentsToMatch(...) non-documented IAE
srastogi
parents: 38774
diff changeset
  3355
     * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
dacdc5add5eb 8158171: MethodHandles.dropArgumentsToMatch(...) non-documented IAE
srastogi
parents: 38774
diff changeset
  3356
     *         or if either index is out of range in its corresponding list,
dacdc5add5eb 8158171: MethodHandles.dropArgumentsToMatch(...) non-documented IAE
srastogi
parents: 38774
diff changeset
  3357
     *         or if the non-skipped target parameter types match the new types at {@code pos}
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3358
     * @since 9
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3359
     */
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3360
    public static
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3361
    MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3362
        Objects.requireNonNull(target);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3363
        Objects.requireNonNull(newTypes);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3364
        return dropArgumentsToMatch(target, skip, newTypes, pos, false);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3365
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3366
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3367
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3368
     * Adapts a target method handle by pre-processing
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3369
     * 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
  3370
     * 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
  3371
     * replaced by the result of its corresponding filter function.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3372
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3373
     * 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
  3374
     * 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
  3375
     * 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
  3376
     * 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
  3377
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3378
     * 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
  3379
     * and the corresponding arguments left unchanged.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3380
     * (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
  3381
     * 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
  3382
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3383
     * 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
  3384
     * 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
  3385
     * 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
  3386
     * replaces the corresponding argument type of the target
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3387
     * in the resulting adapted method handle.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3388
     * 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
  3389
     * parameter type of the target.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3390
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3391
     * 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
  3392
     * (null or not)
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3393
     * 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
  3394
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3395
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3396
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3397
import static java.lang.invoke.MethodType.*;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3398
...
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3399
MethodHandle cat = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3400
  "concat", methodType(String.class, String.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3401
MethodHandle upcase = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3402
  "toUpperCase", methodType(String.class));
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3403
assertEquals("xy", (String) cat.invokeExact("x", "y"));
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3404
MethodHandle f0 = filterArguments(cat, 0, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3405
assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3406
MethodHandle f1 = filterArguments(cat, 1, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3407
assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3408
MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3409
assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3410
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3411
     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3412
     * denotes the return type of both the {@code target} and resulting adapter.
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3413
     * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3414
     * of the parameters and arguments that precede and follow the filter position
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3415
     * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3416
     * values of the filtered parameters and arguments; they also represent the
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3417
     * return types of the {@code filter[i]} handles. The latter accept arguments
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3418
     * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3419
     * the resulting adapter.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3420
     * <blockquote><pre>{@code
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3421
     * T target(P... p, A[i]... a[i], B... b);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3422
     * 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
  3423
     * T adapter(P... p, V[i]... v[i], B... b) {
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3424
     *   return target(p..., filter[i](v[i])..., b...);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3425
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3426
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3427
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3428
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3429
     * 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
  3430
     *
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3431
     * @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
  3432
     * @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
  3433
     * @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
  3434
     * @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
  3435
     * @throws NullPointerException if the target is null
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3436
     *                              or if the {@code filters} array is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3437
     * @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
  3438
     *          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
  3439
     *          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
  3440
     *          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
  3441
     *          <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
  3442
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3443
    public static
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3444
    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
  3445
        filterArgumentsCheckArity(target, pos, filters);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3446
        MethodHandle adapter = target;
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3447
        int curPos = pos-1;  // pre-incremented
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3448
        for (MethodHandle filter : filters) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3449
            curPos += 1;
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3450
            if (filter == null)  continue;  // ignore null elements of filters
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3451
            adapter = filterArgument(adapter, curPos, filter);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3452
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3453
        return adapter;
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3454
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3455
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3456
    /*non-public*/ static
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3457
    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
  3458
        filterArgumentChecks(target, pos, filter);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3459
        MethodType targetType = target.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3460
        MethodType filterType = filter.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3461
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3462
        Class<?> newParamType = filterType.parameterType(0);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3463
        LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3464
        MethodType newType = targetType.changeParameterType(pos, newParamType);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3465
        result = result.copyWithExtendL(newType, lform, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3466
        return result;
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3467
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3468
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3469
    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
  3470
        MethodType targetType = target.type();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3471
        int maxPos = targetType.parameterCount();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3472
        if (pos + filters.length > maxPos)
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3473
            throw newIllegalArgumentException("too many filters");
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3474
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3475
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3476
    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
  3477
        MethodType targetType = target.type();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3478
        MethodType filterType = filter.type();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3479
        if (filterType.parameterCount() != 1
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3480
            || filterType.returnType() != targetType.parameterType(pos))
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3481
            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3482
    }
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3483
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3484
    /**
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3485
     * Adapts a target method handle by pre-processing
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3486
     * 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
  3487
     * 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
  3488
     * filter function.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3489
     * 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
  3490
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3491
     * 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
  3492
     * 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
  3493
     * any arguments not passed to the filter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3494
     * 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
  3495
     * not passed to the filter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3496
     * 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
  3497
     * 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
  3498
     * passed to the adapter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3499
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3500
     * The argument types (if any) of the filter
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3501
     * 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
  3502
     * in the resulting adapted method handle.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3503
     * 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
  3504
     * 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
  3505
     * 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
  3506
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3507
     * 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
  3508
     * {@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
  3509
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3510
     * <blockquote><pre>{@code
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3511
import static java.lang.invoke.MethodHandles.*;
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3512
import static java.lang.invoke.MethodType.*;
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3513
...
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3514
MethodHandle deepToString = publicLookup()
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3515
  .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
  3516
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3517
MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3518
assertEquals("[strange]", (String) ts1.invokeExact("strange"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3519
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3520
MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3521
assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3522
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3523
MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3524
MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3525
assertEquals("[top, [up, down], strange]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3526
             (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3527
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3528
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
  3529
assertEquals("[top, [up, down], [strange]]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3530
             (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
  3531
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3532
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
  3533
assertEquals("[top, [[up, down, strange], charm], bottom]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3534
             (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
  3535
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3536
     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3537
     * represents the return type of the {@code target} and resulting adapter.
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3538
     * {@code V}/{@code v} stand for the return type and value of the
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3539
     * {@code filter}, which are also found in the signature and arguments of
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3540
     * the {@code target}, respectively, unless {@code V} is {@code void}.
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3541
     * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3542
     * and values preceding and following the collection position, {@code pos},
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3543
     * in the {@code target}'s signature. They also turn up in the resulting
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3544
     * adapter's signature and arguments, where they surround
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3545
     * {@code B}/{@code b}, which represent the parameter types and arguments
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3546
     * to the {@code filter} (if any).
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3547
     * <blockquote><pre>{@code
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3548
     * T target(A...,V,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3549
     * V filter(B...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3550
     * T adapter(A... a,B... b,C... c) {
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3551
     *   V v = filter(b...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3552
     *   return target(a...,v,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3553
     * }
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3554
     * // and if the filter has no arguments:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3555
     * T target2(A...,V,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3556
     * V filter2();
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3557
     * T adapter2(A... a,C... c) {
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3558
     *   V v = filter2();
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3559
     *   return target2(a...,v,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3560
     * }
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3561
     * // and if the filter has a void return:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3562
     * T target3(A...,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3563
     * void filter3(B...);
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3564
     * T adapter3(A... a,B... b,C... c) {
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3565
     *   filter3(b...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3566
     *   return target3(a...,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3567
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3568
     * }</pre></blockquote>
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3569
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3570
     * 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
  3571
     * 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
  3572
     * steps as follows:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3573
     * <blockquote><pre>{@code
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3574
     * 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
  3575
     * mh = MethodHandles.foldArguments(mh, coll); //step 1
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3576
     * }</pre></blockquote>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3577
     * 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
  3578
     * (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
  3579
     * is equivalent to {@code filterReturnValue(coll, mh)}.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3580
     * 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
  3581
     * 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
  3582
     * is equivalent to {@code filterArguments(mh, N, coll)}.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3583
     * Other equivalences are possible but would require argument permutation.
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3584
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3585
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3586
     * 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
  3587
     *
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3588
     * @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
  3589
     * @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
  3590
     *            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
  3591
     * @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
  3592
     * @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
  3593
     * @throws NullPointerException if either argument is null
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3594
     * @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
  3595
     *          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
  3596
     *          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
  3597
     *          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
  3598
     *          <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
  3599
     * @see MethodHandles#foldArguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3600
     * @see MethodHandles#filterArguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3601
     * @see MethodHandles#filterReturnValue
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3602
     */
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3603
    public static
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3604
    MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3605
        MethodType newType = collectArgumentsChecks(target, pos, filter);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3606
        MethodType collectorType = filter.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3607
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3608
        LambdaForm lform;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3609
        if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3610
            lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3611
            if (lform != null) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3612
                return result.copyWith(newType, lform);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3613
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3614
        }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3615
        lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3616
        return result.copyWithExtendL(newType, lform, filter);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3617
    }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3618
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3619
    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
  3620
        MethodType targetType = target.type();
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3621
        MethodType filterType = filter.type();
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3622
        Class<?> rtype = filterType.returnType();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3623
        List<Class<?>> filterArgs = filterType.parameterList();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3624
        if (rtype == void.class) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3625
            return targetType.insertParameterTypes(pos, filterArgs);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3626
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3627
        if (rtype != targetType.parameterType(pos)) {
13610
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  3628
            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
  3629
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3630
        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
  3631
    }
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  3632
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3633
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3634
     * 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
  3635
     * 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
  3636
     * 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
  3637
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3638
     * 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
  3639
     * its only argument.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3640
     * 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
  3641
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3642
     * The return type of the filter
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3643
     * replaces the return type of the target
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3644
     * 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
  3645
     * 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
  3646
     * return type of the target.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3647
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3648
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3649
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3650
import static java.lang.invoke.MethodType.*;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3651
...
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3652
MethodHandle cat = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3653
  "concat", methodType(String.class, String.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3654
MethodHandle length = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3655
  "length", methodType(int.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3656
System.out.println((String) cat.invokeExact("x", "y")); // xy
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3657
MethodHandle f0 = filterReturnValue(cat, length);
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3658
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
  3659
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3660
     * <p>Here is pseudocode for the resulting adapter. In the code,
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3661
     * {@code T}/{@code t} represent the result type and value of the
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3662
     * {@code target}; {@code V}, the result type of the {@code filter}; and
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3663
     * {@code A}/{@code a}, the types and values of the parameters and arguments
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3664
     * of the {@code target} as well as the resulting adapter.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3665
     * <blockquote><pre>{@code
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3666
     * T target(A...);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3667
     * V filter(T);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3668
     * V adapter(A... a) {
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3669
     *   T t = target(a...);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3670
     *   return filter(t);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3671
     * }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3672
     * // 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
  3673
     * void target2(A...);
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3674
     * V filter2();
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3675
     * V adapter2(A... a) {
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3676
     *   target2(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3677
     *   return filter2();
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3678
     * }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3679
     * // and if the filter has a void return:
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3680
     * T target3(A...);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3681
     * void filter3(V);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3682
     * void adapter3(A... a) {
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3683
     *   T t = target3(a...);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3684
     *   filter3(t);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3685
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3686
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3687
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3688
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3689
     * 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
  3690
     * @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
  3691
     * @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
  3692
     * @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
  3693
     * @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
  3694
     * @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
  3695
     *          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
  3696
     */
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3697
    public static
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  3698
    MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  3699
        MethodType targetType = target.type();
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  3700
        MethodType filterType = filter.type();
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3701
        filterReturnValueChecks(targetType, filterType);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3702
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3703
        BasicType rtype = BasicType.basicType(filterType.returnType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3704
        LambdaForm lform = result.editor().filterReturnForm(rtype, false);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3705
        MethodType newType = targetType.changeReturnType(filterType.returnType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3706
        result = result.copyWithExtendL(newType, lform, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3707
        return result;
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3708
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3709
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3710
    private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3711
        Class<?> rtype = targetType.returnType();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3712
        int filterValues = filterType.parameterCount();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3713
        if (filterValues == 0
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3714
                ? (rtype != void.class)
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3715
                : (rtype != filterType.parameterType(0)))
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3716
            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
  3717
    }
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  3718
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3719
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3720
     * Adapts a target method handle by pre-processing
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3721
     * 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
  3722
     * 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
  3723
     * sequence of arguments.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3724
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3725
     * 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
  3726
     * 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
  3727
     * 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
  3728
     * (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
  3729
     * 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
  3730
     * 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
  3731
     * arguments.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3732
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3733
     * 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
  3734
     * 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
  3735
     * {@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
  3736
     * of the combiner.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3737
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3738
     * 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
  3739
     * 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
  3740
     * 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
  3741
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3742
     * 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
  3743
     * first parameter type is dropped,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3744
     * 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
  3745
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3746
     * (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
  3747
     * 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
  3748
     * 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
  3749
     * 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
  3750
     * 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
  3751
     * target.)
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3752
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3753
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3754
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
  3755
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
  3756
...
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3757
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
  3758
  "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
  3759
    .bindTo(System.out);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3760
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
  3761
  "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
  3762
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
  3763
MethodHandle catTrace = foldArguments(cat, trace);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3764
// also prints "boo":
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3765
assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3766
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3767
     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3768
     * represents the result type of the {@code target} and resulting adapter.
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3769
     * {@code V}/{@code v} represent the type and value of the parameter and argument
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3770
     * of {@code target} that precedes the folding position; {@code V} also is
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3771
     * the result type of the {@code combiner}. {@code A}/{@code a} denote the
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3772
     * types and values of the {@code N} parameters and arguments at the folding
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3773
     * position. {@code B}/{@code b} represent the types and values of the
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3774
     * {@code target} parameters and arguments that follow the folded parameters
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3775
     * and arguments.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3776
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3777
     * // there are N arguments in A...
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3778
     * T target(V, A[N]..., B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3779
     * V combiner(A...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3780
     * T adapter(A... a, B... b) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3781
     *   V v = combiner(a...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3782
     *   return target(v, a..., b...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3783
     * }
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3784
     * // 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
  3785
     * T target2(A[N]..., B...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3786
     * void combiner2(A...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3787
     * 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
  3788
     *   combiner2(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3789
     *   return target2(a..., b...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3790
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3791
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3792
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3793
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3794
     * 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
  3795
     * @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
  3796
     * @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
  3797
     * @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
  3798
     * @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
  3799
     * @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
  3800
     *          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
  3801
     *          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
  3802
     *          of the target
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3803
     *          (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
  3804
     *          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
  3805
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3806
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3807
    MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3808
        return foldArguments(target, 0, combiner);
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3809
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3810
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3811
    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
  3812
        int foldArgs   = combinerType.parameterCount();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3813
        Class<?> rtype = combinerType.returnType();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3814
        int foldVals = rtype == void.class ? 0 : 1;
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3815
        int afterInsertPos = foldPos + foldVals;
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3816
        boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3817
        if (ok && !(combinerType.parameterList()
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3818
                    .equals(targetType.parameterList().subList(afterInsertPos,
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3819
                                                               afterInsertPos + foldArgs))))
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  3820
            ok = false;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3821
        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
  3822
            ok = false;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3823
        if (!ok)
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3824
            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
  3825
        return rtype;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3826
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3827
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3828
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3829
     * 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
  3830
     * 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
  3831
     * 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
  3832
     * All three method handles must have the same corresponding
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3833
     * 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
  3834
     * 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
  3835
     * to have fewer arguments than the other two method handles.
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3836
     * <p>
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3837
     * Here is pseudocode for the resulting adapter. In the code, {@code T}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3838
     * represents the uniform result type of the three involved handles;
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3839
     * {@code A}/{@code a}, the types and values of the {@code target}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3840
     * parameters and arguments that are consumed by the {@code test}; and
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3841
     * {@code B}/{@code b}, those types and values of the {@code target}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3842
     * parameters and arguments that are not consumed by the {@code test}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3843
     * <blockquote><pre>{@code
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3844
     * boolean test(A...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3845
     * T target(A...,B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3846
     * T fallback(A...,B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3847
     * T adapter(A... a,B... b) {
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3848
     *   if (test(a...))
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3849
     *     return target(a..., b...);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3850
     *   else
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3851
     *     return fallback(a..., b...);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3852
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3853
     * }</pre></blockquote>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3854
     * 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
  3855
     * 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
  3856
     * 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
  3857
     * @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
  3858
     * @param target method handle to call if test passes
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3859
     * @param fallback method handle to call if test fails
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3860
     * @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
  3861
     * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3862
     * @throws IllegalArgumentException if {@code test} does not return boolean,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3863
     *          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
  3864
     *          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
  3865
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3866
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3867
    MethodHandle guardWithTest(MethodHandle test,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3868
                               MethodHandle target,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3869
                               MethodHandle fallback) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3870
        MethodType gtype = test.type();
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3871
        MethodType ttype = target.type();
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3872
        MethodType ftype = fallback.type();
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3873
        if (!ttype.equals(ftype))
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3874
            throw misMatchedTypes("target and fallback types", ttype, ftype);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3875
        if (gtype.returnType() != boolean.class)
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3876
            throw newIllegalArgumentException("guard type is not a predicate "+gtype);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3877
        List<Class<?>> targs = ttype.parameterList();
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3878
        test = dropArgumentsToMatch(test, 0, targs, 0, true);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3879
        if (test == null) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3880
            throw misMatchedTypes("target and test types", ttype, gtype);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3881
        }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  3882
        return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3883
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3884
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3885
    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
  3886
        return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3887
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3888
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3889
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3890
     * 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
  3891
     * by running it inside an exception handler.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3892
     * 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
  3893
     * 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
  3894
     * 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
  3895
     * <p>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3896
     * The target and handler must have the same corresponding
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3897
     * 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
  3898
     * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3899
     * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3900
     * <p>
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3901
     * Here is pseudocode for the resulting adapter. In the code, {@code T}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3902
     * represents the return type of the {@code target} and {@code handler},
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3903
     * and correspondingly that of the resulting adapter; {@code A}/{@code a},
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3904
     * the types and values of arguments to the resulting handle consumed by
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3905
     * {@code handler}; and {@code B}/{@code b}, those of arguments to the
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3906
     * resulting handle discarded by {@code handler}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3907
     * <blockquote><pre>{@code
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3908
     * T target(A..., B...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3909
     * T handler(ExType, A...);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3910
     * T adapter(A... a, B... b) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3911
     *   try {
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3912
     *     return target(a..., b...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3913
     *   } catch (ExType ex) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3914
     *     return handler(ex, a...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3915
     *   }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3916
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3917
     * }</pre></blockquote>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3918
     * 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
  3919
     * 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
  3920
     * 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
  3921
     * <p>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3922
     * 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
  3923
     * always throws.  (This might happen, for instance, because the handler
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3924
     * is simulating a {@code finally} clause).
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3925
     * 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
  3926
     * with {@link #throwException throwException},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3927
     * 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
  3928
     * @param target method handle to call
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3929
     * @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
  3930
     * @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
  3931
     * @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
  3932
     * @throws NullPointerException if any argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3933
     * @throws IllegalArgumentException if {@code handler} does not accept
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3934
     *          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
  3935
     *          not match in their return types and their
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3936
     *          corresponding parameters
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3937
     * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3938
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3939
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3940
    MethodHandle catchException(MethodHandle target,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3941
                                Class<? extends Throwable> exType,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3942
                                MethodHandle handler) {
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3943
        MethodType ttype = target.type();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3944
        MethodType htype = handler.type();
34959
4e7903220c89 8147078: MethodHandles.catchException does not enforce Throwable subtype
mhaupt
parents: 34882
diff changeset
  3945
        if (!Throwable.class.isAssignableFrom(exType))
4e7903220c89 8147078: MethodHandles.catchException does not enforce Throwable subtype
mhaupt
parents: 34882
diff changeset
  3946
            throw new ClassCastException(exType.getName());
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3947
        if (htype.parameterCount() < 1 ||
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3948
            !htype.parameterType(0).isAssignableFrom(exType))
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3949
            throw newIllegalArgumentException("handler does not accept exception type "+exType);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3950
        if (htype.returnType() != ttype.returnType())
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3951
            throw misMatchedTypes("target and handler return types", ttype, htype);
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3952
        handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3953
        if (handler == null) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3954
            throw misMatchedTypes("target and handler types", ttype, htype);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3955
        }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  3956
        return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3957
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3958
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3959
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3960
     * 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
  3961
     * 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
  3962
     * and immediately throw it as an exception.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3963
     * 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
  3964
     * 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
  3965
     * 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
  3966
     * @param returnType the return type of the desired method handle
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  3967
     * @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
  3968
     * @return method handle which can throw the given exceptions
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3969
     * @throws NullPointerException if either argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3970
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3971
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3972
    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
  3973
        if (!Throwable.class.isAssignableFrom(exType))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3974
            throw new ClassCastException(exType.getName());
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  3975
        return MethodHandleImpl.throwException(methodType(returnType, exType));
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3976
    }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3977
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3978
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3979
     * 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
  3980
     * 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
  3981
     * 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
  3982
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3983
     * 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
  3984
     * 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
  3985
     * 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
  3986
     * terms of method handles, each clause will determine four actions:<ul>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3987
     * <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
  3988
     * <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
  3989
     * <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
  3990
     * <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
  3991
     * </ul>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3992
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3993
     * 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
  3994
     * this case. See below for a detailed description.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3995
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  3996
     * 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
  3997
     * 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
  3998
     * 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
  3999
     * if by {@link #dropArguments}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4000
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4001
     * 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
  4002
     * 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
  4003
     * 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
  4004
     * 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
  4005
     * 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
  4006
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4007
     * <em>Step 0: Determine clause structure.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4008
     * <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
  4009
     * <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
  4010
     * <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
  4011
     * four. Padding takes place by appending elements to the array.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4012
     * <li>Clauses with all {@code null}s are disregarded.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4013
     * <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
  4014
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4015
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4016
     * <em>Step 1A: Determine iteration variables.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4017
     * <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
  4018
     * <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
  4019
     * use the common return type (they must be identical).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4020
     * <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
  4021
     * <li>This list of types is called the "common prefix".
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4022
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4023
     * <p>
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4024
     * <em>Step 1B: Determine loop parameters.</em><ul>
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4025
     * <li><b>If at least one init function is given,</b><ol type="a">
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4026
     *   <li>Examine init function parameter lists.
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4027
     *   <li>Omitted init functions are deemed to have {@code null} parameter lists.
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4028
     *   <li>All init function parameter lists must be effectively identical.
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4029
     *   <li>The longest parameter list (which is necessarily unique) is called the "common suffix".
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4030
     * </ol>
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4031
     * <li><b>If no init function is given,</b><ol type="a">
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4032
     *   <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix".
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4033
     *   <li>The longest of these suffixes is taken as the "common suffix".
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4034
     * </ol></ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4035
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4036
     * <em>Step 1C: Determine loop return type.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4037
     * <li>Examine fini function return types, disregarding omitted fini functions.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4038
     * <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
  4039
     * <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
  4040
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4041
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4042
     * <em>Step 1D: Check other types.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4043
     * <li>There must be at least one non-omitted pred function.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4044
     * <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
  4045
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4046
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4047
     * <em>Step 2: Determine parameter lists.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4048
     * <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
  4049
     * <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
  4050
     * lists are already effectively identical to the common suffix.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4051
     * <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
  4052
     * followed by the common suffix, called the "common parameter sequence".
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4053
     * <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
  4054
     * sequence.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4055
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4056
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4057
     * <em>Step 3: Fill in omitted functions.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4058
     * <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
  4059
     * {@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
  4060
     * 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
  4061
     * {@linkplain MethodHandle#asType type conversion}.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4062
     * <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
  4063
     * 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
  4064
     * 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
  4065
     * <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
  4066
     * <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
  4067
     * as this clause is concerned.)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4068
     * <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
  4069
     * loop return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4070
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4071
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4072
     * <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
  4073
     * <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
  4074
     * 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
  4075
     * {@linkplain #dropArguments dropping arguments}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4076
     * <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
  4077
     * 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
  4078
     * of the list by {@linkplain #dropArguments dropping arguments}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4079
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4080
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4081
     * <em>Final observations.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4082
     * <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
  4083
     * <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
  4084
     * <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
  4085
     * <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
  4086
     * (non-{@code void}) iteration variables followed by loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4087
     * <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
  4088
     * <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
  4089
     * common prefix.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4090
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4091
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4092
     * <em>Loop execution.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4093
     * <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
  4094
     * every clause function. These locals are loop invariant.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4095
     * <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
  4096
     * 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
  4097
     * functions, as noted above).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4098
     * <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
  4099
     * 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
  4100
     * <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
  4101
     * returns {@code false}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4102
     * <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
  4103
     * updated value is immediately visible to all subsequent function calls.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4104
     * <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
  4105
     * is returned from the loop as a whole.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4106
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4107
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4108
     * 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
  4109
     * 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
  4110
     * result types of finalizers as well as of the resulting loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4111
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4112
     * V... init...(A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4113
     * boolean pred...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4114
     * V... step...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4115
     * R fini...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4116
     * R loop(A... a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4117
     *   V... v... = init...(a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4118
     *   for (;;) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4119
     *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4120
     *       v = s(v..., a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4121
     *       if (!p(v..., a...)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4122
     *         return f(v..., a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4123
     *       }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4124
     *     }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4125
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4126
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4127
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4128
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4129
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4130
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4131
     * // iterative implementation of the factorial function as a loop handle
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4132
     * static int one(int k) { return 1; }
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4133
     * static int inc(int i, int acc, int k) { return i + 1; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4134
     * static int mult(int i, int acc, int k) { return i * acc; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4135
     * static boolean pred(int i, int acc, int k) { return i < k; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4136
     * static int fin(int i, int acc, int k) { return acc; }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4137
     * // 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
  4138
     * // null initializer for counter, should initialize to 0
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4139
     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4140
     * 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
  4141
     * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4142
     * assertEquals(120, loop.invoke(5));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4143
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4144
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4145
     * @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
  4146
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4147
     * @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
  4148
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4149
     * @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
  4150
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4151
     * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4152
     * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4153
     * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4154
     * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4155
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4156
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4157
    public static MethodHandle loop(MethodHandle[]... clauses) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4158
        // Step 0: determine clause structure.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4159
        checkLoop0(clauses);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4160
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4161
        List<MethodHandle> init = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4162
        List<MethodHandle> step = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4163
        List<MethodHandle> pred = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4164
        List<MethodHandle> fini = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4165
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4166
        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
  4167
            init.add(clause[0]); // all clauses have at least length 1
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4168
            step.add(clause.length <= 1 ? null : clause[1]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4169
            pred.add(clause.length <= 2 ? null : clause[2]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4170
            fini.add(clause.length <= 3 ? null : clause[3]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4171
        });
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4172
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4173
        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
  4174
        final int nclauses = init.size();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4175
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4176
        // Step 1A: determine iteration variables.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4177
        final List<Class<?>> iterationVariableTypes = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4178
        for (int i = 0; i < nclauses; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4179
            MethodHandle in = init.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4180
            MethodHandle st = step.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4181
            if (in == null && st == null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4182
                iterationVariableTypes.add(void.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4183
            } else if (in != null && st != null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4184
                checkLoop1a(i, in, st);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4185
                iterationVariableTypes.add(in.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4186
            } else {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4187
                iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4188
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4189
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4190
        final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4191
                collect(Collectors.toList());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4192
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4193
        // Step 1B: determine loop parameters.
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4194
        final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4195
        checkLoop1b(init, commonSuffix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4196
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4197
        // Step 1C: determine loop return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4198
        // Step 1D: check other types.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4199
        final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4200
                map(MethodType::returnType).findFirst().orElse(void.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4201
        checkLoop1cd(pred, fini, loopReturnType);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4202
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4203
        // Step 2: determine parameter lists.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4204
        final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4205
        commonParameterSequence.addAll(commonSuffix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4206
        checkLoop2(step, pred, fini, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4207
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4208
        // Step 3: fill in omitted functions.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4209
        for (int i = 0; i < nclauses; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4210
            Class<?> t = iterationVariableTypes.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4211
            if (init.get(i) == null) {
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4212
                init.set(i, empty(methodType(t, commonSuffix)));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4213
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4214
            if (step.get(i) == null) {
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4215
                step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4216
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4217
            if (pred.get(i) == null) {
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4218
                pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4219
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4220
            if (fini.get(i) == null) {
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4221
                fini.set(i, empty(methodType(t, commonParameterSequence)));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4222
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4223
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4224
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4225
        // Step 4: fill in missing parameter types.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4226
        List<MethodHandle> finit = fillParameterTypes(init, commonSuffix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4227
        List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4228
        List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4229
        List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4230
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4231
        assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4232
                allMatch(pl -> pl.equals(commonSuffix));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4233
        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
  4234
                allMatch(pl -> pl.equals(commonParameterSequence));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4235
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4236
        return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4237
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4238
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4239
    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
  4240
        return hs.stream().map(h -> {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4241
            int pc = h.type().parameterCount();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4242
            int tpsize = targetParams.size();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4243
            return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4244
        }).collect(Collectors.toList());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4245
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4246
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4247
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4248
     * 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
  4249
     * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4250
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4251
     * 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
  4252
     * 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
  4253
     * 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
  4254
     * 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
  4255
     * generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4256
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4257
     * 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
  4258
     * 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
  4259
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4260
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4261
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4262
     * boolean pred(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4263
     * V body(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4264
     * V whileLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4265
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4266
     *   while (pred(v, a)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4267
     *     v = body(v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4268
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4269
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4270
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4271
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4272
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4273
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4274
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4275
     * // implement the zip function for lists as a loop handle
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4276
     * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4277
     * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4278
     * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4279
     *   zip.add(a.next());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4280
     *   zip.add(b.next());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4281
     *   return zip;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4282
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4283
     * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
36218
f02215b8d857 8150953: j.l.i.MethodHandles: example section in whileLoop(...) provides example for doWhileLoop
mhaupt
parents: 36136
diff changeset
  4284
     * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4285
     * List<String> a = Arrays.asList("a", "b", "c", "d");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4286
     * List<String> b = Arrays.asList("e", "f", "g", "h");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4287
     * 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
  4288
     * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4289
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4290
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4291
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4292
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4293
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4294
     * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4295
     *     MethodHandle[]
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4296
     *         checkExit = {null, null, pred, identity(init.type().returnType())},
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4297
     *         varBody = {init, body};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4298
     *     return loop(checkExit, varBody);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4299
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4300
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4301
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4302
     * @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
  4303
     *             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
  4304
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4305
     * @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
  4306
     * @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
  4307
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4308
     * @return the value of the loop variable as the loop terminates.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4309
     * @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
  4310
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4311
     * @see MethodHandles#loop(MethodHandle[][])
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4312
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4313
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4314
    public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4315
        MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4316
                identity(init.type().returnType());
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4317
        MethodHandle[] checkExit = {null, null, pred, fin};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4318
        MethodHandle[] varBody = {init, body};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4319
        return loop(checkExit, varBody);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4320
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4321
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4322
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4323
     * 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
  4324
     * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4325
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4326
     * 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
  4327
     * 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
  4328
     * 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
  4329
     * 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
  4330
     * generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4331
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4332
     * 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
  4333
     * 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
  4334
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4335
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4336
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4337
     * boolean pred(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4338
     * V body(V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4339
     * V doWhileLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4340
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4341
     *   do {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4342
     *     v = body(v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4343
     *   } while (pred(v, a));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4344
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4345
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4346
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4347
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4348
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4349
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4350
     * // int i = 0; while (i < limit) { ++i; } return i; => limit
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4351
     * static int zero(int limit) { return 0; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4352
     * static int step(int i, int limit) { return i + 1; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4353
     * static boolean pred(int i, int limit) { return i < limit; }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4354
     * // 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
  4355
     * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4356
     * assertEquals(23, loop.invoke(23));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4357
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4358
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4359
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4360
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4361
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4362
     * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4363
     *     MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) };
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4364
     *     return loop(clause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4365
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4366
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4367
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4368
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4369
     * @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
  4370
     *             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
  4371
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4372
     * @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
  4373
     * @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
  4374
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4375
     * @return the value of the loop variable as the loop terminates.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4376
     * @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
  4377
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4378
     * @see MethodHandles#loop(MethodHandle[][])
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4379
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4380
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4381
    public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4382
        MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4383
                identity(init.type().returnType());
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4384
        MethodHandle[] clause = {init, body, pred, fin};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4385
        return loop(clause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4386
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4387
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4388
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4389
     * 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
  4390
     * {@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
  4391
     * 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
  4392
     * 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
  4393
     * combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4394
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4395
     * 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
  4396
     * 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
  4397
     * 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
  4398
     * 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
  4399
     * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4400
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4401
     * 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
  4402
     * 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
  4403
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4404
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4405
     * int iterations(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4406
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4407
     * V body(int, V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4408
     * V countedLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4409
     *   int end = iterations(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4410
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4411
     *   for (int i = 0; i < end; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4412
     *     v = body(i, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4413
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4414
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4415
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4416
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4417
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4418
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4419
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4420
     * // 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
  4421
     * // => a variation on a well known theme
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4422
     * static String start(String arg) { return arg; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4423
     * static String step(int counter, String v, String arg) { return "na " + v; }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4424
     * // 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
  4425
     * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
8e29bd2b5e0e 8143343: add JEP 274 Javadoc tests to JavaDocExamplesTest
mhaupt
parents: 33874
diff changeset
  4426
     * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4427
     * 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
  4428
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4429
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4430
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4431
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4432
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4433
     * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4434
     *     return countedLoop(null, iterations, init, body);  // null => constant zero
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4435
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4436
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4437
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4438
     * @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
  4439
     * @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
  4440
     *             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
  4441
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4442
     * @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
  4443
     *             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
  4444
     *             additional loop-local variable plus loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4445
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4446
     * @return a method handle representing the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4447
     * @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
  4448
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4449
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4450
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4451
    public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4452
        return countedLoop(null, iterations, init, body);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4453
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4454
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4455
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4456
     * 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
  4457
     * 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
  4458
     * 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
  4459
     * 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
  4460
     * 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
  4461
     * obtained by running {@code init}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4462
     * This is a
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4463
     * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4464
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4465
     * 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
  4466
     * #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
  4467
     * 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
  4468
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4469
     * 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
  4470
     * 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
  4471
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4472
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4473
     * int start(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4474
     * int end(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4475
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4476
     * V body(int, V, A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4477
     * V countedLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4478
     *   int s = start(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4479
     *   int e = end(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4480
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4481
     *   for (int i = s; i < e; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4482
     *     v = body(i, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4483
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4484
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4485
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4486
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4487
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4488
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4489
     * @implSpec The implementation of this method is equivalent to:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4490
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4491
     * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4492
     *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
37340
81f996e37e7f 8153637: MethodHandles.countedLoop/3 initialises loop counter to 1 instead of 0
mhaupt
parents: 36935
diff changeset
  4493
     *     // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int,
81f996e37e7f 8153637: MethodHandles.countedLoop/3 initialises loop counter to 1 instead of 0
mhaupt
parents: 36935
diff changeset
  4494
     *     // assume MH_decrement is a handle to x-1 of type int
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4495
     *     MethodHandle[]
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4496
     *         indexVar = {start, MH_increment}, // i = start; i = i+1
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4497
     *         loopLimit = {end, null, MH_lessThan, returnVar }, // i<end
37340
81f996e37e7f 8153637: MethodHandles.countedLoop/3 initialises loop counter to 1 instead of 0
mhaupt
parents: 36935
diff changeset
  4498
     *         bodyClause = {init,
81f996e37e7f 8153637: MethodHandles.countedLoop/3 initialises loop counter to 1 instead of 0
mhaupt
parents: 36935
diff changeset
  4499
     *                       filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v)
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4500
     *     return loop(indexVar, loopLimit, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4501
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4502
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4503
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4504
     * @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
  4505
     *              If it is {@code null}, a constant zero is assumed.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4506
     * @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
  4507
     * @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
  4508
     *             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
  4509
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4510
     * @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
  4511
     *             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
  4512
     *             additional loop-local variable plus loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4513
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4514
     * @return a method handle representing the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4515
     * @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
  4516
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4517
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4518
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4519
    public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
37604
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4520
        Class<?> resultType;
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4521
        MethodHandle actualInit;
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4522
        if (init == null) {
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4523
            resultType = body == null ? void.class : body.type().returnType();
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4524
            actualInit = empty(methodType(resultType));
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4525
        } else {
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4526
            resultType = init.type().returnType();
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4527
            actualInit = init;
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4528
        }
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4529
        MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType);
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4530
        MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body;
37603
e802285989a7 8154751: MethodHandles.countedLoop does not accept empty bodies
mhaupt
parents: 37602
diff changeset
  4531
        MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class);
37604
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4532
        MethodHandle actualEnd = end == null ? constant(int.class, 0) : end;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4533
        MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)};
37604
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4534
        MethodHandle[] loopLimit = {actualEnd, null,
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4535
                MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar};
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4536
        MethodHandle[] bodyClause = {actualInit,
60ad9582da0c 8154754: MethodHandles.countedLoop errors in deriving loop arguments, result type, and local state
mhaupt
parents: 37603
diff changeset
  4537
                filterArgument(dropArguments(actualBody, 1, int.class), 0,
37340
81f996e37e7f 8153637: MethodHandles.countedLoop/3 initialises loop counter to 1 instead of 0
mhaupt
parents: 36935
diff changeset
  4538
                        MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))};
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4539
        return loop(indexVar, loopLimit, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4540
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4541
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4542
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4543
     * 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
  4544
     * The iterator will be produced by the evaluation of the {@code iterator} handle.
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4545
     * This handle must have {@link java.util.Iterator} as its return type.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4546
     * 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
  4547
     * 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
  4548
     * 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
  4549
     * 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
  4550
     * obtained by running {@code init}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4551
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4552
     * This is a convenience wrapper for the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4553
     * {@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
  4554
     * handle follow directly from those described for the latter.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4555
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4556
     * 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
  4557
     * 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
  4558
     * 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
  4559
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4560
     * Iterator<T> iterator(A);  // defaults to Iterable::iterator
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4561
     * V init(A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4562
     * V body(T,V,A);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4563
     * V iteratedLoop(A a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4564
     *   Iterator<T> it = iterator(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4565
     *   V v = init(a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4566
     *   for (T t : it) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4567
     *     v = body(t, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4568
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4569
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4570
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4571
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4572
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4573
     * The type {@code T} may be either a primitive or reference.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4574
     * 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
  4575
     * {@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
  4576
     * 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
  4577
     * 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
  4578
     * 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
  4579
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4580
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4581
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4582
     * // reverse a list
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4583
     * static 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
  4584
     *   r.add(0, e);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4585
     *   return r;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4586
     * }
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4587
     * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4588
     * // assume MH_reverseStep, MH_newArrayList are handles to the above methods
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4589
     * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4590
     * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4591
     * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4592
     * assertEquals(reversedList, (List<String>) loop.invoke(list));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4593
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4594
     * <p>
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4595
     * @implSpec The implementation of this method is equivalent to (excluding error handling):
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4596
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4597
     * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4598
     *     // 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
  4599
     *     Class<?> itype = iterator.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4600
     *     Class<?> ttype = body.type().parameterType(0);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4601
     *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4602
     *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4603
     *     MethodHandle[]
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4604
     *         iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4605
     *         bodyClause = {init, filterArgument(body, 0, nextVal)};  // v = body(t, v, a);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4606
     *     return loop(iterVar, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4607
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4608
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4609
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4610
     * @param iterator a handle to return the iterator to start the loop.
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4611
     *             The handle must have {@link java.util.Iterator} as its return type.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4612
     *             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
  4613
     *             incoming value.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4614
     * @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
  4615
     *             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
  4616
     *             {@code void}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4617
     * @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
  4618
     *             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
  4619
     *             additional loop-local variable plus loop parameters.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4620
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4621
     * @return a method handle embodying the iteration loop functionality.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4622
     * @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
  4623
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4624
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4625
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4626
    public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4627
        checkIteratedLoop(iterator, body);
37602
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4628
        Class<?> resultType = init == null ?
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4629
                body == null ? void.class : body.type().returnType() :
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4630
                init.type().returnType();
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4631
        boolean voidResult = resultType == void.class;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4632
37602
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4633
        MethodHandle initIterator;
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4634
        if (iterator == null) {
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4635
            MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4636
            initIterator = initit.asType(initit.type().changeParameterType(0,
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4637
                    body.type().parameterType(voidResult ? 1 : 2)));
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4638
        } else {
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4639
            initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class));
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4640
        }
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4641
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4642
        Class<?> ttype = body.type().parameterType(0);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4643
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4644
        MethodHandle returnVar =
37602
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  4645
                dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4646
        MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4647
        MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4648
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4649
        MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred),
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4650
                returnVar};
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4651
        MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4652
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4653
        return loop(iterVar, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4654
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4655
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4656
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4657
     * 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
  4658
     * 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
  4659
     * 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
  4660
     * 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
  4661
     * 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
  4662
     * {@code try-finally} handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4663
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4664
     * 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
  4665
     * The first is the exception thrown during the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4666
     * 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
  4667
     * 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
  4668
     * 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
  4669
     * 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
  4670
     * (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
  4671
     * 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
  4672
     * <p>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4673
     * 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
  4674
     * 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
  4675
     * two extra leading parameters:<ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4676
     * <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
  4677
     * <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
  4678
     * the result from the execution of the {@code target} handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4679
     * 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
  4680
     * </ul>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4681
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4682
     * 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
  4683
     * 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
  4684
     * 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
  4685
     * the cleanup.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4686
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4687
     * V target(A..., B...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4688
     * V cleanup(Throwable, V, A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4689
     * V adapter(A... a, B... b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4690
     *   V result = (zero value for V);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4691
     *   Throwable throwable = null;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4692
     *   try {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4693
     *     result = target(a..., b...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4694
     *   } catch (Throwable t) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4695
     *     throwable = t;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4696
     *     throw t;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4697
     *   } finally {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4698
     *     result = cleanup(throwable, result, a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4699
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4700
     *   return result;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4701
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4702
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4703
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4704
     * Note that the saved arguments ({@code a...} in the pseudocode) cannot
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4705
     * 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
  4706
     * from the caller to the cleanup, if it is invoked.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4707
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4708
     * 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
  4709
     * always throws.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4710
     * To create such a throwing cleanup, compose the cleanup logic
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4711
     * with {@link #throwException throwException},
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4712
     * 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
  4713
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4714
     * Note that {@code tryFinally} never converts exceptions into normal returns.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4715
     * 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
  4716
     * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4717
     * to capture an outgoing exception, and then wrap with {@code tryFinally}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4718
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4719
     * @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
  4720
     * @param cleanup the handle that is invoked in the finally block.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4721
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4722
     * @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
  4723
     * @throws NullPointerException if any argument is null
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4724
     * @throws IllegalArgumentException if {@code cleanup} does not accept
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4725
     *          the required leading arguments, or if the method handle types do
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4726
     *          not match in their return types and their
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4727
     *          corresponding trailing parameters
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4728
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4729
     * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4730
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4731
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4732
    public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4733
        List<Class<?>> targetParamTypes = target.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4734
        List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4735
        Class<?> rtype = target.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4736
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4737
        checkTryFinally(target, cleanup);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4738
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4739
        // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4740
        // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4741
        // target parameter list.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4742
        cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4743
        MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount());
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4744
        MethodHandle aCleanup = cleanup.asSpreader(Object[].class, targetParamTypes.size());
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4745
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4746
        return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4747
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4748
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4749
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4750
     * 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
  4751
     * 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
  4752
     * before the folded arguments.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4753
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4754
     * 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
  4755
     * 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
  4756
     * 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
  4757
     * 0.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4758
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4759
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4760
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4761
    import static java.lang.invoke.MethodHandles.*;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4762
    import static java.lang.invoke.MethodType.*;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4763
    ...
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4764
    MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4765
    "println", methodType(void.class, String.class))
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4766
    .bindTo(System.out);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4767
    MethodHandle cat = lookup().findVirtual(String.class,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4768
    "concat", methodType(String.class, String.class));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4769
    assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4770
    MethodHandle catTrace = foldArguments(cat, 1, trace);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4771
    // also prints "jum":
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4772
    assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4773
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4774
     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4775
     * represents the result type of the {@code target} and resulting adapter.
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4776
     * {@code V}/{@code v} represent the type and value of the parameter and argument
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4777
     * of {@code target} that precedes the folding position; {@code V} also is
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4778
     * the result type of the {@code combiner}. {@code A}/{@code a} denote the
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4779
     * types and values of the {@code N} parameters and arguments at the folding
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4780
     * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4781
     * and values of the {@code target} parameters and arguments that precede and
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4782
     * follow the folded parameters and arguments starting at {@code pos},
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4783
     * respectively.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4784
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4785
     * // there are N arguments in A...
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4786
     * T target(Z..., V, A[N]..., B...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4787
     * V combiner(A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4788
     * T adapter(Z... z, A... a, B... b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4789
     *   V v = combiner(a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4790
     *   return target(z..., v, a..., b...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4791
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4792
     * // and if the combiner has a void return:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4793
     * T target2(Z..., A[N]..., B...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4794
     * void combiner2(A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4795
     * T adapter2(Z... z, A... a, B... b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4796
     *   combiner2(a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4797
     *   return target2(z..., a..., b...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4798
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4799
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4800
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4801
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4802
     * 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
  4803
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4804
     * @param target the method handle to invoke after arguments are combined
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4805
     * @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
  4806
     *            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
  4807
     * @param combiner method handle to call initially on the incoming arguments
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4808
     * @return method handle which incorporates the specified argument folding logic
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4809
     * @throws NullPointerException if either argument is null
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4810
     * @throws IllegalArgumentException if {@code combiner}'s return type
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4811
     *          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
  4812
     *          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
  4813
     *          of the target signature
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4814
     *          (skipping one matching the {@code combiner}'s return type)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4815
     *          are not identical with the argument types of {@code combiner}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4816
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4817
     * @see #foldArguments(MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4818
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4819
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4820
    public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4821
        MethodType targetType = target.type();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4822
        MethodType combinerType = combiner.type();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4823
        Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4824
        BoundMethodHandle result = target.rebind();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4825
        boolean dropResult = rtype == void.class;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4826
        LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4827
        MethodType newType = targetType;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4828
        if (!dropResult) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4829
            newType = newType.dropParameterTypes(pos, pos + 1);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4830
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4831
        result = result.copyWithExtendL(newType, lform, combiner);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4832
        return result;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4833
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4834
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4835
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4836
    private static void checkLoop0(MethodHandle[][] clauses) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4837
        if (clauses == null || clauses.length == 0) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4838
            throw newIllegalArgumentException("null or no clauses passed");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4839
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4840
        if (Stream.of(clauses).anyMatch(Objects::isNull)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4841
            throw newIllegalArgumentException("null clauses are not allowed");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4842
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4843
        if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4844
            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
  4845
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4846
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4847
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4848
    private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4849
        if (in.type().returnType() != st.type().returnType()) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4850
            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
  4851
                    st.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4852
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4853
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4854
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4855
    private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4856
        final List<Class<?>> empty = List.of();
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4857
        final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList());
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4858
        if (nonNullInits.isEmpty()) {
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4859
            final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4860
                    // take only those that can contribute to a common suffix because they are longer than the prefix
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4861
                    map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList).
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4862
                    reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4863
            return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size());
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4864
        } else {
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4865
            return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList).
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4866
                    reduce((p, q) -> p.size() >= q.size() ? p : q).get();
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4867
        }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4868
    }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4869
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4870
    private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4871
        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
  4872
                anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4873
            throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4874
                    " (common suffix: " + commonSuffix + ")");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4875
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4876
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4877
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4878
    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
  4879
        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
  4880
                anyMatch(t -> t != loopReturnType)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4881
            throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4882
                    loopReturnType + ")");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4883
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4884
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4885
        if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4886
            throw newIllegalArgumentException("no predicate found", pred);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4887
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4888
        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
  4889
                anyMatch(t -> t != boolean.class)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4890
            throw newIllegalArgumentException("predicates must have boolean return type", pred);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4891
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4892
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4893
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4894
    private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4895
        final int cpSize = commonParameterSequence.size();
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4896
        if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4897
                map(MethodType::parameterList).
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4898
                anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4899
            throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4900
                    "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4901
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4902
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4903
37539
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4904
    private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) {
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4905
        if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) {
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4906
            throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
fc220bc54b59 8150956: j.l.i.MethodHandles.whileLoop(...) and .iteratedLoop(...) throw unexpected exceptions in the case of 'init' return type is void
mhaupt
parents: 37363
diff changeset
  4907
        }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4908
        if (null == body) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4909
            throw newIllegalArgumentException("iterated loop body must not be null");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4910
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4911
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4912
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4913
    private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4914
        Class<?> rtype = target.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4915
        if (rtype != cleanup.type().returnType()) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4916
            throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4917
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4918
        List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4919
        if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4920
            throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4921
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4922
        if (rtype != void.class && cleanupParamTypes.get(1) != rtype) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4923
            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
  4924
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4925
        // 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
  4926
        // target parameter list.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4927
        int cleanupArgIndex = rtype == void.class ? 1 : 2;
36136
564116a434fa 8150825: MethodHandles.tryFinally throws IndexOutOfBoundsException for non-conforming parameter lists
mhaupt
parents: 36114
diff changeset
  4928
        List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size());
564116a434fa 8150825: MethodHandles.tryFinally throws IndexOutOfBoundsException for non-conforming parameter lists
mhaupt
parents: 36114
diff changeset
  4929
        List<Class<?>> targetParamTypes = target.type().parameterList();
564116a434fa 8150825: MethodHandles.tryFinally throws IndexOutOfBoundsException for non-conforming parameter lists
mhaupt
parents: 36114
diff changeset
  4930
        if (targetParamTypes.size() < cleanupArgSuffix.size() ||
564116a434fa 8150825: MethodHandles.tryFinally throws IndexOutOfBoundsException for non-conforming parameter lists
mhaupt
parents: 36114
diff changeset
  4931
                !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4932
            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
  4933
                    cleanup.type(), target.type());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4934
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4935
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4936
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4937
}