src/java.base/share/classes/java/lang/invoke/MethodHandles.java
author psandoz
Fri, 08 Sep 2017 10:46:46 -0700
changeset 48826 c4d9d1b08e2e
parent 48544 050352ed64d5
child 49432 f76e1ac74f28
permissions -rw-r--r--
8186209: Tool support for ConstantDynamic 8186046: Minimal ConstantDynamic support 8190972: Ensure that AOT/Graal filters out class files containing CONSTANT_Dynamic ahead of full AOT support Reviewed-by: acorn, coleenp, kvn Contributed-by: lois.foltan@oracle.com, john.r.rose@oracle.com, paul.sandoz@oracle.com
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
/*
43219
566b551b7820 8160710: Enable Thread to grant VarHandle field access to ThreadLocalRandom/Striped64
psandoz
parents: 42703
diff changeset
     2
 * Copyright (c) 2008, 2017, 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
44359
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
    28
import jdk.internal.misc.SharedSecrets;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
    29
import jdk.internal.module.IllegalAccessLogger;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
    30
import jdk.internal.org.objectweb.asm.ClassReader;
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    31
import jdk.internal.reflect.CallerSensitive;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    32
import jdk.internal.reflect.Reflection;
40175
8df87018d96a 8161379: Force inline methods calling Reflection.getCallerClass
redestad
parents: 39756
diff changeset
    33
import jdk.internal.vm.annotation.ForceInline;
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    34
import sun.invoke.util.ValueConversions;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    35
import sun.invoke.util.VerifyAccess;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    36
import sun.invoke.util.Wrapper;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    37
import sun.reflect.misc.ReflectUtil;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    38
import sun.security.util.SecurityConstants;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    39
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    40
import java.lang.invoke.LambdaForm.BasicType;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    41
import java.lang.reflect.Constructor;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    42
import java.lang.reflect.Field;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    43
import java.lang.reflect.Member;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    44
import java.lang.reflect.Method;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    45
import java.lang.reflect.Modifier;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    46
import java.lang.reflect.ReflectPermission;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    47
import java.nio.ByteOrder;
44359
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
    48
import java.security.AccessController;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
    49
import java.security.PrivilegedAction;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
    50
import java.security.ProtectionDomain;
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    51
import java.util.ArrayList;
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    52
import java.util.Arrays;
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    53
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
    54
import java.util.Iterator;
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    55
import java.util.List;
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
    56
import java.util.Objects;
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
    57
import java.util.concurrent.ConcurrentHashMap;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    58
import java.util.stream.Collectors;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
    59
import java.util.stream.Stream;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    60
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    61
import static java.lang.invoke.MethodHandleImpl.Intrinsic;
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
    62
import static java.lang.invoke.MethodHandleNatives.Constants.*;
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
    63
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
    64
import static java.lang.invoke.MethodType.methodType;
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
    65
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    66
/**
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    67
 * 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
    68
 * method handles. They fall into several categories:
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
    69
 * <ul>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
    70
 * <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
    71
 * <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
    72
 * <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
    73
 * </ul>
24367
705490680527 8030709: Tidy warnings cleanup for java.lang package; minor cleanup in java.math, javax.script
yan
parents: 23898
diff changeset
    74
 *
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    75
 * @author John Rose, JSR 292 EG
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
    76
 * @since 1.7
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    77
 */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    78
public class MethodHandles {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    79
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    80
    private MethodHandles() { }  // do not instantiate
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    81
40272
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
    82
    static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
34720
c2192aa0ab88 8144723: MethodHandleImpl.initStatics is no longer needed
redestad
parents: 34430
diff changeset
    83
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    84
    // See IMPL_LOOKUP below.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    85
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    86
    //// Method handle creation from ordinary methods.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
    87
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    88
    /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    89
     * Returns a {@link Lookup lookup object} with
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    90
     * 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
    91
     * 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
    92
     * Factory methods on the lookup object can create
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    93
     * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    94
     * 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
    95
     * including protected and private fields and methods.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
    96
     * 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
    97
     * 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
    98
     * <p>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
    99
     * 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
   100
     * values to different callers.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   101
     * @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
   102
     */
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   103
    @CallerSensitive
40175
8df87018d96a 8161379: Force inline methods calling Reflection.getCallerClass
redestad
parents: 39756
diff changeset
   104
    @ForceInline // to ensure Reflection.getCallerClass optimization
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   105
    public static Lookup lookup() {
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   106
        return new Lookup(Reflection.getCallerClass());
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   107
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   108
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   109
    /**
45027
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   110
     * This reflected$lookup method is the alternate implementation of
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   111
     * the lookup method when being invoked by reflection.
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   112
     */
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   113
    @CallerSensitive
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   114
    private static Lookup reflected$lookup() {
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   115
        Class<?> caller = Reflection.getCallerClass();
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   116
        if (caller.getClassLoader() == null) {
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   117
            throw newIllegalArgumentException("illegal lookupClass: "+caller);
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   118
        }
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   119
        return new Lookup(caller);
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   120
    }
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   121
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   122
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   123
     * Returns a {@link Lookup lookup object} which is trusted minimally.
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   124
     * The lookup has the {@code PUBLIC} and {@code UNCONDITIONAL} modes.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   125
     * It can only be used to create method handles to public members of
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   126
     * public classes in packages that are exported unconditionally.
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   127
     * <p>
47004
b7e72fc752c9 8186684: Fix broken links in java.base API docs
jjg
parents: 46148
diff changeset
   128
     * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   129
     * of this lookup object will be {@link java.lang.Object}.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   130
     *
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   131
     * @apiNote The use of Object is conventional, and because the lookup modes are
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   132
     * limited, there is no special access provided to the internals of Object, its package
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   133
     * or its module. Consequently, the lookup context of this lookup object will be the
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   134
     * bootstrap 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
   135
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   136
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   137
     * <em>Discussion:</em>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   138
     * 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
   139
     * {@link Lookup#in publicLookup().in(C.class)}.
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   140
     * 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
   141
     * 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
   142
     * <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
   143
     * Also, it cannot access
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   144
     * <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
   145
     * @return a lookup object which is trusted minimally
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   146
     *
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   147
     * @revised 9
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   148
     * @spec JPMS
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   149
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   150
    public static Lookup publicLookup() {
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   151
        return Lookup.PUBLIC_LOOKUP;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   152
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   153
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   154
    /**
42338
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   155
     * Returns a {@link Lookup lookup object} with full capabilities to emulate all
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   156
     * supported bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   157
     * private access</a>, on a target class.
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   158
     * This method checks that a caller, specified as a {@code Lookup} object, is allowed to
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   159
     * do <em>deep reflection</em> on the target class. If {@code m1} is the module containing
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   160
     * the {@link Lookup#lookupClass() lookup class}, and {@code m2} is the module containing
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   161
     * the target class, then this check ensures that
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   162
     * <ul>
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   163
     *     <li>{@code m1} {@link Module#canRead reads} {@code m2}.</li>
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   164
     *     <li>{@code m2} {@link Module#isOpen(String,Module) opens} the package containing
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   165
     *     the target class to at least {@code m1}.</li>
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   166
     *     <li>The lookup has the {@link Lookup#MODULE MODULE} lookup mode.</li>
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   167
     * </ul>
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   168
     * <p>
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   169
     * If there is a security manager, its {@code checkPermission} method is called to
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   170
     * check {@code ReflectPermission("suppressAccessChecks")}.
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   171
     * @apiNote The {@code MODULE} lookup mode serves to authenticate that the lookup object
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   172
     * was created by code in the caller module (or derived from a lookup object originally
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   173
     * created by the caller). A lookup object with the {@code MODULE} lookup mode can be
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   174
     * shared with trusted parties without giving away {@code PRIVATE} and {@code PACKAGE}
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   175
     * access to the caller.
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   176
     * @param targetClass the target class
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   177
     * @param lookup the caller lookup object
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   178
     * @return a lookup object for the target class, with private access
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   179
     * @throws IllegalArgumentException if {@code targetClass} is a primitve type or array class
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   180
     * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   181
     * @throws IllegalAccessException if the access check specified above fails
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   182
     * @throws SecurityException if denied by the security manager
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   183
     * @since 9
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   184
     * @spec JPMS
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   185
     * @see Lookup#dropLookupMode
42338
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   186
     */
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   187
    public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   188
        SecurityManager sm = System.getSecurityManager();
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   189
        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   190
        if (targetClass.isPrimitive())
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   191
            throw new IllegalArgumentException(targetClass + " is a primitive class");
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   192
        if (targetClass.isArray())
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   193
            throw new IllegalArgumentException(targetClass + " is an array class");
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   194
        Module targetModule = targetClass.getModule();
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   195
        Module callerModule = lookup.lookupClass().getModule();
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   196
        if (!callerModule.canRead(targetModule))
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   197
            throw new IllegalAccessException(callerModule + " does not read " + targetModule);
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   198
        if (targetModule.isNamed()) {
42338
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   199
            String pn = targetClass.getPackageName();
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   200
            assert pn.length() > 0 : "unnamed package cannot be in named module";
42338
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   201
            if (!targetModule.isOpen(pn, callerModule))
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   202
                throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   203
        }
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   204
        if ((lookup.lookupModes() & Lookup.MODULE) == 0)
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   205
            throw new IllegalAccessException("lookup does not have MODULE lookup mode");
44359
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   206
        if (!callerModule.isNamed() && targetModule.isNamed()) {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   207
            IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   208
            if (logger != null) {
45652
33342314ce89 8181087: Module system implementation refresh (6/2017)
alanb
parents: 45140
diff changeset
   209
                logger.logIfOpenedForIllegalAccess(lookup, targetClass);
44359
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   210
            }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   211
        }
42338
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   212
        return new Lookup(targetClass);
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   213
    }
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   214
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
   215
    /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   216
     * Performs an unchecked "crack" of a
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   217
     * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   218
     * The result is as if the user had obtained a lookup object capable enough
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   219
     * to crack the target method handle, called
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   220
     * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   221
     * on the target to obtain its symbolic reference, and then called
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   222
     * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   223
     * to resolve the symbolic reference to a member.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   224
     * <p>
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   225
     * If there is a security manager, its {@code checkPermission} method
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   226
     * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   227
     * @param <T> the desired type of the result, either {@link Member} or a subtype
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   228
     * @param target a direct method handle to crack into symbolic reference components
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   229
     * @param expected a class object representing the desired result type {@code T}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   230
     * @return a reference to the method, constructor, or field object
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   231
     * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   232
     * @exception NullPointerException if either argument is {@code null}
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   233
     * @exception IllegalArgumentException if the target is not a direct method handle
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   234
     * @exception ClassCastException if the member is not of the expected type
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   235
     * @since 1.8
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   236
     */
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   237
    public static <T extends Member> T
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   238
    reflectAs(Class<T> expected, MethodHandle target) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   239
        SecurityManager smgr = System.getSecurityManager();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   240
        if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   241
        Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   242
        return lookup.revealDirect(target).reflectAs(expected, lookup);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   243
    }
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   244
    // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
   245
    private static final java.security.Permission ACCESS_PERMISSION =
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   246
        new ReflectPermission("suppressAccessChecks");
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   247
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
   248
    /**
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   249
     * 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
   250
     * when the creation requires access checking.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   251
     * Method handles do not perform
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   252
     * 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
   253
     * Therefore, method handle access
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   254
     * 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
   255
     * The caller class against which those restrictions are enforced
47004
b7e72fc752c9 8186684: Fix broken links in java.base API docs
jjg
parents: 46148
diff changeset
   256
     * is known as the {@linkplain #lookupClass() lookup class}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   257
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   258
     * A lookup class which needs to create method handles will call
47004
b7e72fc752c9 8186684: Fix broken links in java.base API docs
jjg
parents: 46148
diff changeset
   259
     * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   260
     * 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
   261
     * determined, and securely stored in the {@code Lookup} object.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   262
     * 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
   263
     * 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
   264
     * 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
   265
     * even private ones.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   266
     *
44844
b2b4d98404ba 8179364: update "<a name=" in java.base module to use id attribute
jjg
parents: 44545
diff changeset
   267
     * <h1><a id="lookups"></a>Lookup Factory Methods</h1>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   268
     * 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
   269
     * use cases for methods, constructors, and fields.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   270
     * 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
   271
     * equivalent of a particular <em>bytecode behavior</em>.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   272
     * (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
   273
     * 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
   274
     * the behavior of the resulting method handles:
45124
144479e89cdb 8179592: Update tables in java.base to be HTML 5-friendly.
jjg
parents: 45027
diff changeset
   275
     * <table class="striped">
144479e89cdb 8179592: Update tables in java.base to be HTML 5-friendly.
jjg
parents: 45027
diff changeset
   276
     * <caption style="display:none">lookup method behaviors</caption>
144479e89cdb 8179592: Update tables in java.base to be HTML 5-friendly.
jjg
parents: 45027
diff changeset
   277
     * <thead>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   278
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   279
     *     <th scope="col"><a id="equiv"></a>lookup expression</th>
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   280
     *     <th scope="col">member</th>
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   281
     *     <th scope="col">bytecode behavior</th>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   282
     * </tr>
45124
144479e89cdb 8179592: Update tables in java.base to be HTML 5-friendly.
jjg
parents: 45027
diff changeset
   283
     * </thead>
144479e89cdb 8179592: Update tables in java.base to be HTML 5-friendly.
jjg
parents: 45027
diff changeset
   284
     * <tbody>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   285
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   286
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   287
     *     <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
   288
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   289
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   290
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   291
     *     <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
   292
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   293
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   294
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   295
     *     <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
   296
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   297
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   298
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   299
     *     <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
   300
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   301
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   302
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   303
     *     <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
   304
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   305
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   306
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   307
     *     <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
   308
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   309
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   310
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   311
     *     <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
   312
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   313
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   314
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   315
     *     <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
   316
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   317
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   318
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   319
     *     <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
   320
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   321
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   322
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   323
     *     <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
   324
     * </tr>
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   325
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   326
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   327
     *     <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
   328
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   329
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   330
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   331
     *     <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
   332
     * </tr>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   333
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   334
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   335
     *     <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
   336
     * </tr>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   337
     * <tr>
45881
aaec0fbe17ae 8184208: update class="striped" tables for accessibility
jjg
parents: 45705
diff changeset
   338
     *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   339
     *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   340
     * </tr>
45124
144479e89cdb 8179592: Update tables in java.base to be HTML 5-friendly.
jjg
parents: 45027
diff changeset
   341
     * </tbody>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   342
     * </table>
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   343
     *
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   344
     * 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
   345
     * 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
   346
     * 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
   347
     * and the sequence of argument types {@code A*}.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   348
     * 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
   349
     * 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
   350
     * 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
   351
     * 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
   352
     * 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
   353
     * (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
   354
     * 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
   355
     * 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
   356
     * 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
   357
     * 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
   358
     * and {@code this} otherwise.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   359
     * 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
   360
     * for reflective objects corresponding to the given members.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   361
     * <p>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   362
     * 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
   363
     * as if by {@code ldc CONSTANT_Class}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   364
     * 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
   365
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
   366
     * 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
   367
     * 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
   368
     * 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
   369
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   370
     * <em>Discussion:</em>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   371
     * 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
   372
     * class members and bytecode behaviors
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   373
     * can break down in a few ways:
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   374
     * <ul style="font-size:smaller;">
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   375
     * <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
   376
     * 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
   377
     * Java expression or bytecoded constant.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   378
     * <li>Likewise, if {@code T} or {@code MT}
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   379
     * 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
   380
     * the lookup can still succeed.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   381
     * 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
   382
     * {@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
   383
     * <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
   384
     * 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
   385
     * 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
   386
     * 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
   387
     * <li>If the looked-up method has a
b49b07206f7d 8019417: JSR 292 javadoc should clarify method handle arity limits
jrose
parents: 20528
diff changeset
   388
     * <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
   389
     * 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
   390
     * type having too many parameters.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   391
     * </ul>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   392
     *
44844
b2b4d98404ba 8179364: update "<a name=" in java.base module to use id attribute
jjg
parents: 44545
diff changeset
   393
     * <h1><a id="access"></a>Access checking</h1>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   394
     * 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
   395
     * when a method handle is created.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   396
     * 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
   397
     * {@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
   398
     * performs access checking against every caller, on every call.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   399
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   400
     * 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
   401
     * compares its recorded lookup class against all requests to
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   402
     * create method handles.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   403
     * 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
   404
     * 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
   405
     * lookup class.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   406
     * <p>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   407
     * 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
   408
     * such as a metaobject protocol.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   409
     * A shared {@code Lookup} object delegates the capability
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   410
     * 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
   411
     * Even if privileged code uses the {@code Lookup} object,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   412
     * 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
   413
     * original lookup class.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   414
     * <p>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   415
     * A lookup can fail, because
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   416
     * 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
   417
     * 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
   418
     * 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
   419
     * 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
   420
     * 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
   421
     * 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
   422
     * the following:
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   423
     * <ul>
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
   424
     * <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
   425
     * <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
   426
     * <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
   427
     * </ul>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   428
     * <p>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   429
     * 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
   430
     * 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
   431
     * 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
   432
     * 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
   433
     * 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
   434
     * checked exception, such as {@code NoSuchMethodException}.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   435
     * 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
   436
     * 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
   437
     * 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
   438
     * 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
   439
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   440
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   441
     * Access checks only apply to named and reflected methods,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   442
     * constructors, and fields.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   443
     * Other method handle creation methods, such as
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   444
     * {@link MethodHandle#asType MethodHandle.asType},
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   445
     * do not require any access checks, and are used
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   446
     * independently of any {@code Lookup} object.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   447
     * <p>
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   448
     * 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
   449
     * 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
   450
     * 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
   451
     * (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
   452
     * 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
   453
     * 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
   454
     * 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
   455
     * 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
   456
     * {@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
   457
     * (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
   458
     * to the lookup class itself.
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
   459
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   460
     * 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
   461
     * 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
   462
     * 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
   463
     * 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
   464
     * (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
   465
     * <p>
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
   466
     * 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
   467
     * 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
   468
     * 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
   469
     * 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
   470
     * 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
   471
     * <p>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   472
     * 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
   473
     * 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
   474
     * in the same top-level declaration.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   475
     * For example, a nested class {@code C.D}
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   476
     * 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
   477
     * {@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
   478
     * 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
   479
     * 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
   480
     * {@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
   481
     * 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
   482
     * 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
   483
     * classes, without special elevation of privilege.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   484
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   485
     * 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
   486
     * according to its set of {@link #lookupModes lookupModes},
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   487
     * 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
   488
     * For example, the {@link MethodHandles#publicLookup publicLookup}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   489
     * method produces a lookup object which is only allowed to access
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   490
     * public members in public classes of exported packages.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   491
     * The caller sensitive method {@link MethodHandles#lookup lookup}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   492
     * produces a lookup object with full capabilities relative to
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   493
     * its caller class, to emulate all supported bytecode behaviors.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   494
     * 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
   495
     * with fewer access modes than the original lookup object.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   496
     *
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   497
     * <p style="font-size:smaller;">
44844
b2b4d98404ba 8179364: update "<a name=" in java.base module to use id attribute
jjg
parents: 44545
diff changeset
   498
     * <a id="privacc"></a>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   499
     * <em>Discussion of private access:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   500
     * 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
   501
     * if its {@linkplain #lookupModes lookup modes}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   502
     * include the possibility of accessing {@code private} members.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   503
     * As documented in the relevant methods elsewhere,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   504
     * only lookups with private access possess the following capabilities:
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   505
     * <ul style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   506
     * <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
   507
     * <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
   508
     *     such as {@code Class.forName}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   509
     * <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
   510
     * <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
   511
     *     for classes accessible to the lookup class
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   512
     * <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
   513
     *     within the same package member
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   514
     * </ul>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   515
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   516
     * 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
   517
     * 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
   518
     * 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
   519
     * can be reliably determined and emulated by method handles.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   520
     *
44844
b2b4d98404ba 8179364: update "<a name=" in java.base module to use id attribute
jjg
parents: 44545
diff changeset
   521
     * <h1><a id="secmgr"></a>Security manager interactions</h1>
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   522
     * Although bytecode instructions can only refer to classes in
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   523
     * 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
   524
     * 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
   525
     * 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
   526
     * Core Reflection API, and are impossible to bytecode instructions
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   527
     * such as {@code invokestatic} or {@code getfield}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   528
     * 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
   529
     * to allow applications to check such cross-loader references.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   530
     * 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
   531
     * and the Core Reflection API
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   532
     * (as found on {@link java.lang.Class Class}).
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   533
     * <p>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   534
     * 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
   535
     * additional checks.
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   536
     * 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
   537
     * 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
   538
     * {@link java.lang.SecurityException SecurityException}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   539
     * Define {@code smgr} as the security manager,
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   540
     * {@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
   541
     * {@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
   542
     * 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
   543
     * member is actually defined.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   544
     * (If a class or other type is being accessed,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   545
     * 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
   546
     * 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
   547
     * if the current lookup object does not have
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   548
     * <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
   549
     * The calls are made according to the following rules:
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   550
     * <ul>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   551
     * <li><b>Step 1:</b>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   552
     *     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
   553
     *     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
   554
     *     then {@link SecurityManager#checkPackageAccess
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   555
     *     smgr.checkPackageAccess(refcPkg)} is called,
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   556
     *     where {@code refcPkg} is the package of {@code refc}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   557
     * <li><b>Step 2a:</b>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   558
     *     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
   559
     *     {@code lookc} is not present, then
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   560
     *     {@link SecurityManager#checkPermission smgr.checkPermission}
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   561
     *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   562
     * <li><b>Step 2b:</b>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   563
     *     If the retrieved class has a {@code null} class loader,
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   564
     *     and {@code lookc} is not present, then
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   565
     *     {@link SecurityManager#checkPermission smgr.checkPermission}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   566
     *     with {@code RuntimePermission("getClassLoader")} is called.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   567
     * <li><b>Step 3:</b>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   568
     *     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
   569
     *     and if {@code lookc} is not present,
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
   570
     *     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
   571
     *     then {@link SecurityManager#checkPackageAccess
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   572
     *     smgr.checkPackageAccess(defcPkg)} is called,
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   573
     *     where {@code defcPkg} is the package of {@code defc}.
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
   574
     * </ul>
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   575
     * Security checks are performed after other access checks have passed.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
   576
     * 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
   577
     * 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
   578
     * 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
   579
     *
44844
b2b4d98404ba 8179364: update "<a name=" in java.base module to use id attribute
jjg
parents: 44545
diff changeset
   580
     * <h1><a id="callsens"></a>Caller sensitive methods</h1>
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   581
     * 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
   582
     * 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
   583
     * identity of its immediate caller.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   584
     * <p>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   585
     * 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
   586
     * 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
   587
     * 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
   588
     * 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
   589
     * 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
   590
     * 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
   591
     * (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
   592
     * 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
   593
     * different lookup classes may give rise to
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   594
     * differently behaving method handles.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   595
     * <p>
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   596
     * In cases where the lookup object is
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   597
     * {@link MethodHandles#publicLookup() publicLookup()},
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   598
     * or some other lookup object without
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   599
     * <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
   600
     * the lookup class is disregarded.
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
   601
     * 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
   602
     * 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
   603
     * {@code IllegalAccessException}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   604
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   605
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   606
     * For example, the caller-sensitive method
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   607
     * {@link java.lang.Class#forName(String) Class.forName(x)}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   608
     * can return varying classes or throw varying exceptions,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   609
     * 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
   610
     * 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
   611
     * 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
   612
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   613
     * If an application caches method handles for broad sharing,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   614
     * it should use {@code publicLookup()} to create them.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   615
     * 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
   616
     * 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
   617
     * 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
   618
     * bootstrap method, can incorporate the specific identity
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   619
     * of the caller, making the method accessible.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   620
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   621
     * The function {@code MethodHandles.lookup} is caller sensitive
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
   622
     * 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
   623
     * 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
   624
     * objects to check access requests.
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   625
     *
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   626
     * @revised 9
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   627
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   628
    public static final
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   629
    class Lookup {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   630
        /** 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
   631
        private final Class<?> lookupClass;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   632
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   633
        /** 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
   634
        private final int allowedModes;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   635
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   636
        /** A single-bit mask representing {@code public} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   637
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   638
         *  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
   639
         *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   640
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   641
        public static final int PUBLIC = Modifier.PUBLIC;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   642
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   643
        /** A single-bit mask representing {@code private} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   644
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   645
         *  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
   646
         *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   647
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   648
        public static final int PRIVATE = Modifier.PRIVATE;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   649
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   650
        /** A single-bit mask representing {@code protected} access,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   651
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   652
         *  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
   653
         *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   654
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   655
        public static final int PROTECTED = Modifier.PROTECTED;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   656
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   657
        /** A single-bit mask representing {@code package} access (default access),
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   658
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   659
         *  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
   660
         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   661
         */
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   662
        public static final int PACKAGE = Modifier.STATIC;
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   663
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   664
        /** A single-bit mask representing {@code module} access (default access),
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   665
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   666
         *  The value is {@code 0x10}, which does not correspond meaningfully to
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   667
         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   668
         *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   669
         *  with this lookup mode can access all public types in the module of the
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   670
         *  lookup class and public types in packages exported by other modules
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   671
         *  to the module of the lookup class.
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   672
         *  @since 9
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   673
         *  @spec JPMS
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   674
         */
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   675
        public static final int MODULE = PACKAGE << 1;
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   676
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   677
        /** A single-bit mask representing {@code unconditional} access
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   678
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   679
         *  The value is {@code 0x20}, which does not correspond meaningfully to
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   680
         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   681
         *  A {@code Lookup} with this lookup mode assumes {@linkplain
44545
83b611b88ac8 8177530: Module system implementation refresh (4/2017)
alanb
parents: 44359
diff changeset
   682
         *  java.lang.Module#canRead(java.lang.Module) readability}.
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   683
         *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   684
         *  with this lookup mode can access all public members of public types
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   685
         *  of all modules where the type is in a package that is {@link
44545
83b611b88ac8 8177530: Module system implementation refresh (4/2017)
alanb
parents: 44359
diff changeset
   686
         *  java.lang.Module#isExported(String) exported unconditionally}.
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   687
         *  @since 9
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   688
         *  @spec JPMS
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   689
         *  @see #publicLookup()
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   690
         */
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   691
        public static final int UNCONDITIONAL = PACKAGE << 2;
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   692
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   693
        private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL);
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   694
        private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   695
        private static final int TRUSTED   = -1;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   696
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   697
        private static int fixmods(int mods) {
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   698
            mods &= (ALL_MODES - PACKAGE - MODULE - UNCONDITIONAL);
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   699
            return (mods != 0) ? mods : (PACKAGE | MODULE | UNCONDITIONAL);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   700
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   701
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   702
        /** 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
   703
         *  which checks are performed for visibility and access permissions.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   704
         *  <p>
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   705
         *  The class implies a maximum level of access permission,
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   706
         *  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
   707
         *  {@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
   708
         *  can be accessed.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   709
         *  @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
   710
         */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   711
        public Class<?> lookupClass() {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   712
            return lookupClass;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   713
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   714
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   715
        // This is just for calling out to MethodHandleImpl.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   716
        private Class<?> lookupClassOrNull() {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   717
            return (allowedModes == TRUSTED) ? null : lookupClass;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   718
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   719
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   720
        /** 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
   721
         *  The result is a bit-mask of the bits
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   722
         *  {@linkplain #PUBLIC PUBLIC (0x01)},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   723
         *  {@linkplain #PRIVATE PRIVATE (0x02)},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
   724
         *  {@linkplain #PROTECTED PROTECTED (0x04)},
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   725
         *  {@linkplain #PACKAGE PACKAGE (0x08)},
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   726
         *  {@linkplain #MODULE MODULE (0x10)},
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   727
         *  and {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   728
         *  <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   729
         *  A freshly-created lookup object
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   730
         *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   731
         *  all possible bits set, except {@code UNCONDITIONAL}. The lookup can be used to
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   732
         *  access all members of the caller's class, all public types in the caller's module,
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   733
         *  and all public types in packages exported by other modules to the caller's module.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   734
         *  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
   735
         *  {@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
   736
         *  may have some mode bits set to zero.
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   737
         *  Mode bits can also be
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   738
         *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   739
         *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   740
         *  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
   741
         *  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
   742
         *  lookup object, and also by the new lookup class.
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
   743
         *  @return the lookup modes, which limit the kinds of access performed by this lookup object
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   744
         *  @see #in
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   745
         *  @see #dropLookupMode
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   746
         *
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   747
         *  @revised 9
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   748
         *  @spec JPMS
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   749
         */
7052
963a5baf2ba3 6980096: JSR 292 reflective lookup should throw checked exceptions
jrose
parents: 5727
diff changeset
   750
        public int lookupModes() {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   751
            return allowedModes & ALL_MODES;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   752
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   753
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   754
        /** 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
   755
         * for method handle creation.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   756
         * 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
   757
         * 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
   758
         */
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
   759
        Lookup(Class<?> lookupClass) {
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   760
            this(lookupClass, FULL_POWER_MODES);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   761
            // make sure we haven't accidentally picked up a privileged class:
45027
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   762
            checkUnprivilegedlookupClass(lookupClass);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   763
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   764
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   765
        private Lookup(Class<?> lookupClass, int allowedModes) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   766
            this.lookupClass = lookupClass;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   767
            this.allowedModes = allowedModes;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   768
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   769
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   770
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   771
         * Creates a lookup on the specified new lookup class.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   772
         * The resulting object will report the specified
47004
b7e72fc752c9 8186684: Fix broken links in java.base API docs
jjg
parents: 46148
diff changeset
   773
         * class as its own {@link #lookupClass() lookupClass}.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   774
         * <p>
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   775
         * However, the resulting {@code Lookup} object is guaranteed
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   776
         * 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
   777
         * In particular, access capabilities can be lost as follows:<ul>
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   778
         * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   779
         * the new lookup class is in a different module {@code M}, then no members, not
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   780
         * even public members in {@code M}'s exported packages, will be accessible.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   781
         * The exception to this is when this lookup is {@link #publicLookup()
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   782
         * publicLookup}, in which case {@code PUBLIC} access is not lost.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   783
         * <li>If the old lookup class is in an unnamed module, and the new lookup class
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   784
         * is a different module then {@link #MODULE MODULE} access is lost.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   785
         * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   786
         * <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
   787
         * 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
   788
         * <li>If the new lookup class is not within the same package member
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   789
         * as the old one, private members will not be accessible, and protected members
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   790
         * will not be accessible by virtue of inheritance.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   791
         * (Protected members may continue to be accessible because of package sharing.)
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   792
         * <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
   793
         * 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
   794
         * (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
   795
         * </ul>
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   796
         * <p>
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   797
         * The resulting lookup's capabilities for loading classes
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   798
         * (used during {@link #findClass} invocations)
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   799
         * are determined by the lookup class' loader,
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
   800
         * which may change due to this operation.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   801
         *
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   802
         * @param requestedLookupClass the desired lookup class for the new lookup object
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   803
         * @return a lookup object which reports the desired lookup class, or the same object
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   804
         * if there is no change
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
   805
         * @throws NullPointerException if the argument is null
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   806
         *
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   807
         * @revised 9
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   808
         * @spec JPMS
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   809
         */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   810
        public Lookup in(Class<?> requestedLookupClass) {
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
   811
            Objects.requireNonNull(requestedLookupClass);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   812
            if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   813
                return new Lookup(requestedLookupClass, FULL_POWER_MODES);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   814
            if (requestedLookupClass == this.lookupClass)
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   815
                return this;  // keep same capabilities
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   816
            int newModes = (allowedModes & FULL_POWER_MODES);
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   817
            if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   818
                // Need to drop all access when teleporting from a named module to another
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   819
                // module. The exception is publicLookup where PUBLIC is not lost.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   820
                if (this.lookupClass.getModule().isNamed()
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   821
                    && (this.allowedModes & UNCONDITIONAL) == 0)
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   822
                    newModes = 0;
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   823
                else
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   824
                    newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   825
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   826
            if ((newModes & PACKAGE) != 0
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   827
                && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   828
                newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   829
            }
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   830
            // Allow nestmate lookups to be created without special privilege:
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   831
            if ((newModes & PRIVATE) != 0
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   832
                && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   833
                newModes &= ~(PRIVATE|PROTECTED);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   834
            }
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
   835
            if ((newModes & PUBLIC) != 0
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
   836
                && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   837
                // 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
   838
                // No permissions.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   839
                newModes = 0;
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
   840
            }
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
   841
45027
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   842
            checkUnprivilegedlookupClass(requestedLookupClass);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   843
            return new Lookup(requestedLookupClass, newModes);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   844
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   845
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   846
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   847
        /**
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   848
         * Creates a lookup on the same lookup class which this lookup object
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   849
         * finds members, but with a lookup mode that has lost the given lookup mode.
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   850
         * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   851
         * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}.
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   852
         * {@link #PROTECTED PROTECTED} and {@link #UNCONDITIONAL UNCONDITIONAL} are always
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   853
         * dropped and so the resulting lookup mode will never have these access capabilities.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   854
         * When dropping {@code PACKAGE} then the resulting lookup will not have {@code PACKAGE}
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   855
         * or {@code PRIVATE} access. When dropping {@code MODULE} then the resulting lookup will
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   856
         * not have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code PUBLIC}
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   857
         * is dropped then the resulting lookup has no access.
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   858
         * @param modeToDrop the lookup mode to drop
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   859
         * @return a lookup object which lacks the indicated mode, or the same object if there is no change
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   860
         * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   861
         * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE} or {@code UNCONDITIONAL}
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   862
         * @see MethodHandles#privateLookupIn
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   863
         * @since 9
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   864
         */
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   865
        public Lookup dropLookupMode(int modeToDrop) {
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   866
            int oldModes = lookupModes();
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   867
            int newModes = oldModes & ~(modeToDrop | PROTECTED | UNCONDITIONAL);
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   868
            switch (modeToDrop) {
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   869
                case PUBLIC: newModes &= ~(ALL_MODES); break;
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   870
                case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   871
                case PACKAGE: newModes &= ~(PRIVATE); break;
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   872
                case PROTECTED:
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   873
                case PRIVATE:
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   874
                case UNCONDITIONAL: break;
42703
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   875
                default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   876
            }
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   877
            if (newModes == oldModes) return this;  // return self if no change
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   878
            return new Lookup(lookupClass(), newModes);
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   879
        }
20c39ea4a507 8170987: Module system implementation refresh (12/2016)
alanb
parents: 42338
diff changeset
   880
44359
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   881
        /**
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   882
         * Defines a class to the same class loader and in the same runtime package and
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   883
         * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   884
         * {@linkplain #lookupClass() lookup class}.
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   885
         *
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   886
         * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   887
         * {@link #PACKAGE PACKAGE} access as default (package) members will be
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   888
         * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   889
         * that the lookup object was created by a caller in the runtime package (or derived
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   890
         * from a lookup originally created by suitably privileged code to a target class in
45004
ea3137042a61 8178380: Module system implementation refresh (5/2017)
alanb
parents: 44545
diff changeset
   891
         * the runtime package). </p>
44359
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   892
         *
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   893
         * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   894
         * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   895
         * same package as the lookup class. </p>
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   896
         *
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   897
         * <p> This method does not run the class initializer. The class initializer may
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   898
         * run at a later time, as detailed in section 12.4 of the <em>The Java Language
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   899
         * Specification</em>. </p>
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   900
         *
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   901
         * <p> If there is a security manager, its {@code checkPermission} method is first called
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   902
         * to check {@code RuntimePermission("defineClass")}. </p>
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   903
         *
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   904
         * @param bytes the class bytes
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   905
         * @return the {@code Class} object for the class
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   906
         * @throws IllegalArgumentException the bytes are for a class in a different package
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   907
         * to the lookup class
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   908
         * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   909
         * @throws LinkageError if the class is malformed ({@code ClassFormatError}), cannot be
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   910
         * verified ({@code VerifyError}), is already defined, or another linkage error occurs
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   911
         * @throws SecurityException if denied by the security manager
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   912
         * @throws NullPointerException if {@code bytes} is {@code null}
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   913
         * @since 9
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   914
         * @spec JPMS
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   915
         * @see Lookup#privateLookupIn
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   916
         * @see Lookup#dropLookupMode
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   917
         * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   918
         */
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   919
        public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   920
            SecurityManager sm = System.getSecurityManager();
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   921
            if (sm != null)
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   922
                sm.checkPermission(new RuntimePermission("defineClass"));
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   923
            if ((lookupModes() & PACKAGE) == 0)
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   924
                throw new IllegalAccessException("Lookup does not have PACKAGE access");
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   925
            assert (lookupModes() & (MODULE|PUBLIC)) != 0;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   926
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   927
            // parse class bytes to get class name (in internal form)
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   928
            bytes = bytes.clone();
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   929
            String name;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   930
            try {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   931
                ClassReader reader = new ClassReader(bytes);
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   932
                name = reader.getClassName();
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   933
            } catch (RuntimeException e) {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   934
                // ASM exceptions are poorly specified
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   935
                ClassFormatError cfe = new ClassFormatError();
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   936
                cfe.initCause(e);
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   937
                throw cfe;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   938
            }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   939
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   940
            // get package and class name in binary form
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   941
            String cn, pn;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   942
            int index = name.lastIndexOf('/');
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   943
            if (index == -1) {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   944
                cn = name;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   945
                pn = "";
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   946
            } else {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   947
                cn = name.replace('/', '.');
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   948
                pn = cn.substring(0, index);
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   949
            }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   950
            if (!pn.equals(lookupClass.getPackageName())) {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   951
                throw new IllegalArgumentException("Class not in same package as lookup class");
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   952
            }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   953
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   954
            // invoke the class loader's defineClass method
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   955
            ClassLoader loader = lookupClass.getClassLoader();
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   956
            ProtectionDomain pd = (loader != null) ? lookupClassProtectionDomain() : null;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   957
            String source = "__Lookup_defineClass__";
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   958
            Class<?> clazz = SharedSecrets.getJavaLangAccess().defineClass(loader, cn, bytes, pd, source);
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   959
            assert clazz.getClassLoader() == lookupClass.getClassLoader()
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   960
                    && clazz.getPackageName().equals(lookupClass.getPackageName())
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   961
                    && protectionDomain(clazz) == lookupClassProtectionDomain();
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   962
            return clazz;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   963
        }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   964
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   965
        private ProtectionDomain lookupClassProtectionDomain() {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   966
            ProtectionDomain pd = cachedProtectionDomain;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   967
            if (pd == null) {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   968
                cachedProtectionDomain = pd = protectionDomain(lookupClass);
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   969
            }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   970
            return pd;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   971
        }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   972
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   973
        private ProtectionDomain protectionDomain(Class<?> clazz) {
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   974
            PrivilegedAction<ProtectionDomain> pa = clazz::getProtectionDomain;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   975
            return AccessController.doPrivileged(pa);
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   976
        }
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   977
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   978
        // cached protection domain
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   979
        private volatile ProtectionDomain cachedProtectionDomain;
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   980
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
   981
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   982
        // Make sure outer class is initialized first.
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
   983
        static { IMPL_NAMES.getClass(); }
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
   984
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   985
        /** Package-private version of lookup which is trusted. */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
   986
        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
   987
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   988
        /** Version of lookup which is trusted minimally.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   989
         *  It can only be used to create method handles to publicly accessible
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   990
         *  members in packages that are exported unconditionally.
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   991
         */
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   992
        static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, (PUBLIC|UNCONDITIONAL));
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
   993
45027
0cf367e546fb 8020801: Apply the restriction of invoking MethodHandles.lookup to j.l.r.Method.invoke
mchung
parents: 45005
diff changeset
   994
        private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2764
2e45af54c0f9 6839839: access checking logic is wrong at three points in MethodHandles
jrose
parents: 2763
diff changeset
   995
            String name = lookupClass.getName();
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
   996
            if (name.startsWith("java.lang.invoke."))
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   997
                throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   998
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
   999
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  1000
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1001
         * 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
  1002
         * (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
  1003
         * 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
  1004
         * 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
  1005
         * 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
  1006
         * allowed access, and is chosen as follows:
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  1007
         * <ul>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  1008
         * <li>If no access is allowed, the suffix is "/noaccess".
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1009
         * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1010
         * <li>If only public access and unconditional access are allowed, the suffix is "/publicLookup".
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1011
         * <li>If only public and module access are allowed, the suffix is "/module".
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1012
         * <li>If only public, module and package access are allowed, the suffix is "/package".
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1013
         * <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
  1014
         * </ul>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  1015
         * If none of the above cases apply, it is the case that full
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1016
         * access (public, module, package, private, and protected) is allowed.
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  1017
         * In this case, no suffix is added.
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  1018
         * 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
  1019
         * {@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
  1020
         * 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
  1021
         * 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
  1022
         * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1023
         * (It may seem strange that protected access should be
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1024
         * stronger than private access.  Viewed independently from
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1025
         * 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
  1026
         * because it requires a direct subclass relationship between
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1027
         * caller and callee.)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1028
         * @see #in
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1029
         *
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1030
         * @revised 9
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1031
         * @spec JPMS
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1032
         */
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1033
        @Override
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1034
        public String toString() {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1035
            String cname = lookupClass.getName();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1036
            switch (allowedModes) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1037
            case 0:  // no privileges
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1038
                return cname + "/noaccess";
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1039
            case PUBLIC:
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  1040
                return cname + "/public";
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1041
            case PUBLIC|UNCONDITIONAL:
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1042
                return cname  + "/publicLookup";
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1043
            case PUBLIC|MODULE:
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1044
                return cname + "/module";
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  1045
            case PUBLIC|MODULE|PACKAGE:
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1046
                return cname + "/package";
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1047
            case FULL_POWER_MODES & ~PROTECTED:
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1048
                return cname + "/private";
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1049
            case FULL_POWER_MODES:
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1050
                return cname;
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1051
            case TRUSTED:
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1052
                return "/trusted";  // internal only; not exported
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1053
            default:  // Should not happen, but it's a bitfield...
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1054
                cname = cname + "/" + Integer.toHexString(allowedModes);
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1055
                assert(false) : cname;
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1056
                return cname;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1057
            }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1058
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1059
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1060
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1061
         * Produces a method handle for a static method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1062
         * 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
  1063
         * (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
  1064
         * 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
  1065
         * 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
  1066
         * 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
  1067
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1068
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1069
         * {@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
  1070
         * 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
  1071
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1072
         * 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
  1073
         * 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
  1074
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  1075
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1076
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
  1077
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
  1078
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1079
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
  1080
  "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
  1081
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
  1082
         * }</pre></blockquote>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1083
         * @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
  1084
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1085
         * @param type the type of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1086
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1087
         * @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
  1088
         * @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
  1089
         *                                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
  1090
         *                                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
  1091
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1092
         * @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
  1093
         *                              <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
  1094
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1095
         */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1096
        public
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1097
        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
  1098
            MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1099
            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
  1100
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1101
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1102
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1103
         * Produces a method handle for a virtual method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1104
         * 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
  1105
         * with the receiver type (usually {@code refc}) prepended.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1106
         * 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
  1107
         * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1108
         * 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
  1109
         * 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
  1110
         * implementation to enter.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1111
         * (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
  1112
         * {@code invokevirtual} or {@code invokeinterface} instruction.)
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1113
         * <p>
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1114
         * 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
  1115
         * 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
  1116
         * 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
  1117
         * 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
  1118
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1119
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1120
         * {@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
  1121
         * 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
  1122
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1123
         * 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
  1124
         * instructions and method handles produced by {@code findVirtual},
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1125
         * 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
  1126
         * {@code invokeExact} or {@code invoke}, the resulting
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1127
         * 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
  1128
         * {@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
  1129
         * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1130
         * with the same {@code type} argument.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1131
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1132
         * If the class is {@code VarHandle} and the name string corresponds to
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1133
         * the name of a signature-polymorphic access mode method, the resulting
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1134
         * method handle is equivalent to one produced by
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1135
         * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1136
         * the access mode corresponding to the name string and with the same
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1137
         * {@code type} arguments.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1138
         * <p>
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1139
         * <b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  1140
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1141
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
  1142
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
  1143
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1144
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
  1145
  "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
  1146
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
  1147
  "hashCode", methodType(int.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1148
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
  1149
  "hashCode", methodType(int.class));
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1150
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
  1151
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
  1152
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
  1153
// interface method:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1154
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
  1155
  "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
  1156
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
  1157
// 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
  1158
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
  1159
try { assertEquals("impossible", lookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1160
        .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
  1161
 } catch (NoSuchMethodException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1162
MethodHandle MH_newString = publicLookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1163
  .findConstructor(String.class, MT_newString);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1164
assertEquals("", (String) MH_newString.invokeExact());
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1165
         * }</pre></blockquote>
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1166
         *
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1167
         * @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
  1168
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1169
         * @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
  1170
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1171
         * @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
  1172
         * @throws IllegalAccessException if access checking fails,
35772
044f660251cc 8138884: MethodHandles.Lookup.findVirtual() Javadoc fails to consider private interface methods
srastogi
parents: 35716
diff changeset
  1173
         *                                or if the method is {@code static},
044f660251cc 8138884: MethodHandles.Lookup.findVirtual() Javadoc fails to consider private interface methods
srastogi
parents: 35716
diff changeset
  1174
         *                                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
  1175
         *                                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
  1176
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1177
         * @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
  1178
         *                              <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
  1179
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1180
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1181
        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
  1182
            if (refc == MethodHandle.class) {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1183
                MethodHandle mh = findVirtualForMH(name, type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1184
                if (mh != null)  return mh;
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1185
            } else if (refc == VarHandle.class) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1186
                MethodHandle mh = findVirtualForVH(name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1187
                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
  1188
            }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1189
            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
  1190
            MemberName method = resolveOrFail(refKind, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1191
            return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1192
        }
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1193
        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
  1194
            // 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
  1195
            if ("invoke".equals(name))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1196
                return invoker(type);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1197
            if ("invokeExact".equals(name))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1198
                return exactInvoker(type);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1199
            assert(!MemberName.isMethodHandleInvokeName(name));
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1200
            return null;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1201
        }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1202
        private MethodHandle findVirtualForVH(String name, MethodType type) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1203
            try {
37343
35a2231828a7 8151705: VarHandle.AccessMode enum names should conform to code style
psandoz
parents: 37340
diff changeset
  1204
                return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1205
            } catch (IllegalArgumentException e) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1206
                return null;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1207
            }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1208
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1209
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1210
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1211
         * 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
  1212
         * the constructor of the specified type.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1213
         * 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
  1214
         * 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
  1215
         * 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
  1216
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1217
         * 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
  1218
         * (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
  1219
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1220
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1221
         * {@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
  1222
         * 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
  1223
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1224
         * 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
  1225
         * 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
  1226
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  1227
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1228
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
  1229
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
  1230
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1231
MethodHandle MH_newArrayList = publicLookup().findConstructor(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1232
  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
  1233
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
  1234
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
  1235
assert(orig != copy);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1236
assertEquals(orig, copy);
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1237
// a variable-arity constructor:
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1238
MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1239
  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
  1240
ProcessBuilder pb = (ProcessBuilder)
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1241
  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
  1242
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
  1243
         * }</pre></blockquote>
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1244
         * @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
  1245
         * @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
  1246
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1247
         * @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
  1248
         * @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
  1249
         *                                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
  1250
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1251
         * @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
  1252
         *                              <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
  1253
         * @throws NullPointerException if any argument is null
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1254
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1255
        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
  1256
            if (refc.isArray()) {
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  1257
                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
  1258
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1259
            String name = "<init>";
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1260
            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
  1261
            return getDirectConstructor(refc, ctor);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1262
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1263
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1264
        /**
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1265
         * 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
  1266
         * initializer of the class is not run.
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1267
         * <p>
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1268
         * 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
  1269
         * 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
  1270
         * 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
  1271
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1272
         * @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
  1273
         * @return the requested class.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1274
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1275
         *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1276
         * @throws LinkageError if the linkage fails
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1277
         * @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
  1278
         * @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
  1279
         * modes.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1280
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1281
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1282
         * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1283
         */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1284
        public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1285
            Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1286
            return accessClass(targetClass);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1287
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1288
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1289
        /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1290
         * 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
  1291
         * static initializer of the class is not run.
36623
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1292
         * <p>
79e0e71cdb20 8150782: findClass / accessClass throw unexpected exceptions
mhaupt
parents: 36220
diff changeset
  1293
         * 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
  1294
         * {@linkplain #lookupModes() lookup modes}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1295
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1296
         * @param targetClass the class to be access-checked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1297
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1298
         * @return the class that has been access-checked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1299
         *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1300
         * @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
  1301
         * modes.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1302
         * @exception SecurityException if a security manager is present and it
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1303
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1304
         * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1305
         */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1306
        public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1307
            if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1308
                throw new MemberName(targetClass).makeAccessException("access violation", this);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1309
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1310
            checkSecurityManager(targetClass, null);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1311
            return targetClass;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1312
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1313
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1314
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1315
         * 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
  1316
         * 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
  1317
         * <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
  1318
         * 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
  1319
         * 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
  1320
         * with a suitably restricted receiver type prepended.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1321
         * (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
  1322
         * 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
  1323
         * to the lookup object.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1324
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1325
         * Before method resolution,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1326
         * 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
  1327
         * 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
  1328
         * <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
  1329
         * privileges, the access fails.
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1330
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1331
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1332
         * {@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
  1333
         * 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
  1334
         * <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
  1335
         * <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
  1336
         * 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
  1337
         * 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
  1338
         * 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
  1339
         * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  1340
         * <blockquote><pre>{@code
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1341
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
  1342
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
  1343
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1344
static class Listie extends ArrayList {
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1345
  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
  1346
  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
  1347
}
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1348
...
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1349
// 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
  1350
MethodHandle MH_newListie = Listie.lookup()
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1351
  .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
  1352
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
  1353
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
  1354
        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
  1355
 } catch (NoSuchMethodException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1356
// 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
  1357
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
  1358
  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
  1359
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
  1360
  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
  1361
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
  1362
  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
  1363
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
  1364
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
  1365
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
  1366
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
  1367
        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
  1368
 } catch (IllegalAccessException ex) { } // OK
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1369
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
  1370
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
  1371
         * }</pre></blockquote>
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  1372
         *
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1373
         * @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
  1374
         * @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
  1375
         * @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
  1376
         * @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
  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
35716
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1379
         * @throws IllegalAccessException if access checking fails,
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1380
         *                                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
  1381
         *                                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
  1382
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1383
         * @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
  1384
         *                              <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
  1385
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1386
         */
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1387
        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
  1388
                                        Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1389
            checkSpecialCaller(specialCaller, refc);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1390
            Lookup specialLookup = this.in(specialCaller);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1391
            MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  1392
            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
  1393
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1394
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1395
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1396
         * 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
  1397
         * 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
  1398
         * value type.
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1399
         * 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
  1400
         * the field.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1401
         * 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
  1402
         * @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
  1403
         * @param name the field's name
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1404
         * @param type the field's type
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1405
         * @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
  1406
         * @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
  1407
         * @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
  1408
         * @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
  1409
         *                              <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
  1410
         * @throws NullPointerException if any argument is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1411
         * @see #findVarHandle(Class, String, Class)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1412
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1413
        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
  1414
            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
  1415
            return getDirectField(REF_getField, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1416
        }
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1417
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1418
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1419
         * 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
  1420
         * 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
  1421
         * The method handle will take two arguments, the instance containing
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1422
         * the field, and the value to be stored.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1423
         * The second argument will be of the field's value type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1424
         * 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
  1425
         * @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
  1426
         * @param name the field's name
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1427
         * @param type the field's type
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1428
         * @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
  1429
         * @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
  1430
         * @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
  1431
         * @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
  1432
         *                              <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
  1433
         * @throws NullPointerException if any argument is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1434
         * @see #findVarHandle(Class, String, Class)
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1435
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1436
        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
  1437
            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
  1438
            return getDirectField(REF_putField, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1439
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1440
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1441
        /**
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1442
         * Produces a VarHandle giving access to a non-static field {@code name}
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1443
         * of type {@code type} declared in a class of type {@code recv}.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1444
         * The VarHandle's variable type is {@code type} and it has one
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1445
         * coordinate type, {@code recv}.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1446
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1447
         * Access checking is performed immediately on behalf of the lookup
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1448
         * class.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1449
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1450
         * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1451
         * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1452
         * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1453
         * <li>if the field is declared {@code final}, then the write, atomic
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1454
         *     update, numeric atomic update, and bitwise atomic update access
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1455
         *     modes are unsupported.
39470
d6f8b4a85fb0 8157726: VarHandles/Unsafe should support sub-word atomic ops
shade
parents: 38774
diff changeset
  1456
         * <li>if the field type is anything other than {@code byte},
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1457
         *     {@code short}, {@code char}, {@code int}, {@code long},
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1458
         *     {@code float}, or {@code double} then numeric atomic update
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1459
         *     access modes are unsupported.
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1460
         * <li>if the field type is anything other than {@code boolean},
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1461
         *     {@code byte}, {@code short}, {@code char}, {@code int} or
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1462
         *     {@code long} then bitwise atomic update access modes are
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1463
         *     unsupported.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1464
         * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1465
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1466
         * If the field is declared {@code volatile} then the returned VarHandle
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1467
         * will override access to the field (effectively ignore the
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1468
         * {@code volatile} declaration) in accordance to its specified
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1469
         * access modes.
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1470
         * <p>
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1471
         * If the field type is {@code float} or {@code double} then numeric
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1472
         * and atomic update access modes compare values using their bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1473
         * representation (see {@link Float#floatToRawIntBits} and
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1474
         * {@link Double#doubleToRawLongBits}, respectively).
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1475
         * @apiNote
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1476
         * Bitwise comparison of {@code float} values or {@code double} values,
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1477
         * as performed by the numeric and atomic update access modes, differ
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1478
         * from the primitive {@code ==} operator and the {@link Float#equals}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1479
         * and {@link Double#equals} methods, specifically with respect to
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1480
         * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1481
         * Care should be taken when performing a compare and set or a compare
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1482
         * and exchange operation with such values since the operation may
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1483
         * unexpectedly fail.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1484
         * There are many possible NaN values that are considered to be
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1485
         * {@code NaN} in Java, although no IEEE 754 floating-point operation
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1486
         * provided by Java can distinguish between them.  Operation failure can
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1487
         * occur if the expected or witness value is a NaN value and it is
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1488
         * transformed (perhaps in a platform specific manner) into another NaN
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1489
         * value, and thus has a different bitwise representation (see
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1490
         * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1491
         * details).
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1492
         * The values {@code -0.0} and {@code +0.0} have different bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1493
         * representations but are considered equal when using the primitive
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1494
         * {@code ==} operator.  Operation failure can occur if, for example, a
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1495
         * numeric algorithm computes an expected value to be say {@code -0.0}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1496
         * and previously computed the witness value to be say {@code +0.0}.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1497
         * @param recv the receiver class, of type {@code R}, that declares the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1498
         * non-static field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1499
         * @param name the field's name
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1500
         * @param type the field's type, of type {@code T}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1501
         * @return a VarHandle giving access to non-static fields.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1502
         * @throws NoSuchFieldException if the field does not exist
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1503
         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1504
         * @exception SecurityException if a security manager is present and it
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1505
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1506
         * @throws NullPointerException if any argument is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1507
         * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1508
         */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1509
        public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1510
            MemberName getField = resolveOrFail(REF_getField, recv, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1511
            MemberName putField = resolveOrFail(REF_putField, recv, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1512
            return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1513
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1514
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1515
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1516
         * 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
  1517
         * 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
  1518
         * value type.
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1519
         * The method handle will take no arguments.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1520
         * 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
  1521
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1522
         * 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
  1523
         * 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
  1524
         * @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
  1525
         * @param name the field's name
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1526
         * @param type the field's type
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1527
         * @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
  1528
         * @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
  1529
         * @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
  1530
         * @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
  1531
         *                              <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
  1532
         * @throws NullPointerException if any argument is null
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1533
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1534
        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
  1535
            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
  1536
            return getDirectField(REF_getStatic, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1537
        }
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1538
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1539
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1540
         * 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
  1541
         * 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
  1542
         * The method handle will take a single
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1543
         * 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
  1544
         * 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
  1545
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1546
         * 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
  1547
         * 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
  1548
         * @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
  1549
         * @param name the field's name
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1550
         * @param type the field's type
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1551
         * @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
  1552
         * @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
  1553
         * @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
  1554
         * @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
  1555
         *                              <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
  1556
         * @throws NullPointerException if any argument is null
5726
72c9d793224b 6939203: JSR 292 needs method handle constants
jrose
parents: 5722
diff changeset
  1557
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1558
        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
  1559
            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
  1560
            return getDirectField(REF_putStatic, refc, field);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  1561
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1562
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1563
        /**
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1564
         * Produces a VarHandle giving access to a static field {@code name} of
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1565
         * type {@code type} declared in a class of type {@code decl}.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1566
         * The VarHandle's variable type is {@code type} and it has no
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1567
         * coordinate types.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1568
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1569
         * Access checking is performed immediately on behalf of the lookup
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1570
         * class.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1571
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1572
         * If the returned VarHandle is operated on, the declaring class will be
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1573
         * initialized, if it has not already been initialized.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1574
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1575
         * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1576
         * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1577
         * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1578
         * <li>if the field is declared {@code final}, then the write, atomic
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1579
         *     update, numeric atomic update, and bitwise atomic update access
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1580
         *     modes are unsupported.
39470
d6f8b4a85fb0 8157726: VarHandles/Unsafe should support sub-word atomic ops
shade
parents: 38774
diff changeset
  1581
         * <li>if the field type is anything other than {@code byte},
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1582
         *     {@code short}, {@code char}, {@code int}, {@code long},
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1583
         *     {@code float}, or {@code double}, then numeric atomic update
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1584
         *     access modes are unsupported.
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1585
         * <li>if the field type is anything other than {@code boolean},
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1586
         *     {@code byte}, {@code short}, {@code char}, {@code int} or
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1587
         *     {@code long} then bitwise atomic update access modes are
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1588
         *     unsupported.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1589
         * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1590
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1591
         * If the field is declared {@code volatile} then the returned VarHandle
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1592
         * will override access to the field (effectively ignore the
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1593
         * {@code volatile} declaration) in accordance to its specified
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1594
         * access modes.
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1595
         * <p>
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1596
         * If the field type is {@code float} or {@code double} then numeric
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1597
         * and atomic update access modes compare values using their bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1598
         * representation (see {@link Float#floatToRawIntBits} and
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1599
         * {@link Double#doubleToRawLongBits}, respectively).
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1600
         * @apiNote
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1601
         * Bitwise comparison of {@code float} values or {@code double} values,
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1602
         * as performed by the numeric and atomic update access modes, differ
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1603
         * from the primitive {@code ==} operator and the {@link Float#equals}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1604
         * and {@link Double#equals} methods, specifically with respect to
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1605
         * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1606
         * Care should be taken when performing a compare and set or a compare
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1607
         * and exchange operation with such values since the operation may
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1608
         * unexpectedly fail.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1609
         * There are many possible NaN values that are considered to be
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1610
         * {@code NaN} in Java, although no IEEE 754 floating-point operation
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1611
         * provided by Java can distinguish between them.  Operation failure can
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1612
         * occur if the expected or witness value is a NaN value and it is
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1613
         * transformed (perhaps in a platform specific manner) into another NaN
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1614
         * value, and thus has a different bitwise representation (see
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1615
         * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1616
         * details).
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1617
         * The values {@code -0.0} and {@code +0.0} have different bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1618
         * representations but are considered equal when using the primitive
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1619
         * {@code ==} operator.  Operation failure can occur if, for example, a
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1620
         * numeric algorithm computes an expected value to be say {@code -0.0}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1621
         * and previously computed the witness value to be say {@code +0.0}.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1622
         * @param decl the class that declares the static field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1623
         * @param name the field's name
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1624
         * @param type the field's type, of type {@code T}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1625
         * @return a VarHandle giving access to a static field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1626
         * @throws NoSuchFieldException if the field does not exist
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1627
         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1628
         * @exception SecurityException if a security manager is present and it
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1629
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1630
         * @throws NullPointerException if any argument is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1631
         * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1632
         */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1633
        public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1634
            MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1635
            MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1636
            return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1637
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1638
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1639
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1640
         * 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
  1641
         * 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
  1642
         * 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
  1643
         * 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
  1644
         * 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
  1645
         * without any insertion of an additional receiver parameter.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1646
         * 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
  1647
         * 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
  1648
         * requested method on the given receiver.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1649
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1650
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1651
         * {@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
  1652
         * 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
  1653
         * <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
  1654
         * (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
  1655
         * 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
  1656
         * <p>
45065
0c9f6b245cf1 8159995: Rename internal Unsafe.compare methods
psandoz
parents: 44860
diff changeset
  1657
         * This is almost equivalent to the following code, with some differences noted below:
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1658
         * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  1659
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
  1660
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
  1661
...
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1662
MethodHandle mh0 = lookup().findVirtual(defc, name, type);
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1663
MethodHandle mh1 = mh0.bindTo(receiver);
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  1664
mh1 = mh1.withVarargs(mh0.isVarargsCollector());
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1665
return mh1;
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1666
         * }</pre></blockquote>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1667
         * 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
  1668
         * 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
  1669
         * to the lookup class.
45065
0c9f6b245cf1 8159995: Rename internal Unsafe.compare methods
psandoz
parents: 44860
diff changeset
  1670
         * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
0c9f6b245cf1 8159995: Rename internal Unsafe.compare methods
psandoz
parents: 44860
diff changeset
  1671
         * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
45140
2901d2f1a6aa 8180075: Javadoc of MethodHandles.Lookup::bind should note the difference from MethodHandle::bindTo
psandoz
parents: 45124
diff changeset
  1672
         * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
2901d2f1a6aa 8180075: Javadoc of MethodHandles.Lookup::bind should note the difference from MethodHandle::bindTo
psandoz
parents: 45124
diff changeset
  1673
         * the receiver is restricted by {@code findVirtual} to the lookup class.)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1674
         * @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
  1675
         * @param name the name of the method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1676
         * @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
  1677
         * @return the desired method handle
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1678
         * @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
  1679
         * @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
  1680
         *                                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
  1681
         *                                is set and {@code asVarargsCollector} fails
8349
e1ba54c43609 7014755: JSR 292 member lookup interaction with security manager
jrose
parents: 8347
diff changeset
  1682
         * @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
  1683
         *                              <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
  1684
         * @throws NullPointerException if any argument is null
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1685
         * @see MethodHandle#bindTo
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1686
         * @see #findVirtual
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1687
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1688
        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
  1689
            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
  1690
            MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
44859
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  1691
            MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerClass(method));
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  1692
            if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  1693
                throw new IllegalAccessException("The restricted defining class " +
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  1694
                                                 mh.type().leadingReferenceParameter().getName() +
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  1695
                                                 " is not assignable from receiver class " +
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  1696
                                                 receiver.getClass().getName());
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  1697
            }
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  1698
            return mh.bindArgumentL(0, receiver).setVarargs(method);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1699
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1700
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1701
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1702
         * 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
  1703
         * 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
  1704
         * 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
  1705
         * 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
  1706
         * 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
  1707
         * 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
  1708
         * 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
  1709
         * 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
  1710
         * 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
  1711
         * 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
  1712
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1713
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1714
         * {@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
  1715
         * 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
  1716
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1717
         * 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
  1718
         * 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
  1719
         * 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
  1720
         * @param m the reflected method
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1721
         * @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
  1722
         * @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
  1723
         *                                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
  1724
         *                                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
  1725
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1726
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1727
        public MethodHandle unreflect(Method m) throws IllegalAccessException {
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1728
            if (m.getDeclaringClass() == MethodHandle.class) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1729
                MethodHandle mh = unreflectForMH(m);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1730
                if (mh != null)  return mh;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1731
            }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1732
            if (m.getDeclaringClass() == VarHandle.class) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1733
                MethodHandle mh = unreflectForVH(m);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1734
                if (mh != null)  return mh;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1735
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1736
            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
  1737
            byte refKind = method.getReferenceKind();
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1738
            if (refKind == REF_invokeSpecial)
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1739
                refKind = REF_invokeVirtual;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1740
            assert(method.isMethod());
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1741
            @SuppressWarnings("deprecation")
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1742
            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
  1743
            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
  1744
        }
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1745
        private MethodHandle unreflectForMH(Method m) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1746
            // these names require special lookups because they throw UnsupportedOperationException
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1747
            if (MemberName.isMethodHandleInvokeName(m.getName()))
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1748
                return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1749
            return null;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1750
        }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1751
        private MethodHandle unreflectForVH(Method m) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1752
            // these names require special lookups because they throw UnsupportedOperationException
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1753
            if (MemberName.isVarHandleMethodInvokeName(m.getName()))
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1754
                return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1755
            return null;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1756
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1757
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1758
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1759
         * Produces a method handle for a reflected method.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1760
         * 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
  1761
         * <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
  1762
         * instruction from within the explicitly specified {@code specialCaller}.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1763
         * 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
  1764
         * with a suitably restricted receiver type prepended.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1765
         * (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
  1766
         * 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
  1767
         * 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
  1768
         * 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
  1769
         * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1770
         * Before method resolution,
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1771
         * 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
  1772
         * 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
  1773
         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1774
         * privileges, the access fails.
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1775
         * <p>
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1776
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1777
         * {@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
  1778
         * 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
  1779
         * @param m the reflected method
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1780
         * @param specialCaller the class nominally calling the method
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1781
         * @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
  1782
         * @throws IllegalAccessException if access checking fails,
07ecc6d51751 8138578: MethodHandles.Lookup.findSpecial() Javadoc fails to consider static methods
mhaupt
parents: 34959
diff changeset
  1783
         *                                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
  1784
         *                                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
  1785
         *                                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
  1786
         * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1787
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1788
        public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  1789
            checkSpecialCaller(specialCaller, null);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1790
            Lookup specialLookup = this.in(specialCaller);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1791
            MemberName method = new MemberName(m, true);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1792
            assert(method.isMethod());
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1793
            // 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
  1794
            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
  1795
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1796
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1797
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1798
         * Produces a method handle for a reflected constructor.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1799
         * 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
  1800
         * 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
  1801
         * The method handle will perform a {@code newInstance} operation,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1802
         * 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
  1803
         * arguments passed to the method handle.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1804
         * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1805
         * 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
  1806
         * 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
  1807
         * <p>
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1808
         * The returned method handle will have
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  1809
         * {@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
  1810
         * 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
  1811
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1812
         * 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
  1813
         * be initialized, if it has not already been initialized.
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1814
         * @param c the reflected constructor
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1815
         * @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
  1816
         * @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
  1817
         *                                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
  1818
         *                                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
  1819
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1820
         */
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1821
        public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1822
            MemberName ctor = new MemberName(c);
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1823
            assert(ctor.isConstructor());
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1824
            @SuppressWarnings("deprecation")
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1825
            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
  1826
            return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1827
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1828
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1829
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1830
         * 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
  1831
         * 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
  1832
         * value type.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1833
         * 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
  1834
         * Otherwise, its single argument will be the instance containing
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1835
         * the field.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  1836
         * 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
  1837
         * 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
  1838
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1839
         * 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
  1840
         * 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
  1841
         * 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
  1842
         * @param f the reflected field
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1843
         * @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
  1844
         * @throws IllegalAccessException if access checking fails
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1845
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1846
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1847
        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
  1848
            return unreflectField(f, false);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1849
        }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1850
        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
  1851
            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
  1852
            assert(isSetter
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1853
                    ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1854
                    : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  1855
            @SuppressWarnings("deprecation")
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  1856
            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
  1857
            return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1858
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1859
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1860
        /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  1861
         * 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
  1862
         * 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
  1863
         * 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
  1864
         * 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
  1865
         * Otherwise, the two arguments will be the instance containing
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  1866
         * 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
  1867
         * 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
  1868
         * 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
  1869
         * <p>
50fba462caa5 8024599: JSR 292 direct method handles need to respect initialization rules for static members
jrose
parents: 20531
diff changeset
  1870
         * 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
  1871
         * 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
  1872
         * 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
  1873
         * @param f the reflected field
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1874
         * @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
  1875
         * @throws IllegalAccessException if access checking fails
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1876
         * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  1877
         */
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  1878
        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
  1879
            return unreflectField(f, true);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1880
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  1881
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1882
        /**
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1883
         * Produces a VarHandle giving access to a reflected field {@code f}
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1884
         * of type {@code T} declared in a class of type {@code R}.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1885
         * The VarHandle's variable type is {@code T}.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1886
         * If the field is non-static the VarHandle has one coordinate type,
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1887
         * {@code R}.  Otherwise, the field is static, and the VarHandle has no
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1888
         * coordinate types.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1889
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1890
         * Access checking is performed immediately on behalf of the lookup
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1891
         * class, regardless of the value of the field's {@code accessible}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1892
         * flag.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1893
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1894
         * If the field is static, and if the returned VarHandle is operated
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1895
         * on, the field's declaring class will be initialized, if it has not
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1896
         * already been initialized.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1897
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1898
         * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1899
         * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1900
         * <ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1901
         * <li>if the field is declared {@code final}, then the write, atomic
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1902
         *     update, numeric atomic update, and bitwise atomic update access
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1903
         *     modes are unsupported.
39470
d6f8b4a85fb0 8157726: VarHandles/Unsafe should support sub-word atomic ops
shade
parents: 38774
diff changeset
  1904
         * <li>if the field type is anything other than {@code byte},
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1905
         *     {@code short}, {@code char}, {@code int}, {@code long},
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1906
         *     {@code float}, or {@code double} then numeric atomic update
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1907
         *     access modes are unsupported.
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1908
         * <li>if the field type is anything other than {@code boolean},
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1909
         *     {@code byte}, {@code short}, {@code char}, {@code int} or
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1910
         *     {@code long} then bitwise atomic update access modes are
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  1911
         *     unsupported.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1912
         * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1913
         * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1914
         * If the field is declared {@code volatile} then the returned VarHandle
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1915
         * will override access to the field (effectively ignore the
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  1916
         * {@code volatile} declaration) in accordance to its specified
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1917
         * access modes.
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1918
         * <p>
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1919
         * If the field type is {@code float} or {@code double} then numeric
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1920
         * and atomic update access modes compare values using their bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1921
         * representation (see {@link Float#floatToRawIntBits} and
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1922
         * {@link Double#doubleToRawLongBits}, respectively).
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1923
         * @apiNote
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1924
         * Bitwise comparison of {@code float} values or {@code double} values,
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1925
         * as performed by the numeric and atomic update access modes, differ
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1926
         * from the primitive {@code ==} operator and the {@link Float#equals}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1927
         * and {@link Double#equals} methods, specifically with respect to
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1928
         * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1929
         * Care should be taken when performing a compare and set or a compare
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1930
         * and exchange operation with such values since the operation may
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1931
         * unexpectedly fail.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1932
         * There are many possible NaN values that are considered to be
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1933
         * {@code NaN} in Java, although no IEEE 754 floating-point operation
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1934
         * provided by Java can distinguish between them.  Operation failure can
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1935
         * occur if the expected or witness value is a NaN value and it is
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1936
         * transformed (perhaps in a platform specific manner) into another NaN
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1937
         * value, and thus has a different bitwise representation (see
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1938
         * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1939
         * details).
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1940
         * The values {@code -0.0} and {@code +0.0} have different bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1941
         * representations but are considered equal when using the primitive
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1942
         * {@code ==} operator.  Operation failure can occur if, for example, a
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1943
         * numeric algorithm computes an expected value to be say {@code -0.0}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  1944
         * and previously computed the witness value to be say {@code +0.0}.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1945
         * @param f the reflected field, with a field of type {@code T}, and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1946
         * a declaring class of type {@code R}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1947
         * @return a VarHandle giving access to non-static fields or a static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1948
         * field
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1949
         * @throws IllegalAccessException if access checking fails
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1950
         * @throws NullPointerException if the argument is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1951
         * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1952
         */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1953
        public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1954
            MemberName getField = new MemberName(f, false);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1955
            MemberName putField = new MemberName(f, true);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1956
            return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1957
                                                      f.getDeclaringClass(), getField, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1958
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1959
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1960
        /**
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1961
         * 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
  1962
         * created by this lookup object or a similar one.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1963
         * Security and access checks are performed to ensure that this lookup object
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1964
         * is capable of reproducing the target method handle.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1965
         * This means that the cracking may fail if target is a direct method handle
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1966
         * 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
  1967
         * 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
  1968
         * and was created by a lookup object for a different class.
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1969
         * @param target a direct method handle to crack into symbolic reference components
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1970
         * @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
  1971
         * @exception SecurityException if a security manager is present and it
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1972
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1973
         * @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
  1974
         * @exception NullPointerException if the target is {@code null}
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  1975
         * @see MethodHandleInfo
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1976
         * @since 1.8
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1977
         */
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1978
        public MethodHandleInfo revealDirect(MethodHandle target) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1979
            MemberName member = target.internalMemberName();
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1980
            if (member == null || (!member.isResolved() &&
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1981
                                   !member.isMethodHandleInvoke() &&
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  1982
                                   !member.isVarHandleMethodInvoke()))
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1983
                throw newIllegalArgumentException("not a direct method handle");
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1984
            Class<?> defc = member.getDeclaringClass();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1985
            byte refKind = member.getReferenceKind();
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1986
            assert(MethodHandleNatives.refKindIsValid(refKind));
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1987
            if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1988
                // Devirtualized method invocation is usually formally virtual.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1989
                // To avoid creating extra MemberName objects for this common case,
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1990
                // we encode this extra degree of freedom using MH.isInvokeSpecial.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1991
                refKind = REF_invokeVirtual;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1992
            if (refKind == REF_invokeVirtual && defc.isInterface())
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1993
                // Symbolic reference is through interface but resolves to Object method (toString, etc.)
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1994
                refKind = REF_invokeInterface;
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1995
            // Check SM permissions and member access before cracking.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1996
            try {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  1997
                checkAccess(refKind, defc, member);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1998
                checkSecurityManager(defc, member);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  1999
            } catch (IllegalAccessException ex) {
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2000
                throw new IllegalArgumentException(ex);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2001
            }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2002
            if (allowedModes != TRUSTED && member.isCallerSensitive()) {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2003
                Class<?> callerClass = target.internalCallerClass();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2004
                if (!hasPrivateAccess() || callerClass != lookupClass())
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2005
                    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
  2006
            }
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2007
            // Produce the handle to the results.
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2008
            return new InfoFromMemberName(this, member, refKind);
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2009
        }
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2010
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2011
        /// Helper methods, all package-private.
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2012
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2013
        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
  2014
            checkSymbolicClass(refc);  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  2015
            Objects.requireNonNull(name);
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  2016
            Objects.requireNonNull(type);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2017
            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
  2018
                                            NoSuchFieldException.class);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2019
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2020
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2021
        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
  2022
            checkSymbolicClass(refc);  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  2023
            Objects.requireNonNull(name);
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  2024
            Objects.requireNonNull(type);
20531
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  2025
            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
  2026
            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
  2027
                                            NoSuchMethodException.class);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2028
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2029
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2030
        MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2031
            checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  2032
            Objects.requireNonNull(member.getName());
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  2033
            Objects.requireNonNull(member.getType());
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2034
            return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2035
                                            ReflectiveOperationException.class);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2036
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2037
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2038
        void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
29094
a4fd2b5e49f8 8073479: Replace obj.getClass hacks with Objects.requireNonNull
shade
parents: 27947
diff changeset
  2039
            Objects.requireNonNull(refc);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2040
            Class<?> caller = lookupClassOrNull();
13044
8411854afc2b 7165628: Issues with java.lang.invoke.MethodHandles.Lookup
jrose
parents: 11535
diff changeset
  2041
            if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2042
                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
  2043
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2044
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2045
        /** 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
  2046
        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
  2047
            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
  2048
                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
  2049
        }
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  2050
14c2a04f21e6 8001108: an attempt to use "<init>" as a method name should elicit NoSuchMethodException
jrose
parents: 20530
diff changeset
  2051
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2052
        /**
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2053
         * Find my trustable caller class if m is a caller sensitive method.
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2054
         * 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
  2055
         * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2056
         */
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2057
        Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2058
            Class<?> callerClass = null;
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2059
            if (MethodHandleNatives.isCallerSensitive(m)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2060
                // 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
  2061
                if (hasPrivateAccess()) {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2062
                    callerClass = lookupClass;
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2063
                } else {
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2064
                    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
  2065
                }
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2066
            }
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2067
            return callerClass;
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2068
        }
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  2069
42338
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
  2070
        /**
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
  2071
         * Returns {@code true} if this lookup has {@code PRIVATE} access.
44359
c6761862ca0b 8174823: Module system implementation refresh (3/2017)
alanb
parents: 43712
diff changeset
  2072
         * @return {@code true} if this lookup has {@code PRIVATE} access.
42338
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
  2073
         * @since 9
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
  2074
         */
a60f280f803c 8169069: Module system implementation refresh (11/2016)
alanb
parents: 41829
diff changeset
  2075
        public boolean hasPrivateAccess() {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2076
            return (allowedModes & PRIVATE) != 0;
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2077
        }
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2078
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  2079
        /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2080
         * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2081
         * Determines a trustable caller class to compare with refc, the symbolic reference class.
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2082
         * 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
  2083
         */
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2084
        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
  2085
            SecurityManager smgr = System.getSecurityManager();
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2086
            if (smgr == null)  return;
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2087
            if (allowedModes == TRUSTED)  return;
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  2088
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2089
            // Step 1:
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2090
            boolean fullPowerLookup = hasPrivateAccess();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2091
            if (!fullPowerLookup ||
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2092
                !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2093
                ReflectUtil.checkPackageAccess(refc);
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2094
            }
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  2095
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2096
            if (m == null) {  // findClass or accessClass
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2097
                // Step 2b:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2098
                if (!fullPowerLookup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2099
                    smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2100
                }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2101
                return;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2102
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2103
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2104
            // Step 2a:
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2105
            if (m.isPublic()) return;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2106
            if (!fullPowerLookup) {
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2107
                smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
16906
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  2108
            }
44dfee24cb71 8010117: Annotate jdk caller sensitive methods with @sun.reflect.CallerSensitive
mchung
parents: 16898
diff changeset
  2109
18766
28c62f5e9a47 8007035: deprecate public void SecurityManager.checkMemberAccess(Class<?> clazz, int which)
mchung
parents: 18569
diff changeset
  2110
            // Step 3:
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2111
            Class<?> defc = m.getDeclaringClass();
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2112
            if (!fullPowerLookup && defc != refc) {
18264
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2113
                ReflectUtil.checkPackageAccess(defc);
286a7973575a 8009424: Restrict publicLookup with additional checks
twisti
parents: 16906
diff changeset
  2114
            }
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2115
        }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2116
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2117
        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
  2118
            boolean wantStatic = (refKind == REF_invokeStatic);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2119
            String message;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2120
            if (m.isConstructor())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2121
                message = "expected a method, not a constructor";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2122
            else if (!m.isMethod())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2123
                message = "expected a method";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2124
            else if (wantStatic != m.isStatic())
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2125
                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
  2126
            else
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2127
                { checkAccess(refKind, refc, m); return; }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2128
            throw m.makeAccessException(message, this);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2129
        }
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2130
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2131
        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
  2132
            boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2133
            String message;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2134
            if (wantStatic != m.isStatic())
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2135
                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
  2136
            else
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2137
                { checkAccess(refKind, refc, m); return; }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2138
            throw m.makeAccessException(message, this);
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2139
        }
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2140
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2141
        /** 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
  2142
        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
  2143
            assert(m.referenceKindIsConsistentWith(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2144
                   MethodHandleNatives.refKindIsValid(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2145
                   (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2146
            int allowedModes = this.allowedModes;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2147
            if (allowedModes == TRUSTED)  return;
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2148
            int mods = m.getModifiers();
20528
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2149
            if (Modifier.isProtected(mods) &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2150
                    refKind == REF_invokeVirtual &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2151
                    m.getDeclaringClass() == Object.class &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2152
                    m.getName().equals("clone") &&
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2153
                    refc.isArray()) {
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2154
                // The JVM does this hack also.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2155
                // (See ClassVerifier::verify_invoke_instructions
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2156
                // and LinkResolver::check_method_accessability.)
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2157
                // 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
  2158
                // there is no separate method for int[].clone.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2159
                // All arrays simply inherit Object.clone.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2160
                // But for access checking logic, we make Object.clone
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2161
                // (normally protected) appear to be public.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2162
                // Later on, when the DirectMethodHandle is created,
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2163
                // its leading argument will be restricted to the
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2164
                // requested array type.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2165
                // N.B. The return type is not adjusted, because
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2166
                // that is *not* the bytecode behavior.
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2167
                mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
0b1e2130d3f7 8001105: findVirtual of Object[].clone produces internal error
jrose
parents: 20527
diff changeset
  2168
            }
25537
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  2169
            if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  2170
                // cannot "new" a protected ctor in a different package
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  2171
                mods ^= Modifier.PROTECTED;
087de200d457 8035788: Provide more consistency for lookups
twisti
parents: 24860
diff changeset
  2172
            }
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2173
            if (Modifier.isFinal(mods) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2174
                    MethodHandleNatives.refKindIsSetter(refKind))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2175
                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
  2176
            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
  2177
            if ((requestedModes & allowedModes) != 0) {
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2178
                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
  2179
                                                    mods, lookupClass(), allowedModes))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2180
                    return;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2181
            } else {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2182
                // 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
  2183
                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
  2184
                        && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2185
                    return;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2186
            }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2187
            throw m.makeAccessException(accessFailedMessage(refc, m), this);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2188
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2189
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2190
        String accessFailedMessage(Class<?> refc, MemberName m) {
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2191
            Class<?> defc = m.getDeclaringClass();
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2192
            int mods = m.getModifiers();
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2193
            // check the class first:
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2194
            boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2195
                               (defc == refc ||
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2196
                                Modifier.isPublic(refc.getModifiers())));
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2197
            if (!classOK && (allowedModes & PACKAGE) != 0) {
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  2198
                classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), FULL_POWER_MODES) &&
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2199
                           (defc == refc ||
43712
5dfd0950317c 8173393: Module system implementation refresh (2/2017)
alanb
parents: 43219
diff changeset
  2200
                            VerifyAccess.isClassAccessible(refc, lookupClass(), FULL_POWER_MODES)));
8347
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2201
            }
e5daa5772ffd 7013730: JSR 292 reflective operations should report errors with standard exception types
jrose
parents: 8346
diff changeset
  2202
            if (!classOK)
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2203
                return "class is not public";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2204
            if (Modifier.isPublic(mods))
36511
9d0388c6b336 8142968: Module System implementation
alanb
parents: 36220
diff changeset
  2205
                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
  2206
            if (Modifier.isPrivate(mods))
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2207
                return "member is private";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2208
            if (Modifier.isProtected(mods))
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2209
                return "member is protected";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2210
            return "member is private to package";
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2211
        }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2212
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2213
        private static final boolean ALLOW_NESTMATE_ACCESS = false;
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2214
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2215
        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
  2216
            int allowedModes = this.allowedModes;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2217
            if (allowedModes == TRUSTED)  return;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2218
            if (!hasPrivateAccess()
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2219
                || (specialCaller != lookupClass()
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2220
                       // ensure non-abstract methods in superinterfaces can be special-invoked
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2221
                    && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2222
                    && !(ALLOW_NESTMATE_ACCESS &&
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2223
                         VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2224
                throw new MemberName(specialCaller).
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2225
                    makeAccessException("no private access for invokespecial", this);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2226
        }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2227
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2228
        private boolean restrictProtectedReceiver(MemberName method) {
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2229
            // 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
  2230
            // 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
  2231
            if (!method.isProtected() || method.isStatic()
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2232
                || allowedModes == TRUSTED
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2233
                || 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
  2234
                || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2235
                || (ALLOW_NESTMATE_ACCESS &&
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2236
                    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
  2237
                return false;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2238
            return true;
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2239
        }
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2240
        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
  2241
            assert(!method.isStatic());
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2242
            // 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
  2243
            if (!method.getDeclaringClass().isAssignableFrom(caller)) {
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2244
                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
  2245
            }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2246
            MethodType rawType = mh.type();
44859
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  2247
            if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2248
            MethodType narrowType = rawType.changeParameterType(0, caller);
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2249
            assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2250
            assert(mh.viewAsTypeChecks(narrowType, true));
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2251
            return mh.copyWith(narrowType, mh.form);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2252
        }
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2253
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2254
        /** Check access and get the requested method. */
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2255
        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
  2256
            final boolean doRestrict    = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2257
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2258
            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
  2259
        }
44859
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  2260
        /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  2261
        private MethodHandle getDirectMethodNoRestrictInvokeSpecial(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
  2262
            final boolean doRestrict    = false;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2263
            final boolean checkSecurity = true;
44859
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  2264
            return getDirectMethodCommon(REF_invokeSpecial, 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
  2265
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2266
        /** 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
  2267
        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
  2268
            final boolean doRestrict    = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2269
            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
  2270
            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
  2271
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2272
        /** 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
  2273
        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
  2274
                                                   boolean checkSecurity,
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2275
                                                   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
  2276
            checkMethod(refKind, refc, method);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2277
            // 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
  2278
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2279
                checkSecurityManager(refc, method);
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2280
            assert(!method.isMethodHandleInvoke());
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2281
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2282
            if (refKind == REF_invokeSpecial &&
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2283
                refc != lookupClass() &&
19804
83170920c07b 8008688: Make MethodHandleInfo public
rfield
parents: 18766
diff changeset
  2284
                !refc.isInterface() &&
24860
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2285
                refc != lookupClass().getSuperclass() &&
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2286
                refc.isAssignableFrom(lookupClass())) {
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2287
                assert(!method.getName().equals("<init>"));  // not this code path
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2288
                // Per JVMS 6.5, desc. of invokespecial instruction:
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2289
                // If the method is in a superclass of the LC,
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2290
                // 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
  2291
                // repeat the search (symbolic lookup) from LC.super
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2292
                // and continue with the direct superclass of that class,
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2293
                // 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
  2294
                // FIXME: MemberName.resolve should handle this instead.
24860
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2295
                Class<?> refcAsSuper = lookupClass();
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2296
                MemberName m2;
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2297
                do {
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2298
                    refcAsSuper = refcAsSuper.getSuperclass();
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2299
                    m2 = new MemberName(refcAsSuper,
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2300
                                        method.getName(),
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2301
                                        method.getMethodType(),
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2302
                                        REF_invokeSpecial);
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2303
                    m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2304
                } while (m2 == null &&         // no method is found yet
41b07c1952f4 8032400: JSR292: invokeSpecial: InternalError attempting to lookup a method
vlivanov
parents: 24572
diff changeset
  2305
                         refc != refcAsSuper); // search up to refc
16898
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2306
                if (m2 == null)  throw new InternalError(method.toString());
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2307
                method = m2;
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2308
                refc = refcAsSuper;
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2309
                // redo basic checks
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2310
                checkMethod(refKind, refc, method);
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2311
            }
b321dfd1163f 8008140: Better method handle resolution
vlivanov
parents: 16123
diff changeset
  2312
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2313
            DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2314
            MethodHandle mh = dmh;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2315
            // Optionally narrow the receiver argument to refc using restrictReceiver.
44859
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  2316
            if ((doRestrict && refKind == REF_invokeSpecial) ||
5775b131af51 8177146: MethodHandles.Lookup::bind allows illegal protected access
psandoz
parents: 44844
diff changeset
  2317
                    (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2318
                mh = restrictReceiver(method, dmh, lookupClass());
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2319
            }
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2320
            mh = maybeBindCaller(method, mh, callerClass);
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2321
            mh = mh.setVarargs(method);
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2322
            return mh;
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2323
        }
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2324
        private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2325
                                             Class<?> callerClass)
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2326
                                             throws IllegalAccessException {
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2327
            if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2328
                return mh;
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2329
            Class<?> hostClass = lookupClass;
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2330
            if (!hasPrivateAccess())  // caller must have private access
16118
9f3390f42157 8006439: Improve MethodHandles coverage
vlivanov
parents: 14222
diff changeset
  2331
                hostClass = callerClass;  // callerClass came from a security manager style stack walk
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2332
            MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2333
            // Note: caller will apply varargs after this step happens.
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2334
            return cbmh;
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2335
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2336
        /** 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
  2337
        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
  2338
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2339
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2340
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2341
        /** 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
  2342
        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
  2343
            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
  2344
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2345
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2346
        /** 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
  2347
        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
  2348
                                                  boolean checkSecurity) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2349
            checkField(refKind, refc, field);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2350
            // 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
  2351
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2352
                checkSecurityManager(refc, field);
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2353
            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
  2354
            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2355
                                    restrictProtectedReceiver(field));
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2356
            if (doRestrict)
26470
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2357
                return restrictReceiver(field, dmh, lookupClass());
1586df597397 8050173: Add j.l.i.MethodHandle.copyWith(MethodType, LambdaForm)
vlivanov
parents: 26469
diff changeset
  2358
            return dmh;
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2359
        }
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2360
        private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2361
                                            Class<?> refc, MemberName getField, MemberName putField)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2362
                throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2363
            final boolean checkSecurity = true;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2364
            return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2365
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2366
        private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2367
                                                             Class<?> refc, MemberName getField, MemberName putField)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2368
                throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2369
            final boolean checkSecurity = false;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2370
            return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2371
        }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2372
        private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2373
                                                  Class<?> refc, MemberName getField, MemberName putField,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2374
                                                  boolean checkSecurity) throws IllegalAccessException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2375
            assert getField.isStatic() == putField.isStatic();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2376
            assert getField.isGetter() && putField.isSetter();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2377
            assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2378
            assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2379
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2380
            checkField(getRefKind, refc, getField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2381
            if (checkSecurity)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2382
                checkSecurityManager(refc, getField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2383
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2384
            if (!putField.isFinal()) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2385
                // A VarHandle does not support updates to final fields, any
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2386
                // such VarHandle to a final field will be read-only and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2387
                // therefore the following write-based accessibility checks are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2388
                // only required for non-final fields
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2389
                checkField(putRefKind, refc, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2390
                if (checkSecurity)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2391
                    checkSecurityManager(refc, putField);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2392
            }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2393
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2394
            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2395
                                  restrictProtectedReceiver(getField));
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2396
            if (doRestrict) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2397
                assert !getField.isStatic();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2398
                // receiver type of VarHandle is too wide; narrow to caller
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2399
                if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2400
                    throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2401
                }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2402
                refc = lookupClass();
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2403
            }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2404
            return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2405
        }
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2406
        /** 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
  2407
        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
  2408
            final boolean checkSecurity = true;
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2409
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2410
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2411
        /** 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
  2412
        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
  2413
            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
  2414
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2415
        }
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2416
        /** 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
  2417
        private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2418
                                                  boolean checkSecurity) throws IllegalAccessException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2419
            assert(ctor.isConstructor());
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2420
            checkAccess(REF_newInvokeSpecial, refc, ctor);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2421
            // 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
  2422
            if (checkSecurity)
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2423
                checkSecurityManager(refc, ctor);
14222
58f55d4dde46 7196190: Improve method of handling MethodHandles
jrose
parents: 13610
diff changeset
  2424
            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
  2425
            return DirectMethodHandle.make(ctor).setVarargs(ctor);
5722
4ada807383c8 6939134: JSR 292 adjustments to method handle invocation
jrose
parents: 4537
diff changeset
  2426
        }
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2427
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2428
        /** 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
  2429
         */
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2430
        /*non-public*/
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2431
        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
  2432
            if (!(type instanceof Class || type instanceof MethodType))
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2433
                throw new InternalError("unresolved MemberName");
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2434
            MemberName member = new MemberName(refKind, defc, name, type);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2435
            MethodHandle mh = LOOKASIDE_TABLE.get(member);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2436
            if (mh != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2437
                checkSymbolicClass(defc);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2438
                return mh;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2439
            }
21362
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2440
            // Treat MethodHandle.invoke and invokeExact specially.
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2441
            if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2442
                mh = findVirtualForMH(member.getName(), member.getMethodType());
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2443
                if (mh != null) {
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2444
                    return mh;
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2445
                }
8b2d68e8632a 8026502: java/lang/invoke/MethodHandleConstants.java fails on all platforms
twisti
parents: 20877
diff changeset
  2446
            }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2447
            MemberName resolved = resolveOrFail(refKind, member);
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2448
            mh = getDirectMethodForConstant(refKind, defc, resolved);
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2449
            if (mh instanceof DirectMethodHandle
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2450
                    && canBeCached(refKind, defc, resolved)) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2451
                MemberName key = mh.internalMemberName();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2452
                if (key != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2453
                    key = key.asNormalOriginal();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2454
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2455
                if (member.equals(key)) {  // better safe than sorry
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2456
                    LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2457
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2458
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2459
            return mh;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2460
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2461
        private
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2462
        boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2463
            if (refKind == REF_invokeSpecial) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2464
                return false;
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2465
            }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2466
            if (!Modifier.isPublic(defc.getModifiers()) ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2467
                    !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2468
                    !member.isPublic() ||
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2469
                    member.isCallerSensitive()) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2470
                return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2471
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2472
            ClassLoader loader = defc.getClassLoader();
46047
97d615d81827 8161121: VM::isSystemDomainLoader should consider platform class loader
mchung
parents: 45881
diff changeset
  2473
            if (loader != null) {
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2474
                ClassLoader sysl = ClassLoader.getSystemClassLoader();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2475
                boolean found = false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2476
                while (sysl != null) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2477
                    if (loader == sysl) { found = true; break; }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2478
                    sysl = sysl.getParent();
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2479
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2480
                if (!found) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2481
                    return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2482
                }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2483
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2484
            try {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2485
                MemberName resolved2 = publicLookup().resolveOrFail(refKind,
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2486
                    new MemberName(refKind, defc, member.getName(), member.getType()));
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2487
                checkSecurityManager(defc, resolved2);
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2488
            } catch (ReflectiveOperationException | SecurityException ex) {
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2489
                return false;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2490
            }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2491
            return true;
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2492
        }
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2493
        private
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2494
        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
  2495
                throws ReflectiveOperationException {
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  2496
            if (MethodHandleNatives.refKindIsField(refKind)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2497
                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
  2498
            } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2499
                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
  2500
            } else if (refKind == REF_newInvokeSpecial) {
20534
da86f7904e6d 8025112: JSR 292 spec updates for security manager and caller sensitivity
jrose
parents: 20533
diff changeset
  2501
                return getDirectConstructorNoSecurityManager(defc, member);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2502
            }
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2503
            // oops
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2504
            throw newIllegalArgumentException("bad MethodHandle constant #"+member);
9780
6fc3b49cfee4 7050328: (jsr-292) findConstructor throws ExceptionInInitializerError if run under SecurityManager
jrose
parents: 9752
diff changeset
  2505
        }
20527
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2506
d241258cfbcb 8024761: JSR 292 improve performance of generic invocation
jrose
parents: 19804
diff changeset
  2507
        static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2508
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2509
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2510
    /**
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2511
     * Produces a method handle constructing arrays of a desired type,
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2512
     * as if by the {@code anewarray} bytecode.
37674
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2513
     * 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
  2514
     * The type of its sole argument will be {@code int}, which specifies the size of the array.
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2515
     *
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2516
     * <p> If the returned method handle is invoked with a negative
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2517
     * array size, a {@code NegativeArraySizeException} will be thrown.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2518
     *
37674
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2519
     * @param arrayClass an array type
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2520
     * @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
  2521
     * @throws NullPointerException if the argument is {@code null}
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2522
     * @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
  2523
     * @see java.lang.reflect.Array#newInstance(Class, int)
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2524
     * @jvms 6.5 {@code anewarray} Instruction
37674
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2525
     * @since 9
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2526
     */
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2527
    public static
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2528
    MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2529
        if (!arrayClass.isArray()) {
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2530
            throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2531
        }
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2532
        MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2533
                bindTo(arrayClass.getComponentType());
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2534
        return ani.asType(ani.type().changeReturnType(arrayClass));
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2535
    }
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2536
763f704393cf 8155106: MHs.Lookup.findConstructor returns handles for array classes
mhaupt
parents: 37669
diff changeset
  2537
    /**
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2538
     * Produces a method handle returning the length of an array,
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2539
     * as if by the {@code arraylength} bytecode.
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2540
     * 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
  2541
     * and its sole argument will be the array type.
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2542
     *
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2543
     * <p> If the returned method handle is invoked with a {@code null}
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2544
     * array reference, a {@code NullPointerException} will be thrown.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2545
     *
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2546
     * @param arrayClass an array type
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2547
     * @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
  2548
     * @throws NullPointerException if the argument is {@code null}
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2549
     * @throws IllegalArgumentException if arrayClass is not an array type
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2550
     * @jvms 6.5 {@code arraylength} Instruction
38472
6d7aed566bf3 8157590: MethodHandles.arrayLength() lacks @since tag, implementation throws wrong exception
mhaupt
parents: 38376
diff changeset
  2551
     * @since 9
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2552
     */
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2553
    public static
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2554
    MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2555
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2556
    }
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2557
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2558
    /**
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2559
     * Produces a method handle giving read access to elements of an array,
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2560
     * as if by the {@code aaload} bytecode.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2561
     * 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
  2562
     * 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
  2563
     * and the second will be {@code int}.
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2564
     *
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2565
     * <p> When the returned method handle is invoked,
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2566
     * the array reference and array index are checked.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2567
     * A {@code NullPointerException} will be thrown if the array reference
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2568
     * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2569
     * thrown if the index is negative or if it is greater than or equal to
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2570
     * the length of the array.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2571
     *
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2572
     * @param arrayClass an array type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2573
     * @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
  2574
     * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2575
     * @throws  IllegalArgumentException if arrayClass is not an array type
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2576
     * @jvms 6.5 {@code aaload} Instruction
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2577
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2578
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2579
    MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2580
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2581
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2582
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2583
    /**
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2584
     * Produces a method handle giving write access to elements of an array,
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2585
     * as if by the {@code astore} bytecode.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2586
     * 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
  2587
     * 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
  2588
     * The first and second arguments will be the array type and int.
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2589
     *
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2590
     * <p> When the returned method handle is invoked,
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2591
     * the array reference and array index are checked.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2592
     * A {@code NullPointerException} will be thrown if the array reference
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2593
     * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2594
     * thrown if the index is negative or if it is greater than or equal to
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2595
     * the length of the array.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2596
     *
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  2597
     * @param arrayClass the class of an array
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2598
     * @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
  2599
     * @throws NullPointerException if the argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2600
     * @throws IllegalArgumentException if arrayClass is not an array type
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2601
     * @jvms 6.5 {@code aastore} Instruction
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2602
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2603
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2604
    MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
38376
08549412f0dc 8156915: introduce MethodHandle factory for array length
mhaupt
parents: 37674
diff changeset
  2605
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2606
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2607
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2608
    /**
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2609
     * Produces a VarHandle giving access to elements of an array of type
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2610
     * {@code arrayClass}.  The VarHandle's variable type is the component type
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2611
     * of {@code arrayClass} and the list of coordinate types is
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2612
     * {@code (arrayClass, int)}, where the {@code int} coordinate type
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2613
     * corresponds to an argument that is an index into an array.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2614
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2615
     * Certain access modes of the returned VarHandle are unsupported under
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2616
     * the following conditions:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2617
     * <ul>
39470
d6f8b4a85fb0 8157726: VarHandles/Unsafe should support sub-word atomic ops
shade
parents: 38774
diff changeset
  2618
     * <li>if the component type is anything other than {@code byte},
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2619
     *     {@code short}, {@code char}, {@code int}, {@code long},
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2620
     *     {@code float}, or {@code double} then numeric atomic update access
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2621
     *     modes are unsupported.
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2622
     * <li>if the field type is anything other than {@code boolean},
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2623
     *     {@code byte}, {@code short}, {@code char}, {@code int} or
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2624
     *     {@code long} then bitwise atomic update access modes are
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2625
     *     unsupported.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2626
     * </ul>
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2627
     * <p>
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2628
     * If the component type is {@code float} or {@code double} then numeric
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2629
     * and atomic update access modes compare values using their bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2630
     * representation (see {@link Float#floatToRawIntBits} and
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2631
     * {@link Double#doubleToRawLongBits}, respectively).
47856
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2632
     *
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2633
     * <p> When the returned {@code VarHandle} is invoked,
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2634
     * the array reference and array index are checked.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2635
     * A {@code NullPointerException} will be thrown if the array reference
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2636
     * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2637
     * thrown if the index is negative or if it is greater than or equal to
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2638
     * the length of the array.
76519338df34 8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
mchung
parents: 47216
diff changeset
  2639
     *
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2640
     * @apiNote
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2641
     * Bitwise comparison of {@code float} values or {@code double} values,
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2642
     * as performed by the numeric and atomic update access modes, differ
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2643
     * from the primitive {@code ==} operator and the {@link Float#equals}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2644
     * and {@link Double#equals} methods, specifically with respect to
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2645
     * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2646
     * Care should be taken when performing a compare and set or a compare
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2647
     * and exchange operation with such values since the operation may
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2648
     * unexpectedly fail.
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2649
     * There are many possible NaN values that are considered to be
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2650
     * {@code NaN} in Java, although no IEEE 754 floating-point operation
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2651
     * provided by Java can distinguish between them.  Operation failure can
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2652
     * occur if the expected or witness value is a NaN value and it is
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2653
     * transformed (perhaps in a platform specific manner) into another NaN
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2654
     * value, and thus has a different bitwise representation (see
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2655
     * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2656
     * details).
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2657
     * The values {@code -0.0} and {@code +0.0} have different bitwise
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2658
     * representations but are considered equal when using the primitive
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2659
     * {@code ==} operator.  Operation failure can occur if, for example, a
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2660
     * numeric algorithm computes an expected value to be say {@code -0.0}
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2661
     * and previously computed the witness value to be say {@code +0.0}.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2662
     * @param arrayClass the class of an array, of type {@code T[]}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2663
     * @return a VarHandle giving access to elements of an array
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2664
     * @throws NullPointerException if the arrayClass is null
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2665
     * @throws IllegalArgumentException if arrayClass is not an array type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2666
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2667
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2668
    public static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2669
    VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2670
        return VarHandles.makeArrayElementHandle(arrayClass);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2671
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2672
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2673
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2674
     * Produces a VarHandle giving access to elements of a {@code byte[]} array
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2675
     * viewed as if it were a different primitive array type, such as
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2676
     * {@code int[]} or {@code long[]}.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2677
     * The VarHandle's variable type is the component type of
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2678
     * {@code viewArrayClass} and the list of coordinate types is
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2679
     * {@code (byte[], int)}, where the {@code int} coordinate type
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2680
     * corresponds to an argument that is an index into a {@code byte[]} array.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2681
     * The returned VarHandle accesses bytes at an index in a {@code byte[]}
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2682
     * array, composing bytes to or from a value of the component type of
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2683
     * {@code viewArrayClass} according to the given endianness.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2684
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2685
     * The supported component types (variables types) are {@code short},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2686
     * {@code char}, {@code int}, {@code long}, {@code float} and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2687
     * {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2688
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2689
     * Access of bytes at a given index will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2690
     * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2691
     * or greater than the {@code byte[]} array length minus the size (in bytes)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2692
     * of {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2693
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2694
     * Access of bytes at an index may be aligned or misaligned for {@code T},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2695
     * with respect to the underlying memory address, {@code A} say, associated
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2696
     * with the array and index.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2697
     * If access is misaligned then access for anything other than the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2698
     * {@code get} and {@code set} access modes will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2699
     * {@code IllegalStateException}.  In such cases atomic access is only
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2700
     * guaranteed with respect to the largest power of two that divides the GCD
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2701
     * of {@code A} and the size (in bytes) of {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2702
     * If access is aligned then following access modes are supported and are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2703
     * guaranteed to support atomic access:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2704
     * <ul>
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2705
     * <li>read write access modes for all {@code T}, with the exception of
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2706
     *     access modes {@code get} and {@code set} for {@code long} and
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2707
     *     {@code double} on 32-bit platforms.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2708
     * <li>atomic update access modes for {@code int}, {@code long},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2709
     *     {@code float} or {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2710
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2711
     *     types for certain currently unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2712
     * <li>numeric atomic update access modes for {@code int} and {@code long}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2713
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2714
     *     numeric types for certain currently unsupported access modes.)
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2715
     * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2716
     *     (Future major platform releases of the JDK may support additional
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2717
     *     numeric types for certain currently unsupported access modes.)
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2718
     * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2719
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2720
     * Misaligned access, and therefore atomicity guarantees, may be determined
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2721
     * for {@code byte[]} arrays without operating on a specific array.  Given
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2722
     * an {@code index}, {@code T} and it's corresponding boxed type,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2723
     * {@code T_BOX}, misalignment may be determined as follows:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2724
     * <pre>{@code
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2725
     * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2726
     * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2727
     *     alignmentOffset(0, sizeOfT);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2728
     * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2729
     * boolean isMisaligned = misalignedAtIndex != 0;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2730
     * }</pre>
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2731
     * <p>
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2732
     * If the variable type is {@code float} or {@code double} then atomic
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2733
     * update access modes compare values using their bitwise representation
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2734
     * (see {@link Float#floatToRawIntBits} and
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2735
     * {@link Double#doubleToRawLongBits}, respectively).
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2736
     * @param viewArrayClass the view array class, with a component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2737
     * type {@code T}
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2738
     * @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
  2739
     * stored in the underlying {@code byte} array
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2740
     * @return a VarHandle giving access to elements of a {@code byte[]} array
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2741
     * viewed as if elements corresponding to the components type of the view
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2742
     * array class
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2743
     * @throws NullPointerException if viewArrayClass or byteOrder is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2744
     * @throws IllegalArgumentException if viewArrayClass is not an array type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2745
     * @throws UnsupportedOperationException if the component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2746
     * viewArrayClass is not supported as a variable type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2747
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2748
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2749
    public static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2750
    VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2751
                                     ByteOrder byteOrder) throws IllegalArgumentException {
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2752
        Objects.requireNonNull(byteOrder);
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2753
        return VarHandles.byteArrayViewHandle(viewArrayClass,
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2754
                                              byteOrder == ByteOrder.BIG_ENDIAN);
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2755
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2756
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2757
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2758
     * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2759
     * viewed as if it were an array of elements of a different primitive
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2760
     * component type to that of {@code byte}, such as {@code int[]} or
44860
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2761
     * {@code long[]}.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2762
     * The VarHandle's variable type is the component type of
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2763
     * {@code viewArrayClass} and the list of coordinate types is
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2764
     * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2765
     * corresponds to an argument that is an index into a {@code byte[]} array.
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2766
     * The returned VarHandle accesses bytes at an index in a
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2767
     * {@code ByteBuffer}, composing bytes to or from a value of the component
a33107d3a388 8167229: Improve VarHandle documentation
psandoz
parents: 44859
diff changeset
  2768
     * type of {@code viewArrayClass} according to the given endianness.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2769
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2770
     * The supported component types (variables types) are {@code short},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2771
     * {@code char}, {@code int}, {@code long}, {@code float} and
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2772
     * {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2773
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2774
     * Access will result in a {@code ReadOnlyBufferException} for anything
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2775
     * other than the read access modes if the {@code ByteBuffer} is read-only.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2776
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2777
     * Access of bytes at a given index will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2778
     * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2779
     * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2780
     * {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2781
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2782
     * Access of bytes at an index may be aligned or misaligned for {@code T},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2783
     * with respect to the underlying memory address, {@code A} say, associated
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2784
     * with the {@code ByteBuffer} and index.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2785
     * If access is misaligned then access for anything other than the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2786
     * {@code get} and {@code set} access modes will result in an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2787
     * {@code IllegalStateException}.  In such cases atomic access is only
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2788
     * guaranteed with respect to the largest power of two that divides the GCD
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2789
     * of {@code A} and the size (in bytes) of {@code T}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2790
     * If access is aligned then following access modes are supported and are
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2791
     * guaranteed to support atomic access:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2792
     * <ul>
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2793
     * <li>read write access modes for all {@code T}, with the exception of
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2794
     *     access modes {@code get} and {@code set} for {@code long} and
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2795
     *     {@code double} on 32-bit platforms.
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2796
     * <li>atomic update access modes for {@code int}, {@code long},
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2797
     *     {@code float} or {@code double}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2798
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2799
     *     types for certain currently unsupported access modes.)
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2800
     * <li>numeric atomic update access modes for {@code int} and {@code long}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2801
     *     (Future major platform releases of the JDK may support additional
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2802
     *     numeric types for certain currently unsupported access modes.)
40732
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2803
     * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2804
     *     (Future major platform releases of the JDK may support additional
2fd9cf42bb3c 8161444: VarHandles should provide access bitwise atomics
psandoz
parents: 40418
diff changeset
  2805
     *     numeric types for certain currently unsupported access modes.)
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2806
     * </ul>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2807
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2808
     * Misaligned access, and therefore atomicity guarantees, may be determined
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2809
     * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2810
     * {@code index}, {@code T} and it's corresponding boxed type,
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2811
     * {@code T_BOX}, as follows:
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2812
     * <pre>{@code
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2813
     * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2814
     * ByteBuffer bb = ...
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2815
     * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2816
     * boolean isMisaligned = misalignedAtIndex != 0;
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2817
     * }</pre>
39471
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2818
     * <p>
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2819
     * If the variable type is {@code float} or {@code double} then atomic
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2820
     * update access modes compare values using their bitwise representation
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2821
     * (see {@link Float#floatToRawIntBits} and
6622892a347a 8158039: VarHandle float/double field/array access should support CAS/set/add atomics
psandoz
parents: 39470
diff changeset
  2822
     * {@link Double#doubleToRawLongBits}, respectively).
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2823
     * @param viewArrayClass the view array class, with a component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2824
     * type {@code T}
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2825
     * @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
  2826
     * 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
  2827
     * endianness of a {@code ByteBuffer})
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2828
     * @return a VarHandle giving access to elements of a {@code ByteBuffer}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2829
     * viewed as if elements corresponding to the components type of the view
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2830
     * array class
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2831
     * @throws NullPointerException if viewArrayClass or byteOrder is null
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2832
     * @throws IllegalArgumentException if viewArrayClass is not an array type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2833
     * @throws UnsupportedOperationException if the component type of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2834
     * viewArrayClass is not supported as a variable type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2835
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2836
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2837
    public static
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2838
    VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
37668
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2839
                                      ByteOrder byteOrder) throws IllegalArgumentException {
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2840
        Objects.requireNonNull(byteOrder);
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2841
        return VarHandles.makeByteBufferViewHandle(viewArrayClass,
34a002e5168a 8154556: Use java.nio.ByteOrder instead of boolean value
psandoz
parents: 37604
diff changeset
  2842
                                                   byteOrder == ByteOrder.BIG_ENDIAN);
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2843
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2844
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2845
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2846
    /// method handle invocation (reflective style)
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2847
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2848
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2849
     * 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
  2850
     * 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
  2851
     * a single trailing {@code Object[]} array.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2852
     * 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
  2853
     * arguments:
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2854
     * <ul>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2855
     * <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
  2856
     * <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
  2857
     * <li>an {@code Object[]} array containing trailing arguments
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2858
     * </ul>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2859
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2860
     * 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
  2861
     * the indicated {@code type}.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2862
     * 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
  2863
     * 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
  2864
     * 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
  2865
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2866
     * 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
  2867
     * 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
  2868
     * 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
  2869
     * the final parameter.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  2870
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2871
     * 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
  2872
     * 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
  2873
     * 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
  2874
     * 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
  2875
     * an {@link IllegalArgumentException} instead of invoking the target.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2876
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2877
     * 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
  2878
     * <blockquote><pre>{@code
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2879
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
  2880
int spreadArgCount = type.parameterCount() - leadingArgCount;
8345
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  2881
invoker = invoker.asSpreader(Object[].class, spreadArgCount);
9e2483e6cfab 7013417: JSR 292 needs to support variadic method handle calls
jrose
parents: 7562
diff changeset
  2882
return invoker;
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2883
     * }</pre></blockquote>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2884
     * This method throws no reflective or security exceptions.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2885
     * @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
  2886
     * @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
  2887
     * @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
  2888
     * @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
  2889
     * @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
  2890
     *                  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
  2891
     *                  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
  2892
     *          <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
  2893
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2894
    public static
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2895
    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
  2896
        if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
  2897
            throw newIllegalArgumentException("bad argument count", leadingArgCount);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  2898
        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
  2899
        return type.invokers().spreadInvoker(leadingArgCount);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2900
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2901
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2902
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2903
     * 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
  2904
     * 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
  2905
     * 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
  2906
     * 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
  2907
     * an additional leading argument of type {@code MethodHandle}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2908
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  2909
     * 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
  2910
     * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2911
     *
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2912
     * <p style="font-size:smaller;">
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2913
     * <em>Discussion:</em>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2914
     * 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
  2915
     * of unknown types.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2916
     * 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
  2917
     * handle {@code M}, extract its type {@code T},
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2918
     * 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
  2919
     * 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
  2920
     * (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
  2921
     * is unknown.)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2922
     * If spreading, collecting, or other argument transformations are required,
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2923
     * 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
  2924
     * 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
  2925
     * <p style="font-size:smaller;">
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2926
     * <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
  2927
     * 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
  2928
     * 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
  2929
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2930
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2931
     * This method throws no reflective or security exceptions.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2932
     * @param type the desired target type
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2933
     * @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
  2934
     * @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
  2935
     *          <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
  2936
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2937
    public static
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2938
    MethodHandle exactInvoker(MethodType type) {
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  2939
        return type.invokers().exactInvoker();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2940
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  2941
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2942
    /**
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2943
     * 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
  2944
     * 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
  2945
     * The resulting invoker will have a type which is
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2946
     * 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
  2947
     * an additional leading argument of type {@code MethodHandle}.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2948
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  2949
     * 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
  2950
     * the invoker will apply reference casts as
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2951
     * 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
  2952
     * 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
  2953
     * 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
  2954
     * 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
  2955
     * <p>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2956
     * 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
  2957
     * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2958
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2959
     * <em>Discussion:</em>
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2960
     * 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
  2961
     * 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
  2962
     * 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
  2963
     * of the same arity as the general type.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2964
     * <p style="font-size:smaller;">
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  2965
     * <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
  2966
     * 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
  2967
     * 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
  2968
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2969
     * <p>
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2970
     * This method throws no reflective or security exceptions.
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2971
     * @param type the desired target type
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  2972
     * @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
  2973
     * @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
  2974
     *          <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
  2975
     */
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  2976
    public static
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2977
    MethodHandle invoker(MethodType type) {
26468
2d57604f9299 8050053: Improve caching of different invokers
vlivanov
parents: 26467
diff changeset
  2978
        return type.invokers().genericInvoker();
9645
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2979
    }
dabb5e4edc4c 7034977: JSR 292 MethodHandle.invokeGeneric should be renamed MethodHandle.invoke
jrose
parents: 8822
diff changeset
  2980
36934
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2981
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2982
     * Produces a special <em>invoker method handle</em> which can be used to
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2983
     * invoke a signature-polymorphic access mode method on any VarHandle whose
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2984
     * associated access mode type is compatible with the given type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2985
     * The resulting invoker will have a type which is exactly equal to the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2986
     * desired given type, except that it will accept an additional leading
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2987
     * argument of type {@code VarHandle}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2988
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2989
     * @param accessMode the VarHandle access mode
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2990
     * @param type the desired target type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2991
     * @return a method handle suitable for invoking an access mode method of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2992
     *         any VarHandle whose access mode type is of the given type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2993
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2994
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2995
    static public
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2996
    MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2997
        return type.invokers().varHandleMethodExactInvoker(accessMode);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2998
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  2999
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3000
    /**
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3001
     * Produces a special <em>invoker method handle</em> which can be used to
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3002
     * invoke a signature-polymorphic access mode method on any VarHandle whose
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3003
     * associated access mode type is compatible with the given type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3004
     * The resulting invoker will have a type which is exactly equal to the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3005
     * desired given type, except that it will accept an additional leading
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3006
     * argument of type {@code VarHandle}.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3007
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3008
     * Before invoking its target, if the access mode type differs from the
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3009
     * desired given type, the invoker will apply reference casts as necessary
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3010
     * and box, unbox, or widen primitive values, as if by
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3011
     * {@link MethodHandle#asType asType}.  Similarly, the return value will be
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3012
     * converted as necessary.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3013
     * <p>
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3014
     * This method is equivalent to the following code (though it may be more
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3015
     * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3016
     *
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3017
     * @param accessMode the VarHandle access mode
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3018
     * @param type the desired target type
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3019
     * @return a method handle suitable for invoking an access mode method of
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3020
     *         any VarHandle whose access mode type is convertible to the given
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3021
     *         type.
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3022
     * @since 9
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3023
     */
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3024
    static public
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3025
    MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3026
        return type.invokers().varHandleMethodInvoker(accessMode);
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3027
    }
590fc47a0aeb 8149644: Integrate VarHandles
psandoz
parents: 36623
diff changeset
  3028
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3029
    static /*non-public*/
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3030
    MethodHandle basicInvoker(MethodType type) {
26467
d69abed3a07d 8050052: Small cleanups in java.lang.invoke code
vlivanov
parents: 25859
diff changeset
  3031
        return type.invokers().basicInvoker();
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3032
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3033
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3034
     /// method handle modification (creation from other method handles)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3035
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3036
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3037
     * 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
  3038
     * 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
  3039
     * 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
  3040
     * 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
  3041
     * which is equal to the desired new type.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3042
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3043
     * 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
  3044
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3045
     * 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
  3046
     * 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
  3047
     * 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
  3048
     * 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
  3049
     * <ul>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3050
     * <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
  3051
     *     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
  3052
     *     (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
  3053
     * <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
  3054
     *     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
  3055
     *     (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
  3056
     * <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
  3057
     *     <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
  3058
     *     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
  3059
     * <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
  3060
     *     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
  3061
     *     (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
  3062
     *     widening and/or narrowing.)
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3063
     * <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
  3064
     *     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
  3065
     *     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
  3066
     *     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
  3067
     *     the low-order bit.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3068
     * <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
  3069
     *     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
  3070
     * </ul>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3071
     * @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
  3072
     * @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
  3073
     * @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
  3074
     *           any necessary argument conversions, and arranges for any
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3075
     *           necessary return value conversions
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3076
     * @throws NullPointerException if either argument is null
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3077
     * @throws WrongMethodTypeException if the conversion cannot be made
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3078
     * @see MethodHandle#asType
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3079
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3080
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3081
    MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3082
        explicitCastArgumentsChecks(target, newType);
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3083
        // use the asTypeCache when possible:
26478
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  3084
        MethodType oldType = target.type();
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  3085
        if (oldType == newType)  return target;
285691ed55e4 8057656: Improve MethodType.isCastableTo() & MethodType.isConvertibleTo() checks
vlivanov
parents: 26477
diff changeset
  3086
        if (oldType.explicitCastEquivalentToAsType(newType)) {
27947
dba3bc0c087e 8066746: MHs.explicitCastArguments does incorrect type checks for VarargsCollector
vlivanov
parents: 27755
diff changeset
  3087
            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
  3088
        }
26474
655d08549e43 8050877: Improve code for pairwise argument conversions and value boxing/unboxing
vlivanov
parents: 26470
diff changeset
  3089
        return MethodHandleImpl.makePairwiseConvert(target, newType, false);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3090
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3091
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3092
    private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3093
        if (target.type().parameterCount() != newType.parameterCount()) {
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3094
            throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3095
        }
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3096
    }
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3097
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3098
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3099
     * 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
  3100
     * 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
  3101
     * 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
  3102
     * which is equal to the desired new type.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3103
     * <p>
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3104
     * The given array controls the reordering.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3105
     * 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
  3106
     * {@code newType.parameterCount()}, and call {@code #O} the number
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3107
     * of outgoing parameters (the value {@code target.type().parameterCount()}).
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3108
     * 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
  3109
     * 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
  3110
     * 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
  3111
     * 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
  3112
     * argument, where {@code I} is {@code reorder[N]}.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3113
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3114
     * No argument or return value conversions are applied.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3115
     * 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
  3116
     * 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
  3117
     * or parameters in the target method handle.
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3118
     * 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
  3119
     * type of the original target.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3120
     * <p>
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3121
     * The reordering array need not specify an actual permutation.
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3122
     * 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
  3123
     * 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
  3124
     * 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
  3125
     * 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
  3126
     * incoming arguments which are not mentioned in the reordering array
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3127
     * may be of any type, as determined only by {@code newType}.
18156
edb590d448c5 8016217: More javadoc warnings
alanb
parents: 16906
diff changeset
  3128
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3129
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
  3130
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
  3131
...
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3132
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
  3133
MethodType intfn2 = methodType(int.class, int.class, int.class);
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  3134
MethodHandle sub = ... (int x, int y) -> (x-y) ...;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3135
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
  3136
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
  3137
MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3138
assert((int)rsub.invokeExact(1, 100) == 99);
18569
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  3139
MethodHandle add = ... (int x, int y) -> (x+y) ...;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3140
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
  3141
MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3142
assert(twice.type().equals(intfn1));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3143
assert((int)twice.invokeExact(21) == 42);
18156
edb590d448c5 8016217: More javadoc warnings
alanb
parents: 16906
diff changeset
  3144
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3145
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3146
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3147
     * 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
  3148
     * @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
  3149
     * @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
  3150
     * @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
  3151
     * @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
  3152
     *           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
  3153
     * @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
  3154
     * @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
  3155
     *                  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
  3156
     *                  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
  3157
     *                  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
  3158
     *                  {@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
  3159
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3160
    public static
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3161
    MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3162
        reorder = reorder.clone();  // get a private copy
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3163
        MethodType oldType = target.type();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3164
        permuteArgumentChecks(reorder, newType, oldType);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3165
        // first detect dropped arguments and handle them separately
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3166
        int[] originalReorder = reorder;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3167
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3168
        LambdaForm form = result.form;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3169
        int newArity = newType.parameterCount();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3170
        // Normalize the reordering into a real permutation,
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3171
        // by removing duplicates and adding dropped elements.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3172
        // This somewhat improves lambda form caching, as well
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3173
        // as simplifying the transform by breaking it up into steps.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3174
        for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3175
            if (ddIdx > 0) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3176
                // We found a duplicated entry at reorder[ddIdx].
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3177
                // Example:  (x,y,z)->asList(x,y,z)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3178
                // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3179
                // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3180
                // The starred element corresponds to the argument
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3181
                // deleted by the dupArgumentForm transform.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3182
                int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3183
                boolean killFirst = false;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3184
                for (int val; (val = reorder[--dstPos]) != dupVal; ) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3185
                    // Set killFirst if the dup is larger than an intervening position.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3186
                    // This will remove at least one inversion from the permutation.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3187
                    if (dupVal > val) killFirst = true;
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3188
                }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3189
                if (!killFirst) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3190
                    srcPos = dstPos;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3191
                    dstPos = ddIdx;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3192
                }
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3193
                form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3194
                assert (reorder[srcPos] == reorder[dstPos]);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3195
                oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3196
                // contract the reordering by removing the element at dstPos
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3197
                int tailPos = dstPos + 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3198
                System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3199
                reorder = Arrays.copyOf(reorder, reorder.length - 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3200
            } else {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3201
                int dropVal = ~ddIdx, insPos = 0;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3202
                while (insPos < reorder.length && reorder[insPos] < dropVal) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3203
                    // Find first element of reorder larger than dropVal.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3204
                    // This is where we will insert the dropVal.
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3205
                    insPos += 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3206
                }
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3207
                Class<?> ptype = newType.parameterType(dropVal);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3208
                form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3209
                oldType = oldType.insertParameterTypes(insPos, ptype);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3210
                // expand the reordering by inserting an element at insPos
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3211
                int tailPos = insPos + 1;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3212
                reorder = Arrays.copyOf(reorder, reorder.length + 1);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3213
                System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3214
                reorder[insPos] = dropVal;
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3215
            }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3216
            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
  3217
        }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3218
        assert (reorder.length == newArity);  // a perfect permutation
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3219
        // 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
  3220
        form = form.editor().permuteArgumentsForm(1, reorder);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3221
        if (newType == result.type() && form == result.internalForm())
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3222
            return result;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3223
        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
  3224
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3225
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3226
    /**
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3227
     * 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
  3228
     * 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
  3229
     * 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
  3230
     * Otherwise, return zero.
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3231
     * 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
  3232
     */
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3233
    private static int findFirstDupOrDrop(int[] reorder, int newArity) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3234
        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
  3235
        if (newArity < BIT_LIMIT) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3236
            long mask = 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3237
            for (int i = 0; i < reorder.length; i++) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3238
                int arg = reorder[i];
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3239
                if (arg >= newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3240
                    return reorder.length;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3241
                }
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3242
                long bit = 1L << arg;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3243
                if ((mask & bit) != 0) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3244
                    return i;  // >0 indicates a dup
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3245
                }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3246
                mask |= bit;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3247
            }
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3248
            if (mask == (1L << newArity) - 1) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3249
                assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3250
                return 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3251
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3252
            // find first zero
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3253
            long zeroBit = Long.lowestOneBit(~mask);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3254
            int zeroPos = Long.numberOfTrailingZeros(zeroBit);
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3255
            assert(zeroPos <= newArity);
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3256
            if (zeroPos == newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3257
                return 0;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3258
            }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3259
            return ~zeroPos;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3260
        } else {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3261
            // same algorithm, different bit set
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3262
            BitSet mask = new BitSet(newArity);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3263
            for (int i = 0; i < reorder.length; i++) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3264
                int arg = reorder[i];
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3265
                if (arg >= newArity) {
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3266
                    return reorder.length;
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3267
                }
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3268
                if (mask.get(arg)) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3269
                    return i;  // >0 indicates a dup
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3270
                }
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3271
                mask.set(arg);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3272
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3273
            int zeroPos = mask.nextClearBit(0);
26626
14bb608ce64e 8058293: Bit set computation in MHs.findFirstDupOrDrop/findFirstDrop is broken
vlivanov
parents: 26625
diff changeset
  3274
            assert(zeroPos <= newArity);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3275
            if (zeroPos == newArity) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3276
                return 0;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3277
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3278
            return ~zeroPos;
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3279
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3280
    }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3281
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3282
    private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3283
        if (newType.returnType() != oldType.returnType())
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3284
            throw newIllegalArgumentException("return types do not match",
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3285
                    oldType, newType);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3286
        if (reorder.length == oldType.parameterCount()) {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3287
            int limit = newType.parameterCount();
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3288
            boolean bad = false;
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3289
            for (int j = 0; j < reorder.length; j++) {
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3290
                int i = reorder[j];
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3291
                if (i < 0 || i >= limit) {
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3292
                    bad = true; break;
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3293
                }
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3294
                Class<?> src = newType.parameterType(i);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3295
                Class<?> dst = oldType.parameterType(j);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3296
                if (src != dst)
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3297
                    throw newIllegalArgumentException("parameter types do not match after reorder",
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3298
                            oldType, newType);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3299
            }
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3300
            if (!bad)  return true;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3301
        }
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3302
        throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3303
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3304
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3305
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3306
     * 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
  3307
     * constant value every time it is invoked.
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3308
     * <p>
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3309
     * 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
  3310
     * 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
  3311
     * 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
  3312
     * <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
  3313
     * @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
  3314
     * @param value the value to return
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3315
     * @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
  3316
     * @throws NullPointerException if the {@code type} argument is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3317
     * @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
  3318
     * @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
  3319
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3320
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3321
    MethodHandle constant(Class<?> type, Object value) {
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3322
        if (type.isPrimitive()) {
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3323
            if (type == void.class)
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3324
                throw newIllegalArgumentException("void type");
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3325
            Wrapper w = Wrapper.forPrimitiveType(type);
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3326
            value = w.convert(value, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3327
            if (w.zero().equals(value))
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3328
                return zero(w, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3329
            return insertArguments(identity(type), 0, value);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3330
        } else {
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3331
            if (value == null)
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3332
                return zero(Wrapper.OBJECT, type);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3333
            return identity(type).bindTo(value);
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3334
        }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3335
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3336
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3337
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3338
     * 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
  3339
     * @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
  3340
     * @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
  3341
     * @throws NullPointerException if the argument is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3342
     * @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
  3343
     */
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3344
    public static
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3345
    MethodHandle identity(Class<?> type) {
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3346
        Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3347
        int pos = btw.ordinal();
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3348
        MethodHandle ident = IDENTITY_MHS[pos];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3349
        if (ident == null) {
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3350
            ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3351
        }
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3352
        if (ident.type().returnType() == type)
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3353
            return ident;
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3354
        // 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
  3355
        assert (btw == Wrapper.OBJECT);
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3356
        return makeIdentity(type);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3357
    }
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3358
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
     * 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
  3361
     * 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
  3362
     * 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
  3363
     * <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
  3364
     * 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
  3365
     * 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
  3366
     * @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
  3367
     * @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
  3368
     *         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
  3369
     * @throws NullPointerException if the argument is null
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3370
     * @see MethodHandles#constant
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3371
     * @see MethodHandles#empty
38774
b2ca0c2ec115 8156868: MethodHandles.zero(Class) doc issues
mhaupt
parents: 38472
diff changeset
  3372
     * @see MethodHandles#explicitCastArguments
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3373
     * @since 9
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3374
     */
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3375
    public static MethodHandle zero(Class<?> type) {
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3376
        Objects.requireNonNull(type);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3377
        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
  3378
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3379
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3380
    private static MethodHandle identityOrVoid(Class<?> type) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3381
        return type == void.class ? zero(type) : identity(type);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3382
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3383
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3384
    /**
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3385
     * 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
  3386
     * 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
  3387
     * 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
  3388
     * <p>The returned method handle is equivalent to
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3389
     * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  3390
     *
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3391
     * @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
  3392
     * {@code guardWithTest(pred, target, empty(target.type())}.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3393
     * @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
  3394
     * @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
  3395
     * @throws NullPointerException if the argument is null
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3396
     * @see MethodHandles#zero
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3397
     * @see MethodHandles#constant
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3398
     * @since 9
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3399
     */
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3400
    public static  MethodHandle empty(MethodType type) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3401
        Objects.requireNonNull(type);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3402
        return dropArguments(zero(type.returnType()), 0, type.parameterList());
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3403
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3404
40256
c5e03eaf7ba2 8163370: Reduce number of classes loaded by common usage of java.lang.invoke
redestad
parents: 40175
diff changeset
  3405
    private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3406
    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
  3407
        MethodType mtype = methodType(ptype, ptype);
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3408
        LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3409
        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3410
    }
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3411
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3412
    private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3413
        int pos = btw.ordinal();
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3414
        MethodHandle zero = ZERO_MHS[pos];
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3415
        if (zero == null) {
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3416
            zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3417
        }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3418
        if (zero.type().returnType() == rtype)
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3419
            return zero;
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3420
        assert(btw == Wrapper.OBJECT);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3421
        return makeZero(rtype);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3422
    }
40256
c5e03eaf7ba2 8163370: Reduce number of classes loaded by common usage of java.lang.invoke
redestad
parents: 40175
diff changeset
  3423
    private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3424
    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
  3425
        MethodType mtype = methodType(rtype);
26476
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3426
        LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3427
        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3428
    }
2b814465aaa3 8050887: Intrinsify constants for default values
vlivanov
parents: 26475
diff changeset
  3429
32649
2ee9017c7597 8136583: Core libraries should use blessed modifier order
martin
parents: 29094
diff changeset
  3430
    private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
26475
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3431
        // Simulate a CAS, to avoid racy duplication of results.
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3432
        MethodHandle prev = cache[pos];
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3433
        if (prev != null) return prev;
acf0c98309d3 8050884: Intrinsify ValueConversions.identity() functions
vlivanov
parents: 26474
diff changeset
  3434
        return cache[pos] = value;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3435
    }
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3436
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3437
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3438
     * 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
  3439
     * 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
  3440
     * 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
  3441
     * 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
  3442
     * 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
  3443
     * 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
  3444
     * 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
  3445
     * and calls the original target.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3446
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3447
     * 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
  3448
     * 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
  3449
     * 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
  3450
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3451
     * 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
  3452
     * 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
  3453
     * 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
  3454
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3455
     * 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
  3456
     * 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
  3457
     * 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
  3458
     * and <i>L</i> is the length of the values array.
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3459
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3460
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3461
     * 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
  3462
     * @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
  3463
     * @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
  3464
     * @param values the series of arguments to insert
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3465
     * @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
  3466
     *         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
  3467
     * @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
  3468
     * @see MethodHandle#bindTo
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3469
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3470
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3471
    MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3472
        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
  3473
        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
  3474
        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
  3475
        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
  3476
        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
  3477
            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
  3478
            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
  3479
            if (ptype.isPrimitive()) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3480
                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
  3481
            } else {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3482
                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
  3483
                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
  3484
            }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3485
        }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3486
        return result;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3487
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3488
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3489
    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
  3490
                                                             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
  3491
        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
  3492
        // 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
  3493
        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
  3494
        switch (w) {
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3495
        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
  3496
        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
  3497
        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
  3498
        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
  3499
        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
  3500
        }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3501
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3502
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3503
    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
  3504
        MethodType oldType = target.type();
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3505
        int outargs = oldType.parameterCount();
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3506
        int inargs  = outargs - insCount;
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3507
        if (inargs < 0)
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3508
            throw newIllegalArgumentException("too many values to insert");
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3509
        if (pos < 0 || pos > inargs)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3510
            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
  3511
        return oldType.ptypes();
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3512
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3513
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3514
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3515
     * 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
  3516
     * 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
  3517
     * 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
  3518
     * 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
  3519
     * at some given position.
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3520
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3521
     * 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
  3522
     * 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
  3523
     * 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
  3524
     * 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
  3525
     * they will come after.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3526
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3527
     * <b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3528
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3529
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3530
import static java.lang.invoke.MethodType.*;
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3531
...
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3532
MethodHandle cat = lookup().findVirtual(String.class,
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3533
  "concat", methodType(String.class, String.class));
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3534
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
  3535
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
  3536
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
  3537
assertEquals(bigType, d0.type());
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3538
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
  3539
     * }</pre></blockquote>
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3540
     * <p>
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3541
     * This method is also equivalent to the following code:
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3542
     * <blockquote><pre>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3543
     * {@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
  3544
     * </pre></blockquote>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3545
     * @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
  3546
     * @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
  3547
     * @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
  3548
     * @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
  3549
     *         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
  3550
     * @throws NullPointerException if the target is null,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3551
     *                              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
  3552
     * @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
  3553
     *                  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
  3554
     *                  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
  3555
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3556
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3557
    MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
40272
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  3558
        return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
39755
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3559
    }
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3560
40272
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  3561
    private static List<Class<?>> copyTypes(Object[] array) {
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  3562
        return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
39755
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3563
    }
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3564
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3565
    private static
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3566
    MethodHandle dropArguments0(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
  3567
        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
  3568
        int dropped = dropArgumentChecks(oldType, pos, valueTypes);
26625
cbeb3711fa94 8058291: Missing some checks during parameter validation
vlivanov
parents: 26482
diff changeset
  3569
        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
  3570
        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
  3571
        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
  3572
        LambdaForm lform = result.form;
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3573
        int insertFormArg = 1 + pos;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3574
        for (Class<?> ptype : valueTypes) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3575
            lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3576
        }
26469
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3577
        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
  3578
        return result;
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3579
    }
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3580
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3581
    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
  3582
        int dropped = valueTypes.size();
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3583
        MethodType.checkSlotCount(dropped);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3584
        int outargs = oldType.parameterCount();
13423
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  3585
        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
  3586
        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
  3587
            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
  3588
                    + 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
  3589
                    );
e6bc14fae1cf 8050166: Get rid of some package-private methods on arguments in j.l.i.MethodHandle
vlivanov
parents: 26468
diff changeset
  3590
        return dropped;
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3591
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  3592
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3593
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3594
     * 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
  3595
     * 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
  3596
     * 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
  3597
     * 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
  3598
     * at some given position.
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3599
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3600
     * 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
  3601
     * 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
  3602
     * 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
  3603
     * 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
  3604
     * they will come after.
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3605
     * @apiNote
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3606
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3607
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3608
import static java.lang.invoke.MethodType.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3609
...
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3610
MethodHandle cat = lookup().findVirtual(String.class,
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3611
  "concat", methodType(String.class, String.class));
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3612
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
  3613
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
  3614
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
  3615
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
  3616
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
  3617
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
  3618
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
  3619
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
  3620
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
  3621
     * }</pre></blockquote>
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3622
     * <p>
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3623
     * This method is also equivalent to the following code:
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3624
     * <blockquote><pre>
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3625
     * {@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
  3626
     * </pre></blockquote>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3627
     * @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
  3628
     * @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
  3629
     * @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
  3630
     * @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
  3631
     *         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
  3632
     * @throws NullPointerException if the target is null,
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3633
     *                              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
  3634
     * @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
  3635
     *                  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
  3636
     *                  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
  3637
     *                  <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
  3638
     */
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3639
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3640
    MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
40272
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  3641
        return dropArguments0(target, pos, copyTypes(valueTypes));
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3642
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3643
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3644
    // 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
  3645
    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
  3646
                                      boolean nullOnFailure) {
40272
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  3647
        newTypes = copyTypes(newTypes.toArray());
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3648
        List<Class<?>> oldTypes = target.type().parameterList();
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3649
        int match = oldTypes.size();
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3650
        if (skip != 0) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3651
            if (skip < 0 || skip > match) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3652
                throw newIllegalArgumentException("illegal skip", skip, target);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3653
            }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3654
            oldTypes = oldTypes.subList(skip, match);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3655
            match -= skip;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3656
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3657
        List<Class<?>> addTypes = newTypes;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3658
        int add = addTypes.size();
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3659
        if (pos != 0) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3660
            if (pos < 0 || pos > add) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3661
                throw newIllegalArgumentException("illegal pos", pos, newTypes);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3662
            }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3663
            addTypes = addTypes.subList(pos, add);
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3664
            add -= pos;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3665
            assert(addTypes.size() == add);
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3666
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3667
        // 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
  3668
        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
  3669
            if (nullOnFailure) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3670
                return null;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3671
            }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3672
            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
  3673
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3674
        addTypes = addTypes.subList(match, add);
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3675
        add -= match;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3676
        assert(addTypes.size() == add);
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3677
        // newTypes:     (   P*[pos], M*[match], A*[add] )
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3678
        // target: ( S*[skip],        M*[match]  )
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3679
        MethodHandle adapter = target;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3680
        if (add > 0) {
39755
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3681
            adapter = dropArguments0(adapter, skip+ match, addTypes);
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3682
        }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3683
        // adapter: (S*[skip],        M*[match], A*[add] )
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3684
        if (pos > 0) {
39755
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  3685
            adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3686
        }
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3687
        // 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
  3688
        return adapter;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3689
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3690
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3691
    /**
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3692
     * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3693
     * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3694
     * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3695
     * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3696
     * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3697
     * {@link #dropArguments(MethodHandle, int, Class[])}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3698
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3699
     * The resulting handle will have the same return type as the target handle.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3700
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3701
     * In more formal terms, assume these two type lists:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3702
     * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3703
     * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3704
     * {@code newTypes}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3705
     * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3706
     * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3707
     * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3708
     * sub-list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3709
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3710
     * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3711
     * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3712
     * {@link #dropArguments(MethodHandle, int, Class[])}.
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  3713
     *
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3714
     * @apiNote
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3715
     * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3716
     * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3717
     * <blockquote><pre>{@code
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3718
import static java.lang.invoke.MethodHandles.*;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3719
import static java.lang.invoke.MethodType.*;
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3720
...
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3721
...
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3722
MethodHandle h0 = constant(boolean.class, true);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3723
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
  3724
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
  3725
MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3726
if (h1.type().parameterCount() < h2.type().parameterCount())
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3727
    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
  3728
else
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3729
    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
  3730
MethodHandle h3 = guardWithTest(h0, h1, h2);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3731
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
  3732
     * }</pre></blockquote>
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3733
     * @param target the method handle to adapt
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3734
     * @param skip number of targets parameters to disregard (they will be unchanged)
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3735
     * @param newTypes the list of types to match {@code target}'s parameter type list to
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3736
     * @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
  3737
     * @return a possibly adapted method handle
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3738
     * @throws NullPointerException if either argument is null
38785
dacdc5add5eb 8158171: MethodHandles.dropArgumentsToMatch(...) non-documented IAE
srastogi
parents: 38774
diff changeset
  3739
     * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
39488
8dee5a37bdc7 8158169: MethodHandles.dropArgumentsToMatch(...)
srastogi
parents: 39476
diff changeset
  3740
     *         or if {@code skip} is negative or greater than the arity of the target,
8dee5a37bdc7 8158169: MethodHandles.dropArgumentsToMatch(...)
srastogi
parents: 39476
diff changeset
  3741
     *         or if {@code pos} is negative or greater than the newTypes list size,
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3742
     *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  3743
     *         {@code pos}.
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3744
     * @since 9
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3745
     */
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3746
    public static
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3747
    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
  3748
        Objects.requireNonNull(target);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3749
        Objects.requireNonNull(newTypes);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3750
        return dropArgumentsToMatch(target, skip, newTypes, pos, false);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3751
    }
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  3752
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3753
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3754
     * Adapts a target method handle by pre-processing
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3755
     * 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
  3756
     * 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
  3757
     * replaced by the result of its corresponding filter function.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3758
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3759
     * 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
  3760
     * 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
  3761
     * 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
  3762
     * argument of the target, and so on in sequence.
48544
050352ed64d5 8194554: filterArguments runs multiple filters in the wrong order
mchung
parents: 47856
diff changeset
  3763
     * The filter functions are invoked in left to right order.
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3764
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  3765
     * 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
  3766
     * and the corresponding arguments left unchanged.
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3767
     * (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
  3768
     * 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
  3769
     * <p>
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3770
     * 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
  3771
     * 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
  3772
     * 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
  3773
     * replaces the corresponding argument type of the target
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3774
     * in the resulting adapted method handle.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3775
     * 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
  3776
     * parameter type of the target.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3777
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3778
     * 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
  3779
     * (null or not)
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3780
     * 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
  3781
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3782
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3783
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  3784
import static java.lang.invoke.MethodType.*;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3785
...
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3786
MethodHandle cat = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3787
  "concat", methodType(String.class, String.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3788
MethodHandle upcase = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3789
  "toUpperCase", methodType(String.class));
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3790
assertEquals("xy", (String) cat.invokeExact("x", "y"));
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3791
MethodHandle f0 = filterArguments(cat, 0, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3792
assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3793
MethodHandle f1 = filterArguments(cat, 1, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3794
assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3795
MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  3796
assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3797
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3798
     * <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
  3799
     * 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
  3800
     * {@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
  3801
     * 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
  3802
     * {@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
  3803
     * 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
  3804
     * 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
  3805
     * {@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
  3806
     * the resulting adapter.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3807
     * <blockquote><pre>{@code
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3808
     * 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
  3809
     * 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
  3810
     * 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
  3811
     *   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
  3812
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3813
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3814
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3815
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3816
     * 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
  3817
     *
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3818
     * @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
  3819
     * @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
  3820
     * @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
  3821
     * @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
  3822
     * @throws NullPointerException if the target is null
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3823
     *                              or if the {@code filters} array is null
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3824
     * @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
  3825
     *          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
  3826
     *          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
  3827
     *          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
  3828
     *          <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
  3829
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3830
    public static
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  3831
    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
  3832
        filterArgumentsCheckArity(target, pos, filters);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3833
        MethodHandle adapter = target;
48544
050352ed64d5 8194554: filterArguments runs multiple filters in the wrong order
mchung
parents: 47856
diff changeset
  3834
        // process filters in reverse order so that the invocation of
050352ed64d5 8194554: filterArguments runs multiple filters in the wrong order
mchung
parents: 47856
diff changeset
  3835
        // the resulting adapter will invoke the filters in left-to-right order
050352ed64d5 8194554: filterArguments runs multiple filters in the wrong order
mchung
parents: 47856
diff changeset
  3836
        for (int i = filters.length - 1; i >= 0; --i) {
050352ed64d5 8194554: filterArguments runs multiple filters in the wrong order
mchung
parents: 47856
diff changeset
  3837
            MethodHandle filter = filters[i];
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  3838
            if (filter == null)  continue;  // ignore null elements of filters
48544
050352ed64d5 8194554: filterArguments runs multiple filters in the wrong order
mchung
parents: 47856
diff changeset
  3839
            adapter = filterArgument(adapter, pos + i, filter);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3840
        }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3841
        return adapter;
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3842
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  3843
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3844
    /*non-public*/ static
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3845
    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
  3846
        filterArgumentChecks(target, pos, filter);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3847
        MethodType targetType = target.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3848
        MethodType filterType = filter.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3849
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3850
        Class<?> newParamType = filterType.parameterType(0);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3851
        LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3852
        MethodType newType = targetType.changeParameterType(pos, newParamType);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3853
        result = result.copyWithExtendL(newType, lform, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3854
        return result;
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3855
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3856
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3857
    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
  3858
        MethodType targetType = target.type();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3859
        int maxPos = targetType.parameterCount();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3860
        if (pos + filters.length > maxPos)
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3861
            throw newIllegalArgumentException("too many filters");
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3862
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3863
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  3864
    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
  3865
        MethodType targetType = target.type();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3866
        MethodType filterType = filter.type();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3867
        if (filterType.parameterCount() != 1
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3868
            || filterType.returnType() != targetType.parameterType(pos))
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3869
            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3870
    }
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  3871
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3872
    /**
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3873
     * Adapts a target method handle by pre-processing
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3874
     * 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
  3875
     * 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
  3876
     * filter function.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3877
     * 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
  3878
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3879
     * 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
  3880
     * 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
  3881
     * any arguments not passed to the filter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3882
     * 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
  3883
     * not passed to the filter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3884
     * 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
  3885
     * 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
  3886
     * passed to the adapter.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3887
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3888
     * The argument types (if any) of the filter
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3889
     * 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
  3890
     * in the resulting adapted method handle.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3891
     * 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
  3892
     * 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
  3893
     * 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
  3894
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3895
     * 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
  3896
     * {@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
  3897
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  3898
     * <blockquote><pre>{@code
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3899
import static java.lang.invoke.MethodHandles.*;
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3900
import static java.lang.invoke.MethodType.*;
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3901
...
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3902
MethodHandle deepToString = publicLookup()
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3903
  .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
  3904
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3905
MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3906
assertEquals("[strange]", (String) ts1.invokeExact("strange"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3907
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3908
MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3909
assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3910
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3911
MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3912
MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3913
assertEquals("[top, [up, down], strange]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3914
             (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3915
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3916
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
  3917
assertEquals("[top, [up, down], [strange]]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3918
             (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
  3919
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3920
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
  3921
assertEquals("[top, [[up, down, strange], charm], bottom]",
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3922
             (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
  3923
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3924
     * <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
  3925
     * 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
  3926
     * {@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
  3927
     * {@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
  3928
     * the {@code target}, respectively, unless {@code V} is {@code void}.
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3929
     * {@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
  3930
     * and values preceding and following the collection position, {@code pos},
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3931
     * 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
  3932
     * adapter's signature and arguments, where they surround
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3933
     * {@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
  3934
     * to the {@code filter} (if any).
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3935
     * <blockquote><pre>{@code
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3936
     * T target(A...,V,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3937
     * V filter(B...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3938
     * T adapter(A... a,B... b,C... c) {
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3939
     *   V v = filter(b...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3940
     *   return target(a...,v,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3941
     * }
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3942
     * // and if the filter has no arguments:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3943
     * T target2(A...,V,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3944
     * V filter2();
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3945
     * T adapter2(A... a,C... c) {
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3946
     *   V v = filter2();
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3947
     *   return target2(a...,v,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3948
     * }
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3949
     * // and if the filter has a void return:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3950
     * T target3(A...,C...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3951
     * void filter3(B...);
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  3952
     * 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
  3953
     *   filter3(b...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3954
     *   return target3(a...,c...);
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3955
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  3956
     * }</pre></blockquote>
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3957
     * <p>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3958
     * 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
  3959
     * 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
  3960
     * steps as follows:
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3961
     * <blockquote><pre>{@code
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3962
     * 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
  3963
     * mh = MethodHandles.foldArguments(mh, coll); //step 1
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3964
     * }</pre></blockquote>
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3965
     * 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
  3966
     * (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
  3967
     * is equivalent to {@code filterReturnValue(coll, mh)}.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3968
     * 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
  3969
     * 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
  3970
     * is equivalent to {@code filterArguments(mh, N, coll)}.
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3971
     * Other equivalences are possible but would require argument permutation.
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3972
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3973
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  3974
     * 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
  3975
     *
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3976
     * @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
  3977
     * @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
  3978
     *            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
  3979
     * @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
  3980
     * @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
  3981
     * @throws NullPointerException if either argument is null
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3982
     * @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
  3983
     *          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
  3984
     *          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
  3985
     *          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
  3986
     *          <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
  3987
     * @see MethodHandles#foldArguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3988
     * @see MethodHandles#filterArguments
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3989
     * @see MethodHandles#filterReturnValue
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3990
     */
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3991
    public static
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  3992
    MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  3993
        MethodType newType = collectArgumentsChecks(target, pos, filter);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3994
        MethodType collectorType = filter.type();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3995
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3996
        LambdaForm lform;
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3997
        if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3998
            lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  3999
            if (lform != null) {
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4000
                return result.copyWith(newType, lform);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4001
            }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4002
        }
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4003
        lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4004
        return result.copyWithExtendL(newType, lform, filter);
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4005
    }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4006
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4007
    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
  4008
        MethodType targetType = target.type();
20533
bee974bc42ac 8001110: method handles should have a collectArguments transform, generalizing asCollector
jrose
parents: 20532
diff changeset
  4009
        MethodType filterType = filter.type();
26482
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4010
        Class<?> rtype = filterType.returnType();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4011
        List<Class<?>> filterArgs = filterType.parameterList();
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4012
        if (rtype == void.class) {
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4013
            return targetType.insertParameterTypes(pos, filterArgs);
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4014
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4015
        if (rtype != targetType.parameterType(pos)) {
13610
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  4016
            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
  4017
        }
cea1ab1c3ac7 8057922: Improve LambdaForm sharing by using LambdaFormEditor more extensively
vlivanov
parents: 26478
diff changeset
  4018
        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
  4019
    }
28122b96858e 7191102: nightly failures after JSR 292 lazy method handle update (round 3)
jrose
parents: 13423
diff changeset
  4020
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4021
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4022
     * 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
  4023
     * 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
  4024
     * 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
  4025
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4026
     * 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
  4027
     * its only argument.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4028
     * 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
  4029
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4030
     * The return type of the filter
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4031
     * replaces the return type of the target
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4032
     * 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
  4033
     * 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
  4034
     * return type of the target.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4035
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  4036
     * <blockquote><pre>{@code
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  4037
import static java.lang.invoke.MethodHandles.*;
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  4038
import static java.lang.invoke.MethodType.*;
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4039
...
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4040
MethodHandle cat = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4041
  "concat", methodType(String.class, String.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4042
MethodHandle length = lookup().findVirtual(String.class,
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4043
  "length", methodType(int.class));
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4044
System.out.println((String) cat.invokeExact("x", "y")); // xy
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4045
MethodHandle f0 = filterReturnValue(cat, length);
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4046
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
  4047
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4048
     * <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
  4049
     * {@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
  4050
     * {@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
  4051
     * {@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
  4052
     * 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
  4053
     * <blockquote><pre>{@code
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4054
     * T target(A...);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4055
     * V filter(T);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4056
     * V adapter(A... a) {
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4057
     *   T t = target(a...);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4058
     *   return filter(t);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4059
     * }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4060
     * // 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
  4061
     * void target2(A...);
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4062
     * V filter2();
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4063
     * V adapter2(A... a) {
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4064
     *   target2(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4065
     *   return filter2();
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4066
     * }
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4067
     * // and if the filter has a void return:
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4068
     * T target3(A...);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4069
     * void filter3(V);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4070
     * void adapter3(A... a) {
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4071
     *   T t = target3(a...);
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4072
     *   filter3(t);
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4073
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4074
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4075
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4076
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4077
     * 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
  4078
     * @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
  4079
     * @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
  4080
     * @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
  4081
     * @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
  4082
     * @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
  4083
     *          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
  4084
     */
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4085
    public static
7554
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  4086
    MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  4087
        MethodType targetType = target.type();
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  4088
        MethodType filterType = filter.type();
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4089
        filterReturnValueChecks(targetType, filterType);
27755
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4090
        BoundMethodHandle result = target.rebind();
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4091
        BasicType rtype = BasicType.basicType(filterType.returnType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4092
        LambdaForm lform = result.editor().filterReturnForm(rtype, false);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4093
        MethodType newType = targetType.changeReturnType(filterType.returnType());
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4094
        result = result.copyWithExtendL(newType, lform, filter);
baf8735fc8bf 8063135: Enable full LF sharing by default
vlivanov
parents: 26626
diff changeset
  4095
        return result;
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4096
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4097
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4098
    private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  4099
        Class<?> rtype = targetType.returnType();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  4100
        int filterValues = filterType.parameterCount();
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  4101
        if (filterValues == 0
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  4102
                ? (rtype != void.class)
39756
c50c31af8cd9 8158571: Additional method handle validation
mhaupt
parents: 39755
diff changeset
  4103
                : (rtype != filterType.parameterType(0) || filterValues != 1))
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4104
            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
  4105
    }
8a0ad9757002 6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions
jrose
parents: 7053
diff changeset
  4106
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4107
    /**
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4108
     * Adapts a target method handle by pre-processing
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4109
     * 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
  4110
     * 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
  4111
     * sequence of arguments.
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4112
     * <p>
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4113
     * 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
  4114
     * 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
  4115
     * 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
  4116
     * (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
  4117
     * 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
  4118
     * 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
  4119
     * arguments.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4120
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4121
     * 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
  4122
     * 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
  4123
     * {@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
  4124
     * of the combiner.
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4125
     * <p>
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4126
     * 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
  4127
     * 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
  4128
     * 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
  4129
     * <p>
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4130
     * 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
  4131
     * first parameter type is dropped,
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4132
     * 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
  4133
     * <p>
7555
a279ebc3b25c 6981777: implement JSR 292 EG adjustments from summer 2010
jrose
parents: 7554
diff changeset
  4134
     * (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
  4135
     * 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
  4136
     * 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
  4137
     * 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
  4138
     * 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
  4139
     * target.)
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4140
     * <p><b>Example:</b>
20877
83ea903d5cf1 8026183: minor documentation problems in java.lang.invoke
rriggs
parents: 20853
diff changeset
  4141
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4142
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
  4143
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
  4144
...
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4145
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
  4146
  "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
  4147
    .bindTo(System.out);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4148
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
  4149
  "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
  4150
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
  4151
MethodHandle catTrace = foldArguments(cat, trace);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4152
// also prints "boo":
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4153
assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4154
     * }</pre></blockquote>
36114
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4155
     * <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
  4156
     * 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
  4157
     * {@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
  4158
     * 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
  4159
     * 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
  4160
     * 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
  4161
     * 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
  4162
     * {@code target} parameters and arguments that follow the folded parameters
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4163
     * and arguments.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4164
     * <blockquote><pre>{@code
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4165
     * // there are N arguments in A...
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4166
     * T target(V, A[N]..., B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4167
     * V combiner(A...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4168
     * T adapter(A... a, B... b) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4169
     *   V v = combiner(a...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4170
     *   return target(v, a..., b...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4171
     * }
9752
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4172
     * // 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
  4173
     * T target2(A[N]..., B...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4174
     * void combiner2(A...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4175
     * 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
  4176
     *   combiner2(a...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4177
     *   return target2(a..., b...);
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4178
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4179
     * }</pre></blockquote>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4180
     * <p>
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4181
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  4182
     * 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
  4183
     * @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
  4184
     * @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
  4185
     * @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
  4186
     * @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
  4187
     * @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
  4188
     *          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
  4189
     *          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
  4190
     *          of the target
88ab34b6da6d 7032323: code changes for JSR 292 EG adjustments to API, through Public Review
jrose
parents: 9731
diff changeset
  4191
     *          (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
  4192
     *          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
  4193
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4194
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4195
    MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4196
        return foldArguments(target, 0, combiner);
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4197
    }
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4198
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4199
    /**
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4200
     * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4201
     * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4202
     * before the folded arguments.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4203
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4204
     * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4205
     * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4206
     * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4207
     * 0.
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  4208
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4209
     * @apiNote Example:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4210
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4211
    import static java.lang.invoke.MethodHandles.*;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4212
    import static java.lang.invoke.MethodType.*;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4213
    ...
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4214
    MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4215
    "println", methodType(void.class, String.class))
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4216
    .bindTo(System.out);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4217
    MethodHandle cat = lookup().findVirtual(String.class,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4218
    "concat", methodType(String.class, String.class));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4219
    assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4220
    MethodHandle catTrace = foldArguments(cat, 1, trace);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4221
    // also prints "jum":
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4222
    assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4223
     * }</pre></blockquote>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4224
     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4225
     * represents the result type of the {@code target} and resulting adapter.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4226
     * {@code V}/{@code v} represent the type and value of the parameter and argument
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4227
     * of {@code target} that precedes the folding position; {@code V} also is
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4228
     * the result type of the {@code combiner}. {@code A}/{@code a} denote the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4229
     * types and values of the {@code N} parameters and arguments at the folding
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4230
     * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4231
     * and values of the {@code target} parameters and arguments that precede and
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4232
     * follow the folded parameters and arguments starting at {@code pos},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4233
     * respectively.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4234
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4235
     * // there are N arguments in A...
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4236
     * T target(Z..., V, A[N]..., B...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4237
     * V combiner(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4238
     * T adapter(Z... z, A... a, B... b) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4239
     *   V v = combiner(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4240
     *   return target(z..., v, a..., b...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4241
     * }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4242
     * // and if the combiner has a void return:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4243
     * T target2(Z..., A[N]..., B...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4244
     * void combiner2(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4245
     * T adapter2(Z... z, A... a, B... b) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4246
     *   combiner2(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4247
     *   return target2(z..., a..., b...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4248
     * }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4249
     * }</pre></blockquote>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4250
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4251
     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4252
     * variable-arity method handle}, even if the original target method handle was.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4253
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4254
     * @param target the method handle to invoke after arguments are combined
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4255
     * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4256
     *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4257
     * @param combiner method handle to call initially on the incoming arguments
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4258
     * @return method handle which incorporates the specified argument folding logic
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4259
     * @throws NullPointerException if either argument is null
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4260
     * @throws IllegalArgumentException if either of the following two conditions holds:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4261
     *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4262
     *              {@code pos} of the target signature;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4263
     *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4264
     *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4265
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4266
     * @see #foldArguments(MethodHandle, MethodHandle)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4267
     * @since 9
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4268
     */
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4269
    public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4270
        MethodType targetType = target.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4271
        MethodType combinerType = combiner.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4272
        Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4273
        BoundMethodHandle result = target.rebind();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4274
        boolean dropResult = rtype == void.class;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4275
        LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4276
        MethodType newType = targetType;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4277
        if (!dropResult) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4278
            newType = newType.dropParameterTypes(pos, pos + 1);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4279
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4280
        result = result.copyWithExtendL(newType, lform, combiner);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4281
        return result;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4282
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4283
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4284
    /**
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4285
     * As {@see foldArguments(MethodHandle, int, MethodHandle)}, but with the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4286
     * added capability of selecting the arguments from the targets parameters
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4287
     * to call the combiner with. This allows us to avoid some simple cases of
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4288
     * permutations and padding the combiner with dropArguments to select the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4289
     * right argument, which may ultimately produce fewer intermediaries.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4290
     */
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4291
    static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner, int ... argPositions) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4292
        MethodType targetType = target.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4293
        MethodType combinerType = combiner.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4294
        Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType, argPositions);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4295
        BoundMethodHandle result = target.rebind();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4296
        boolean dropResult = rtype == void.class;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4297
        LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType(), argPositions);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4298
        MethodType newType = targetType;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4299
        if (!dropResult) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4300
            newType = newType.dropParameterTypes(pos, pos + 1);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4301
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4302
        result = result.copyWithExtendL(newType, lform, combiner);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4303
        return result;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4304
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4305
26477
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4306
    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
  4307
        int foldArgs   = combinerType.parameterCount();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4308
        Class<?> rtype = combinerType.returnType();
e095a2b8a1f8 8057654: Extract checks performed during MethodHandle construction into separate methods
vlivanov
parents: 26476
diff changeset
  4309
        int foldVals = rtype == void.class ? 0 : 1;
9646
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  4310
        int afterInsertPos = foldPos + foldVals;
5ebbe5ab084f 6939861: JVM should handle more conversion operations
jrose
parents: 9645
diff changeset
  4311
        boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
40272
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4312
        if (ok) {
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4313
            for (int i = 0; i < foldArgs; i++) {
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4314
                if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4315
                    ok = false;
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4316
                    break;
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4317
                }
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4318
            }
6af4511ee5a4 8163878: Remove unnecessary bridge methods, allocations in java.lang.invoke
redestad
parents: 40256
diff changeset
  4319
        }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4320
        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
  4321
            ok = false;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4322
        if (!ok)
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4323
            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
  4324
        return rtype;
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4325
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4326
40810
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4327
    private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType, int ... argPos) {
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4328
        int foldArgs = combinerType.parameterCount();
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4329
        if (argPos.length != foldArgs) {
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4330
            throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4331
        }
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4332
        Class<?> rtype = combinerType.returnType();
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4333
        int foldVals = rtype == void.class ? 0 : 1;
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4334
        boolean ok = true;
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4335
        for (int i = 0; i < foldArgs; i++) {
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4336
            int arg = argPos[i];
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4337
            if (arg < 0 || arg > targetType.parameterCount()) {
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4338
                throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4339
            }
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4340
            if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4341
                throw newIllegalArgumentException("target argument type at position " + arg
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4342
                        + " must match combiner argument type at index " + i + ": " + targetType
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4343
                        + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4344
            }
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4345
        }
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4346
        if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) {
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4347
            ok = false;
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4348
        }
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4349
        if (!ok)
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4350
            throw misMatchedTypes("target and combiner types", targetType, combinerType);
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4351
        return rtype;
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4352
    }
b88d5910ea1e 8165492: Reduce number of lambda forms generated by MethodHandleInlineCopyStrategy
redestad
parents: 40732
diff changeset
  4353
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4354
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  4355
     * 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
  4356
     * 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
  4357
     * 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
  4358
     * All three method handles must have the same corresponding
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4359
     * 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
  4360
     * 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
  4361
     * 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
  4362
     * <p>
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4363
     * 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
  4364
     * represents the uniform result type of the three involved handles;
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4365
     * {@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
  4366
     * 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
  4367
     * {@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
  4368
     * 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
  4369
     * <blockquote><pre>{@code
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4370
     * boolean test(A...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4371
     * T target(A...,B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4372
     * T fallback(A...,B...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4373
     * T adapter(A... a,B... b) {
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4374
     *   if (test(a...))
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4375
     *     return target(a..., b...);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4376
     *   else
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4377
     *     return fallback(a..., b...);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4378
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4379
     * }</pre></blockquote>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4380
     * 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
  4381
     * 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
  4382
     * 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
  4383
     * @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
  4384
     * @param target method handle to call if test passes
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4385
     * @param fallback method handle to call if test fails
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4386
     * @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
  4387
     * @throws NullPointerException if any argument is null
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4388
     * @throws IllegalArgumentException if {@code test} does not return boolean,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4389
     *          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
  4390
     *          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
  4391
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4392
    public static
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4393
    MethodHandle guardWithTest(MethodHandle test,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4394
                               MethodHandle target,
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4395
                               MethodHandle fallback) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4396
        MethodType gtype = test.type();
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4397
        MethodType ttype = target.type();
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4398
        MethodType ftype = fallback.type();
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4399
        if (!ttype.equals(ftype))
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4400
            throw misMatchedTypes("target and fallback types", ttype, ftype);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4401
        if (gtype.returnType() != boolean.class)
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4402
            throw newIllegalArgumentException("guard type is not a predicate "+gtype);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4403
        List<Class<?>> targs = ttype.parameterList();
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4404
        test = dropArgumentsToMatch(test, 0, targs, 0, true);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4405
        if (test == null) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4406
            throw misMatchedTypes("target and test types", ttype, gtype);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4407
        }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  4408
        return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4409
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4410
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4411
    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
  4412
        return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4413
    }
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4414
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4415
    /**
8822
8145ab9f5f86 7012648: move JSR 292 to package java.lang.invoke and adjust names
jrose
parents: 8821
diff changeset
  4416
     * 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
  4417
     * by running it inside an exception handler.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4418
     * 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
  4419
     * 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
  4420
     * 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
  4421
     * <p>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4422
     * The target and handler must have the same corresponding
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4423
     * 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
  4424
     * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4425
     * 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
  4426
     * <p>
a5ed9456c9be 8143410: augment pseudo-code descriptions in MethodHandles API
mhaupt
parents: 36112
diff changeset
  4427
     * 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
  4428
     * 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
  4429
     * 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
  4430
     * 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
  4431
     * {@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
  4432
     * resulting handle discarded by {@code handler}.
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4433
     * <blockquote><pre>{@code
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4434
     * T target(A..., B...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4435
     * T handler(ExType, A...);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4436
     * T adapter(A... a, B... b) {
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4437
     *   try {
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4438
     *     return target(a..., b...);
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4439
     *   } catch (ExType ex) {
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4440
     *     return handler(ex, a...);
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4441
     *   }
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4442
     * }
20535
cc85c8626435 8024438: JSR 292 API specification maintenance for JDK 8
jrose
parents: 20534
diff changeset
  4443
     * }</pre></blockquote>
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4444
     * 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
  4445
     * 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
  4446
     * 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
  4447
     * <p>
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4448
     * 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
  4449
     * always throws.  (This might happen, for instance, because the handler
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4450
     * is simulating a {@code finally} clause).
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4451
     * 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
  4452
     * with {@link #throwException throwException},
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4453
     * 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
  4454
     * @param target method handle to call
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4455
     * @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
  4456
     * @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
  4457
     * @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
  4458
     * @throws NullPointerException if any argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4459
     * @throws IllegalArgumentException if {@code handler} does not accept
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4460
     *          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
  4461
     *          not match in their return types and their
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4462
     *          corresponding parameters
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4463
     * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4464
     */
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4465
    public static
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4466
    MethodHandle catchException(MethodHandle target,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4467
                                Class<? extends Throwable> exType,
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4468
                                MethodHandle handler) {
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4469
        MethodType ttype = target.type();
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4470
        MethodType htype = handler.type();
34959
4e7903220c89 8147078: MethodHandles.catchException does not enforce Throwable subtype
mhaupt
parents: 34882
diff changeset
  4471
        if (!Throwable.class.isAssignableFrom(exType))
4e7903220c89 8147078: MethodHandles.catchException does not enforce Throwable subtype
mhaupt
parents: 34882
diff changeset
  4472
            throw new ClassCastException(exType.getName());
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4473
        if (htype.parameterCount() < 1 ||
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4474
            !htype.parameterType(0).isAssignableFrom(exType))
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4475
            throw newIllegalArgumentException("handler does not accept exception type "+exType);
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4476
        if (htype.returnType() != ttype.returnType())
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4477
            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
  4478
        handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4479
        if (handler == null) {
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4480
            throw misMatchedTypes("target and handler types", ttype, htype);
7562
a0ad195efe2c 7001424: implement JSR 292 EG adjustments, November 2010
jrose
parents: 7555
diff changeset
  4481
        }
8821
2836ee97ee27 6839872: remove implementation inheritance from JSR 292 APIs
jrose
parents: 8349
diff changeset
  4482
        return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4483
    }
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  4484
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4485
    /**
8346
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  4486
     * 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
  4487
     * 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
  4488
     * and immediately throw it as an exception.
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4489
     * 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
  4490
     * 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
  4491
     * 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
  4492
     * @param returnType the return type of the desired method handle
0e46c17766b7 8019357: Fix doclint warnings in java.lang.invoke
darcy
parents: 18274
diff changeset
  4493
     * @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
  4494
     * @return method handle which can throw the given exceptions
3b891698c4ec 7012650: implement JSR 292 EG adjustments through January 2010
jrose
parents: 8345
diff changeset
  4495
     * @throws NullPointerException if either argument is null
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4496
     */
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4497
    public static
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4498
    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
  4499
        if (!Throwable.class.isAssignableFrom(exType))
17843fff200d 7023639: JSR 292 method handle invocation needs a fast path for compiled code
twisti
parents: 13044
diff changeset
  4500
            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
  4501
        return MethodHandleImpl.throwException(methodType(returnType, exType));
4537
7c3c7f8d5195 6914665: update jdk code for JSR 292 (post 6858164)
jrose
parents: 2764
diff changeset
  4502
    }
33874
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
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4505
     * 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
  4506
     * 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
  4507
     * 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
  4508
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4509
     * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4510
     * 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
  4511
     * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4512
     * terms of method handles, each clause will specify up to four independent actions:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4513
     * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4514
     * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4515
     * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4516
     * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4517
     * </ul>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4518
     * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4519
     * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4520
     * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4521
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4522
     * 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
  4523
     * this case. See below for a detailed description.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4524
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4525
     * <em>Parameters optional everywhere:</em>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4526
     * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4527
     * As an exception, the init functions cannot take any {@code v} parameters,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4528
     * because those values are not yet computed when the init functions are executed.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4529
     * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4530
     * In fact, any clause function may take no arguments at all.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4531
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4532
     * <em>Loop parameters:</em>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4533
     * A clause function may take all the iteration variable values it is entitled to, in which case
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4534
     * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4535
     * with their types and values notated as {@code (A...)} and {@code (a...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4536
     * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4537
     * (Since init functions do not accept iteration variables {@code v}, any parameter to an
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4538
     * init function is automatically a loop parameter {@code a}.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4539
     * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4540
     * These loop parameters act as loop-invariant values visible across the whole loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4541
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4542
     * <em>Parameters visible everywhere:</em>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4543
     * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4544
     * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4545
     * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4546
     * Most clause functions will not need all of this information, but they will be formally connected to it
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4547
     * as if by {@link #dropArguments}.
44844
b2b4d98404ba 8179364: update "<a name=" in java.base module to use id attribute
jjg
parents: 44545
diff changeset
  4548
     * <a id="astar"></a>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4549
     * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4550
     * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4551
     * In that notation, the general form of an init function parameter list
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4552
     * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4553
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4554
     * <em>Checking clause structure:</em>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4555
     * 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
  4556
     * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4557
     * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4558
     * met by the inputs to the loop combinator.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4559
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4560
     * <em>Effectively identical sequences:</em>
44844
b2b4d98404ba 8179364: update "<a name=" in java.base module to use id attribute
jjg
parents: 44545
diff changeset
  4561
     * <a id="effid"></a>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4562
     * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4563
     * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4564
     * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4565
     * as a whole if the set contains a longest list, and all members of the set are effectively identical to
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4566
     * that longest list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4567
     * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4568
     * and the same is true if more sequences of the form {@code (V... A*)} are added.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4569
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4570
     * <em>Step 0: Determine clause structure.</em><ol type="a">
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4571
     * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4572
     * <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
  4573
     * <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
  4574
     * four. Padding takes place by appending elements to the array.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4575
     * <li>Clauses with all {@code null}s are disregarded.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4576
     * <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
  4577
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4578
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4579
     * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4580
     * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4581
     * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4582
     * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4583
     * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4584
     * iteration variable type.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4585
     * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4586
     * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4587
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4588
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4589
     * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4590
     * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4591
     * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4592
     * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4593
     * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4594
     * (These types will checked in step 2, along with all the clause function types.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4595
     * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4596
     * <li>All of the collected parameter lists must be effectively identical.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4597
     * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4598
     * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4599
     * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4600
     * the "internal parameter list".
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4601
     * </ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4602
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4603
     * <em>Step 1C: Determine loop return type.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4604
     * <li>Examine fini function return types, disregarding omitted fini functions.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4605
     * <li>If there are no fini functions, the loop return type is {@code void}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4606
     * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4607
     * type.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4608
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4609
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4610
     * <em>Step 1D: Check other types.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4611
     * <li>There must be at least one non-omitted pred function.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4612
     * <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
  4613
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4614
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4615
     * <em>Step 2: Determine parameter lists.</em><ol type="a">
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4616
     * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4617
     * <li>The parameter list for init functions will be adjusted to the external parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4618
     * (Note that their parameter lists are already effectively identical to this list.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4619
     * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4620
     * effectively identical to the internal parameter list {@code (V... A...)}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4621
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4622
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4623
     * <em>Step 3: Fill in omitted functions.</em><ol type="a">
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4624
     * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4625
     * type.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4626
     * <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
  4627
     * 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
  4628
     * 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
  4629
     * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4630
     * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4631
     * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4632
     * loop return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4633
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4634
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4635
     * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4636
     * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4637
     * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4638
     * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4639
     * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4640
     * pad out the end of the list.
47004
b7e72fc752c9 8186684: Fix broken links in java.base API docs
jjg
parents: 46148
diff changeset
  4641
     * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4642
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4643
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4644
     * <em>Final observations.</em><ol type="a">
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4645
     * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4646
     * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4647
     * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4648
     * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4649
     * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4650
     * <li>Each pair of init and step functions agrees in their return type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4651
     * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4652
     * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4653
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4654
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4655
     * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4656
     * <ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4657
     * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4658
     * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4659
     * (Only one {@code Pn} has to be non-{@code null}.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4660
     * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4661
     * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4662
     * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4663
     * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4664
     * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4665
     * the resulting loop handle's parameter types {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4666
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4667
     * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4668
     * which is natural if most of the loop computation happens in the steps.  For some loops,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4669
     * the burden of computation might be heaviest in the pred functions, and so the pred functions
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4670
     * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4671
     * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4672
     * where the init functions will need the extra parameters.  For such reasons, the rules for
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4673
     * determining these parameters are as symmetric as possible, across all clause parts.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4674
     * In general, the loop parameters function as common invariant values across the whole
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4675
     * loop, while the iteration variables function as common variant values, or (if there is
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4676
     * no step function) as internal loop invariant temporaries.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4677
     * <p>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4678
     * <em>Loop execution.</em><ol type="a">
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4679
     * <li>When the loop is called, the loop input values are saved in locals, to be passed to
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4680
     * every clause function. These locals are loop invariant.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4681
     * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4682
     * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4683
     * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4684
     * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4685
     * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4686
     * (in argument order).
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4687
     * <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
  4688
     * returns {@code false}.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4689
     * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4690
     * sequence {@code (v...)} of loop variables.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4691
     * The updated value is immediately visible to all subsequent function calls.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4692
     * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4693
     * (of type {@code R}) is returned from the loop as a whole.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4694
     * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4695
     * except by throwing an exception.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4696
     * </ol>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4697
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4698
     * <em>Usage tips.</em>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4699
     * <ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4700
     * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4701
     * sometimes a step function only needs to observe the current value of its own variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4702
     * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4703
     * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4704
     * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4705
     * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4706
     * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4707
     * <li>If some of the clause functions are virtual methods on an instance, the instance
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4708
     * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4709
     * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4710
     * will be the first iteration variable value, and it will be easy to use virtual
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4711
     * methods as clause parts, since all of them will take a leading instance reference matching that value.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4712
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4713
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4714
     * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4715
     * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4716
     * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4717
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4718
     * V... init...(A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4719
     * boolean pred...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4720
     * V... step...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4721
     * R fini...(V..., A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4722
     * R loop(A... a) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4723
     *   V... v... = init...(a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4724
     *   for (;;) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4725
     *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4726
     *       v = s(v..., a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4727
     *       if (!p(v..., a...)) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4728
     *         return f(v..., a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4729
     *       }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4730
     *     }
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
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4733
     * }</pre></blockquote>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4734
     * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4735
     * to their full length, even though individual clause functions may neglect to take them all.
47004
b7e72fc752c9 8186684: Fix broken links in java.base API docs
jjg
parents: 46148
diff changeset
  4736
     * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  4737
     *
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4738
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4739
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4740
     * // iterative implementation of the factorial function as a loop handle
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4741
     * static int one(int k) { return 1; }
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4742
     * 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
  4743
     * 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
  4744
     * 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
  4745
     * 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
  4746
     * // 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
  4747
     * // null initializer for counter, should initialize to 0
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4748
     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4749
     * 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
  4750
     * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4751
     * assertEquals(120, loop.invoke(5));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4752
     * }</pre></blockquote>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4753
     * The same example, dropping arguments and using combinators:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4754
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4755
     * // simplified implementation of the factorial function as a loop handle
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4756
     * static int inc(int i) { return i + 1; } // drop acc, k
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4757
     * static int mult(int i, int acc) { return i * acc; } //drop k
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4758
     * static boolean cmp(int i, int k) { return i < k; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4759
     * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4760
     * // null initializer for counter, should initialize to 0
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4761
     * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4762
     * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4763
     * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4764
     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4765
     * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4766
     * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4767
     * assertEquals(720, loop.invoke(6));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4768
     * }</pre></blockquote>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4769
     * A similar example, using a helper object to hold a loop parameter:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4770
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4771
     * // instance-based implementation of the factorial function as a loop handle
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4772
     * static class FacLoop {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4773
     *   final int k;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4774
     *   FacLoop(int k) { this.k = k; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4775
     *   int inc(int i) { return i + 1; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4776
     *   int mult(int i, int acc) { return i * acc; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4777
     *   boolean pred(int i) { return i < k; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4778
     *   int fin(int i, int acc) { return acc; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4779
     * }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4780
     * // assume MH_FacLoop is a handle to the constructor
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4781
     * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4782
     * // null initializer for counter, should initialize to 0
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4783
     * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4784
     * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4785
     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4786
     * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4787
     * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4788
     * assertEquals(5040, loop.invoke(7));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4789
     * }</pre></blockquote>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4790
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4791
     * @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
  4792
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4793
     * @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
  4794
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4795
     * @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
  4796
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4797
     * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4798
     * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4799
     * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4800
     * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4801
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4802
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4803
    public static MethodHandle loop(MethodHandle[]... clauses) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4804
        // Step 0: determine clause structure.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4805
        loopChecks0(clauses);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4806
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4807
        List<MethodHandle> init = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4808
        List<MethodHandle> step = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4809
        List<MethodHandle> pred = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4810
        List<MethodHandle> fini = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4811
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4812
        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
  4813
            init.add(clause[0]); // all clauses have at least length 1
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4814
            step.add(clause.length <= 1 ? null : clause[1]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4815
            pred.add(clause.length <= 2 ? null : clause[2]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4816
            fini.add(clause.length <= 3 ? null : clause[3]);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4817
        });
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4818
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4819
        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
  4820
        final int nclauses = init.size();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4821
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4822
        // Step 1A: determine iteration variables (V...).
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4823
        final List<Class<?>> iterationVariableTypes = new ArrayList<>();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4824
        for (int i = 0; i < nclauses; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4825
            MethodHandle in = init.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4826
            MethodHandle st = step.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4827
            if (in == null && st == null) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4828
                iterationVariableTypes.add(void.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4829
            } else if (in != null && st != null) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4830
                loopChecks1a(i, in, st);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4831
                iterationVariableTypes.add(in.type().returnType());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4832
            } else {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4833
                iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
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
        final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4837
                collect(Collectors.toList());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4838
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4839
        // Step 1B: determine loop parameters (A...).
36220
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  4840
        final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4841
        loopChecks1b(init, commonSuffix);
33874
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
        // Step 1C: determine loop return type.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4844
        // Step 1D: check other types.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4845
        final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4846
                map(MethodType::returnType).findFirst().orElse(void.class);
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4847
        loopChecks1cd(pred, fini, loopReturnType);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4848
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4849
        // Step 2: determine parameter lists.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4850
        final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4851
        commonParameterSequence.addAll(commonSuffix);
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4852
        loopChecks2(step, pred, fini, commonParameterSequence);
33874
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
        // Step 3: fill in omitted functions.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4855
        for (int i = 0; i < nclauses; ++i) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4856
            Class<?> t = iterationVariableTypes.get(i);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4857
            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
  4858
                init.set(i, empty(methodType(t, commonSuffix)));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4859
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4860
            if (step.get(i) == null) {
37347
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  4861
                step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4862
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4863
            if (pred.get(i) == null) {
39755
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  4864
                pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4865
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4866
            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
  4867
                fini.set(i, empty(methodType(t, commonParameterSequence)));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4868
            }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4869
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4870
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4871
        // Step 4: fill in missing parameter types.
41125
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4872
        // Also convert all handles to fixed-arity handles.
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4873
        List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4874
        List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4875
        List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4876
        List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
33874
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
        assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4879
                allMatch(pl -> pl.equals(commonSuffix));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4880
        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
  4881
                allMatch(pl -> pl.equals(commonParameterSequence));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4882
39342
f66a89ed6fca 8143211: provide bytecode intrinsics for loop and try/finally executors
mhaupt
parents: 38861
diff changeset
  4883
        return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
33874
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
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4886
    private static void loopChecks0(MethodHandle[][] clauses) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4887
        if (clauses == null || clauses.length == 0) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4888
            throw newIllegalArgumentException("null or no clauses passed");
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4889
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4890
        if (Stream.of(clauses).anyMatch(Objects::isNull)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4891
            throw newIllegalArgumentException("null clauses are not allowed");
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4892
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4893
        if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4894
            throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4895
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4896
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4897
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4898
    private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4899
        if (in.type().returnType() != st.type().returnType()) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4900
            throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4901
                    st.type().returnType());
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4902
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4903
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4904
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4905
    private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4906
        final List<Class<?>> empty = List.of();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4907
        final List<Class<?>> longest = mhs.filter(Objects::nonNull).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4908
                // take only those that can contribute to a common suffix because they are longer than the prefix
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4909
                        map(MethodHandle::type).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4910
                        filter(t -> t.parameterCount() > skipSize).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4911
                        map(MethodType::parameterList).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4912
                        reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4913
        return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size());
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4914
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4915
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4916
    private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4917
        final List<Class<?>> empty = List.of();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4918
        return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4919
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4920
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4921
    private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4922
        final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4923
        final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4924
        return longestParameterList(Arrays.asList(longest1, longest2));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4925
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4926
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4927
    private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4928
        if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4929
                anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4930
            throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4931
                    " (common suffix: " + commonSuffix + ")");
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4932
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4933
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4934
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4935
    private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4936
        if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4937
                anyMatch(t -> t != loopReturnType)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4938
            throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4939
                    loopReturnType + ")");
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4940
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4941
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4942
        if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4943
            throw newIllegalArgumentException("no predicate found", pred);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4944
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4945
        if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4946
                anyMatch(t -> t != boolean.class)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4947
            throw newIllegalArgumentException("predicates must have boolean return type", pred);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4948
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4949
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4950
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4951
    private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4952
        if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4953
                anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4954
            throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4955
                    "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4956
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4957
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4958
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4959
    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
  4960
        return hs.stream().map(h -> {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4961
            int pc = h.type().parameterCount();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4962
            int tpsize = targetParams.size();
39755
3924e70f9f08 8155985: Persistent Parameter Processing
mhaupt
parents: 39754
diff changeset
  4963
            return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4964
        }).collect(Collectors.toList());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4965
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4966
41125
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4967
    private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4968
        return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList());
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4969
    }
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  4970
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4971
    /**
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4972
     * Constructs a {@code while} loop from an initializer, a body, and a predicate.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4973
     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4974
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4975
     * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4976
     * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4977
     * evaluates to {@code true}).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4978
     * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4979
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4980
     * The {@code init} handle describes the initial value of an additional optional loop-local variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4981
     * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4982
     * and updated with the value returned from its invocation. The result of loop execution will be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4983
     * the final value of the additional loop-local variable (if present).
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  4984
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4985
     * The following rules hold for these argument handles:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4986
     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4987
     * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4988
     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4989
     * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4990
     * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4991
     * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4992
     * It will constrain the parameter lists of the other loop parts.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4993
     * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4994
     * list {@code (A...)} is called the <em>external parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4995
     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4996
     * additional state variable of the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4997
     * The body must both accept and return a value of this type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4998
     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  4999
     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5000
     * <a href="MethodHandles.html#effid">effectively identical</a>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5001
     * to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5002
     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5003
     * {@linkplain #empty default value}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5004
     * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5005
     * Its parameter list (either empty or of the form {@code (V A*)}) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5006
     * effectively identical to the internal parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5007
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5008
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5009
     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5010
     * <li>The loop handle's result type is the result type {@code V} of the body.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5011
     * <li>The loop handle's parameter types are the types {@code (A...)},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5012
     * from the external parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5013
     * </ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5014
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5015
     * 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
  5016
     * 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
  5017
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5018
     * <blockquote><pre>{@code
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5019
     * V init(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5020
     * boolean pred(V, A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5021
     * V body(V, A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5022
     * V whileLoop(A... a...) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5023
     *   V v = init(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5024
     *   while (pred(v, a...)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5025
     *     v = body(v, a...);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5026
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5027
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5028
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5029
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5030
     *
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5031
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5032
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5033
     * // 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
  5034
     * 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
  5035
     * 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
  5036
     * 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
  5037
     *   zip.add(a.next());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5038
     *   zip.add(b.next());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5039
     *   return zip;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5040
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5041
     * // 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
  5042
     * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5043
     * List<String> a = Arrays.asList("a", "b", "c", "d");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5044
     * List<String> b = Arrays.asList("e", "f", "g", "h");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5045
     * 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
  5046
     * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5047
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5048
     *
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5049
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5050
     * @apiNote The implementation of this method can be expressed as follows:
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5051
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5052
     * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5053
     *     MethodHandle fini = (body.type().returnType() == void.class
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5054
     *                         ? null : identity(body.type().returnType()));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5055
     *     MethodHandle[]
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5056
     *         checkExit = { null, null, pred, fini },
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5057
     *         varBody   = { init, body };
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5058
     *     return loop(checkExit, varBody);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5059
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5060
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5061
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5062
     * @param init optional initializer, providing the initial value of the loop variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5063
     *             May be {@code null}, implying a default initial value.  See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5064
     * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5065
     *             above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5066
     * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5067
     *             See above for other constraints.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5068
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5069
     * @return a method handle implementing the {@code while} loop as described by the arguments.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5070
     * @throws IllegalArgumentException if the rules for the arguments are violated.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5071
     * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5072
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5073
     * @see #loop(MethodHandle[][])
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5074
     * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5075
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5076
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5077
    public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5078
        whileLoopChecks(init, pred, body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5079
        MethodHandle fini = identityOrVoid(body.type().returnType());
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5080
        MethodHandle[] checkExit = { null, null, pred, fini };
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5081
        MethodHandle[] varBody = { init, body };
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5082
        return loop(checkExit, varBody);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5083
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5084
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5085
    /**
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5086
     * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5087
     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5088
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5089
     * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5090
     * method will, in each iteration, first execute its body and then evaluate the predicate.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5091
     * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5092
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5093
     * The {@code init} handle describes the initial value of an additional optional loop-local variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5094
     * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5095
     * and updated with the value returned from its invocation. The result of loop execution will be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5096
     * the final value of the additional loop-local variable (if present).
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5097
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5098
     * The following rules hold for these argument handles:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5099
     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5100
     * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5101
     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5102
     * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5103
     * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5104
     * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5105
     * It will constrain the parameter lists of the other loop parts.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5106
     * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5107
     * list {@code (A...)} is called the <em>external parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5108
     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5109
     * additional state variable of the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5110
     * The body must both accept and return a value of this type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5111
     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5112
     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5113
     * <a href="MethodHandles.html#effid">effectively identical</a>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5114
     * to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5115
     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5116
     * {@linkplain #empty default value}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5117
     * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5118
     * Its parameter list (either empty or of the form {@code (V A*)}) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5119
     * effectively identical to the internal parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5120
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5121
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5122
     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5123
     * <li>The loop handle's result type is the result type {@code V} of the body.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5124
     * <li>The loop handle's parameter types are the types {@code (A...)},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5125
     * from the external parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5126
     * </ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5127
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5128
     * 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
  5129
     * 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
  5130
     * passed to the loop.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5131
     * <blockquote><pre>{@code
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5132
     * V init(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5133
     * boolean pred(V, A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5134
     * V body(V, A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5135
     * V doWhileLoop(A... a...) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5136
     *   V v = init(a...);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5137
     *   do {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5138
     *     v = body(v, a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5139
     *   } while (pred(v, a...));
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5140
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5141
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5142
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5143
     *
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5144
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5145
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5146
     * // 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
  5147
     * static int zero(int limit) { return 0; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  5148
     * static int step(int i, int limit) { return i + 1; }
32754521e67e 8150635: j.l.i.MethodHandles.loop(...) throws IndexOutOfBoundsException
mhaupt
parents: 36218
diff changeset
  5149
     * static boolean pred(int i, int limit) { return i < limit; }
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5150
     * // 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
  5151
     * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5152
     * assertEquals(23, loop.invoke(23));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5153
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5154
     *
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5155
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5156
     * @apiNote The implementation of this method can be expressed as follows:
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5157
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5158
     * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5159
     *     MethodHandle fini = (body.type().returnType() == void.class
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5160
     *                         ? null : identity(body.type().returnType()));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5161
     *     MethodHandle[] clause = { init, body, pred, fini };
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5162
     *     return loop(clause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5163
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5164
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5165
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5166
     * @param init optional initializer, providing the initial value of the loop variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5167
     *             May be {@code null}, implying a default initial value.  See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5168
     * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5169
     *             See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5170
     * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5171
     *             above for other constraints.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5172
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5173
     * @return a method handle implementing the {@code while} loop as described by the arguments.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5174
     * @throws IllegalArgumentException if the rules for the arguments are violated.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5175
     * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5176
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5177
     * @see #loop(MethodHandle[][])
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5178
     * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5179
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5180
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5181
    public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5182
        whileLoopChecks(init, pred, body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5183
        MethodHandle fini = identityOrVoid(body.type().returnType());
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5184
        MethodHandle[] clause = {init, body, pred, fini };
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5185
        return loop(clause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5186
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5187
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5188
    private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5189
        Objects.requireNonNull(pred);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5190
        Objects.requireNonNull(body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5191
        MethodType bodyType = body.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5192
        Class<?> returnType = bodyType.returnType();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5193
        List<Class<?>> innerList = bodyType.parameterList();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5194
        List<Class<?>> outerList = innerList;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5195
        if (returnType == void.class) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5196
            // OK
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5197
        } else if (innerList.size() == 0 || innerList.get(0) != returnType) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5198
            // leading V argument missing => error
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5199
            MethodType expected = bodyType.insertParameterTypes(0, returnType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5200
            throw misMatchedTypes("body function", bodyType, expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5201
        } else {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5202
            outerList = innerList.subList(1, innerList.size());
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5203
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5204
        MethodType predType = pred.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5205
        if (predType.returnType() != boolean.class ||
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5206
                !predType.effectivelyIdenticalParameters(0, innerList)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5207
            throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5208
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5209
        if (init != null) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5210
            MethodType initType = init.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5211
            if (initType.returnType() != returnType ||
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5212
                    !initType.effectivelyIdenticalParameters(0, outerList)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5213
                throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5214
            }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5215
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5216
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5217
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5218
    /**
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5219
     * Constructs a loop that runs a given number of iterations.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5220
     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5221
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5222
     * The number of iterations is determined by the {@code iterations} handle evaluation result.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5223
     * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5224
     * It will be initialized to 0 and incremented by 1 in each iteration.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5225
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5226
     * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5227
     * of that type is also present.  This variable is initialized using the optional {@code init} handle,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5228
     * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5229
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5230
     * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5231
     * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5232
     * iteration variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5233
     * The result of the loop handle execution will be the final {@code V} value of that variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5234
     * (or {@code void} if there is no {@code V} variable).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5235
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5236
     * The following rules hold for the argument handles:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5237
     * <li>The {@code iterations} handle must not be {@code null}, and must return
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5238
     * the type {@code int}, referred to here as {@code I} in parameter type lists.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5239
     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5240
     * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5241
     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5242
     * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5243
     * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5244
     * <li>The parameter list {@code (V I A...)} of the body contributes to a list
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5245
     * of types called the <em>internal parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5246
     * It will constrain the parameter lists of the other loop parts.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5247
     * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5248
     * with no additional {@code A} types, then the internal parameter list is extended by
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5249
     * the argument types {@code A...} of the {@code iterations} handle.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5250
     * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5251
     * list {@code (A...)} is called the <em>external parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5252
     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5253
     * additional state variable of the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5254
     * The body must both accept a leading parameter and return a value of this type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5255
     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5256
     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5257
     * <a href="MethodHandles.html#effid">effectively identical</a>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5258
     * to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5259
     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5260
     * {@linkplain #empty default value}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5261
     * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5262
     * effectively identical to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5263
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5264
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5265
     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5266
     * <li>The loop handle's result type is the result type {@code V} of the body.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5267
     * <li>The loop handle's parameter types are the types {@code (A...)},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5268
     * from the external parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5269
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5270
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5271
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5272
     * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5273
     * arguments passed to the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5274
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5275
     * int iterations(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5276
     * V init(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5277
     * V body(V, int, A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5278
     * V countedLoop(A... a...) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5279
     *   int end = iterations(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5280
     *   V v = init(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5281
     *   for (int i = 0; i < end; ++i) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5282
     *     v = body(v, i, a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5283
     *   }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5284
     *   return v;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5285
     * }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5286
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5287
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5288
     * @apiNote Example with a fully conformant body method:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5289
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5290
     * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5291
     * // => a variation on a well known theme
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5292
     * static String step(String v, int counter, String init) { return "na " + v; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5293
     * // assume MH_step is a handle to the method above
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5294
     * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5295
     * MethodHandle start = MethodHandles.identity(String.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5296
     * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5297
     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5298
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5299
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5300
     * @apiNote Example with the simplest possible body method type,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5301
     * and passing the number of iterations to the loop invocation:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5302
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5303
     * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5304
     * // => a variation on a well known theme
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5305
     * static String step(String v, int counter ) { return "na " + v; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5306
     * // assume MH_step is a handle to the method above
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5307
     * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5308
     * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5309
     * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5310
     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5311
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5312
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5313
     * @apiNote Example that treats the number of iterations, string to append to, and string to append
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5314
     * as loop parameters:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5315
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5316
     * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5317
     * // => a variation on a well known theme
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5318
     * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5319
     * // assume MH_step is a handle to the method above
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5320
     * MethodHandle count = MethodHandles.identity(int.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5321
     * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5322
     * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5323
     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5324
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5325
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5326
     * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5327
     * to enforce a loop type:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5328
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5329
     * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5330
     * // => a variation on a well known theme
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5331
     * static String step(String v, int counter, String pre) { return pre + " " + v; }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5332
     * // assume MH_step is a handle to the method above
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5333
     * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5334
     * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5335
     * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5336
     * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5337
     * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5338
     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5339
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5340
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5341
     * @apiNote The implementation of this method can be expressed as follows:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5342
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5343
     * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5344
     *     return countedLoop(empty(iterations.type()), iterations, init, body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5345
     * }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5346
     * }</pre></blockquote>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5347
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5348
     * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5349
     *                   result type must be {@code int}. See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5350
     * @param init optional initializer, providing the initial value of the loop variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5351
     *             May be {@code null}, implying a default initial value.  See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5352
     * @param body body of the loop, which may not be {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5353
     *             It controls the loop parameters and result type in the standard case (see above for details).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5354
     *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5355
     *             and may accept any number of additional types.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5356
     *             See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5357
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5358
     * @return a method handle representing the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5359
     * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5360
     * @throws IllegalArgumentException if any argument violates the rules formulated above.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5361
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5362
     * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5363
     * @since 9
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5364
     */
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5365
    public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5366
        return countedLoop(empty(iterations.type()), iterations, init, body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5367
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5368
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5369
    /**
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5370
     * Constructs a loop that counts over a range of numbers.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5371
     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5372
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5373
     * The loop counter {@code i} is a loop iteration variable of type {@code int}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5374
     * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5375
     * values of the loop counter.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5376
     * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5377
     * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5378
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5379
     * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5380
     * of that type is also present.  This variable is initialized using the optional {@code init} handle,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5381
     * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5382
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5383
     * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5384
     * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5385
     * iteration variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5386
     * The result of the loop handle execution will be the final {@code V} value of that variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5387
     * (or {@code void} if there is no {@code V} variable).
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5388
     * <p>
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5389
     * The following rules hold for the argument handles:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5390
     * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5391
     * the common type {@code int}, referred to here as {@code I} in parameter type lists.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5392
     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5393
     * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5394
     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5395
     * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5396
     * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5397
     * <li>The parameter list {@code (V I A...)} of the body contributes to a list
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5398
     * of types called the <em>internal parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5399
     * It will constrain the parameter lists of the other loop parts.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5400
     * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5401
     * with no additional {@code A} types, then the internal parameter list is extended by
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5402
     * the argument types {@code A...} of the {@code end} handle.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5403
     * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5404
     * list {@code (A...)} is called the <em>external parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5405
     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5406
     * additional state variable of the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5407
     * The body must both accept a leading parameter and return a value of this type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5408
     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5409
     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5410
     * <a href="MethodHandles.html#effid">effectively identical</a>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5411
     * to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5412
     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5413
     * {@linkplain #empty default value}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5414
     * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5415
     * effectively identical to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5416
     * <li>Likewise, the parameter list of {@code end} must be effectively identical
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5417
     * to the external parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5418
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5419
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5420
     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5421
     * <li>The loop handle's result type is the result type {@code V} of the body.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5422
     * <li>The loop handle's parameter types are the types {@code (A...)},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5423
     * from the external parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5424
     * </ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5425
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5426
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5427
     * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5428
     * arguments passed to the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5429
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5430
     * int start(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5431
     * int end(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5432
     * V init(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5433
     * V body(V, int, A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5434
     * V countedLoop(A... a...) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5435
     *   int e = end(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5436
     *   int s = start(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5437
     *   V v = init(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5438
     *   for (int i = s; i < e; ++i) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5439
     *     v = body(v, i, a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5440
     *   }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5441
     *   return v;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5442
     * }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5443
     * }</pre></blockquote>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5444
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5445
     * @apiNote The implementation of this method can be expressed as follows:
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5446
     * <blockquote><pre>{@code
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5447
     * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5448
     *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5449
     *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5450
     *     // the following semantics:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5451
     *     // MH_increment: (int limit, int counter) -> counter + 1
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5452
     *     // MH_predicate: (int limit, int counter) -> counter < limit
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5453
     *     Class<?> counterType = start.type().returnType();  // int
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5454
     *     Class<?> returnType = body.type().returnType();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5455
     *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5456
     *     if (returnType != void.class) {  // ignore the V variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5457
     *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5458
     *         pred = dropArguments(pred, 1, returnType);  // ditto
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5459
     *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5460
     *     }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5461
     *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5462
     *     MethodHandle[]
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5463
     *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5464
     *         bodyClause = { init, body },            // v = init(); v = body(v, i)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5465
     *         indexVar   = { start, incr };           // i = start(); i = i + 1
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5466
     *     return loop(loopLimit, bodyClause, indexVar);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5467
     * }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5468
     * }</pre></blockquote>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5469
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5470
     * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5471
     *              See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5472
     * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5473
     *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5474
     * @param init optional initializer, providing the initial value of the loop variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5475
     *             May be {@code null}, implying a default initial value.  See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5476
     * @param body body of the loop, which may not be {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5477
     *             It controls the loop parameters and result type in the standard case (see above for details).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5478
     *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5479
     *             and may accept any number of additional types.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5480
     *             See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5481
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5482
     * @return a method handle representing the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5483
     * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5484
     * @throws IllegalArgumentException if any argument violates the rules formulated above.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5485
     *
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5486
     * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5487
     * @since 9
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5488
     */
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5489
    public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5490
        countedLoopChecks(start, end, init, body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5491
        Class<?> counterType = start.type().returnType();  // int, but who's counting?
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5492
        Class<?> limitType   = end.type().returnType();    // yes, int again
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5493
        Class<?> returnType  = body.type().returnType();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5494
        MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5495
        MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5496
        MethodHandle retv = null;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5497
        if (returnType != void.class) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5498
            incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5499
            pred = dropArguments(pred, 1, returnType);  // ditto
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5500
            retv = dropArguments(identity(returnType), 0, counterType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5501
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5502
        body = dropArguments(body, 0, counterType);  // ignore the limit variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5503
        MethodHandle[]
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5504
            loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5505
            bodyClause = { init, body },            // v = init(); v = body(v, i)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5506
            indexVar   = { start, incr };           // i = start(); i = i + 1
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5507
        return loop(loopLimit, bodyClause, indexVar);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5508
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5509
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5510
    private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5511
        Objects.requireNonNull(start);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5512
        Objects.requireNonNull(end);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5513
        Objects.requireNonNull(body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5514
        Class<?> counterType = start.type().returnType();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5515
        if (counterType != int.class) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5516
            MethodType expected = start.type().changeReturnType(int.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5517
            throw misMatchedTypes("start function", start.type(), expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5518
        } else if (end.type().returnType() != counterType) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5519
            MethodType expected = end.type().changeReturnType(counterType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5520
            throw misMatchedTypes("end function", end.type(), expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5521
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5522
        MethodType bodyType = body.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5523
        Class<?> returnType = bodyType.returnType();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5524
        List<Class<?>> innerList = bodyType.parameterList();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5525
        // strip leading V value if present
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5526
        int vsize = (returnType == void.class ? 0 : 1);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5527
        if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5528
            // argument list has no "V" => error
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5529
            MethodType expected = bodyType.insertParameterTypes(0, returnType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5530
            throw misMatchedTypes("body function", bodyType, expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5531
        } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5532
            // missing I type => error
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5533
            MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5534
            throw misMatchedTypes("body function", bodyType, expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5535
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5536
        List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5537
        if (outerList.isEmpty()) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5538
            // special case; take lists from end handle
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5539
            outerList = end.type().parameterList();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5540
            innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5541
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5542
        MethodType expected = methodType(counterType, outerList);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5543
        if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5544
            throw misMatchedTypes("start parameter types", start.type(), expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5545
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5546
        if (end.type() != start.type() &&
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5547
            !end.type().effectivelyIdenticalParameters(0, outerList)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5548
            throw misMatchedTypes("end parameter types", end.type(), expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5549
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5550
        if (init != null) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5551
            MethodType initType = init.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5552
            if (initType.returnType() != returnType ||
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5553
                !initType.effectivelyIdenticalParameters(0, outerList)) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5554
                throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5555
            }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5556
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5557
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5558
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5559
    /**
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5560
     * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5561
     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5562
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5563
     * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5564
     * Each value it produces will be stored in a loop iteration variable of type {@code T}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5565
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5566
     * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5567
     * of that type is also present.  This variable is initialized using the optional {@code init} handle,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5568
     * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5569
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5570
     * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5571
     * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5572
     * iteration variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5573
     * The result of the loop handle execution will be the final {@code V} value of that variable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5574
     * (or {@code void} if there is no {@code V} variable).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5575
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5576
     * The following rules hold for the argument handles:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5577
     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5578
     * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5579
     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5580
     * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5581
     * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5582
     * <li>The parameter list {@code (V T A...)} of the body contributes to a list
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5583
     * of types called the <em>internal parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5584
     * It will constrain the parameter lists of the other loop parts.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5585
     * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5586
     * with no additional {@code A} types, then the internal parameter list is extended by
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5587
     * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5588
     * single type {@code Iterable} is added and constitutes the {@code A...} list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5589
     * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5590
     * list {@code (A...)} is called the <em>external parameter list</em>.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5591
     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5592
     * additional state variable of the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5593
     * The body must both accept a leading parameter and return a value of this type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5594
     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5595
     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5596
     * <a href="MethodHandles.html#effid">effectively identical</a>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5597
     * to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5598
     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5599
     * {@linkplain #empty default value}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5600
     * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5601
     * type {@code java.util.Iterator} or a subtype thereof.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5602
     * The iterator it produces when the loop is executed will be assumed
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5603
     * to yield values which can be converted to type {@code T}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5604
     * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5605
     * effectively identical to the external parameter list {@code (A...)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5606
     * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5607
     * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5608
     * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5609
     * handle parameter is adjusted to accept the leading {@code A} type, as if by
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5610
     * the {@link MethodHandle#asType asType} conversion method.
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5611
     * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5612
     * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5613
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5614
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5615
     * The type {@code T} may be either a primitive or reference.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5616
     * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5617
     * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5618
     * as if by the {@link MethodHandle#asType asType} conversion method.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5619
     * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5620
     * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5621
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5622
     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5623
     * <li>The loop handle's result type is the result type {@code V} of the body.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5624
     * <li>The loop handle's parameter types are the types {@code (A...)},
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5625
     * from the external parameter list.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5626
     * </ul>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5627
     * <p>
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5628
     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5629
     * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5630
     * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5631
     * <blockquote><pre>{@code
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5632
     * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5633
     * V init(A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5634
     * V body(V,T,A...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5635
     * V iteratedLoop(A... a...) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5636
     *   Iterator<T> it = iterator(a...);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5637
     *   V v = init(a...);
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5638
     *   while (it.hasNext()) {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5639
     *     T t = it.next();
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5640
     *     v = body(v, t, a...);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5641
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5642
     *   return v;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5643
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5644
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5645
     *
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5646
     * @apiNote Example:
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5647
     * <blockquote><pre>{@code
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5648
     * // get an iterator from a list
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5649
     * static List<String> reverseStep(List<String> r, String e) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5650
     *   r.add(0, e);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5651
     *   return r;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5652
     * }
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5653
     * static List<String> newArrayList() { return new ArrayList<>(); }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5654
     * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5655
     * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5656
     * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5657
     * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5658
     * assertEquals(reversedList, (List<String>) loop.invoke(list));
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5659
     * }</pre></blockquote>
46148
6d8e27cd2f1e 8186052: Fix a11y and HTML issues in the java.base/java.lang[.*] packages
jjg
parents: 46047
diff changeset
  5660
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5661
     * @apiNote The implementation of this method can be expressed approximately as follows:
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5662
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5663
     * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5664
     *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5665
     *     Class<?> returnType = body.type().returnType();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5666
     *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5667
     *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5668
     *     MethodHandle retv = null, step = body, startIter = iterator;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5669
     *     if (returnType != void.class) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5670
     *         // the simple thing first:  in (I V A...), drop the I to get V
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5671
     *         retv = dropArguments(identity(returnType), 0, Iterator.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5672
     *         // body type signature (V T A...), internal loop types (I V A...)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5673
     *         step = swapArguments(body, 0, 1);  // swap V <-> T
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5674
     *     }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5675
     *     if (startIter == null)  startIter = MH_getIter;
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5676
     *     MethodHandle[]
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5677
     *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5678
     *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5679
     *     return loop(iterVar, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5680
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5681
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5682
     *
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5683
     * @param iterator an optional handle to return the iterator to start the loop.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5684
     *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5685
     *                 See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5686
     * @param init optional initializer, providing the initial value of the loop variable.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5687
     *             May be {@code null}, implying a default initial value.  See above for other constraints.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5688
     * @param body body of the loop, which may not be {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5689
     *             It controls the loop parameters and result type in the standard case (see above for details).
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5690
     *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5691
     *             and may accept any number of additional types.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5692
     *             See above for other constraints.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5693
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5694
     * @return a method handle embodying the iteration loop functionality.
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5695
     * @throws NullPointerException if the {@code body} handle is {@code null}.
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5696
     * @throws IllegalArgumentException if any argument violates the above requirements.
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5697
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5698
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5699
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5700
    public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5701
        Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5702
        Class<?> returnType = body.type().returnType();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5703
        MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5704
        MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5705
        MethodHandle startIter;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5706
        MethodHandle nextVal;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5707
        {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5708
            MethodType iteratorType;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5709
            if (iterator == null) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5710
                // derive argument type from body, if available, else use Iterable
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5711
                startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5712
                iteratorType = startIter.type().changeParameterType(0, iterableType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5713
            } else {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5714
                // force return type to the internal iterator class
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5715
                iteratorType = iterator.type().changeReturnType(Iterator.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5716
                startIter = iterator;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5717
            }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5718
            Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5719
            MethodType nextValType = nextRaw.type().changeReturnType(ttype);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5720
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5721
            // perform the asType transforms under an exception transformer, as per spec.:
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5722
            try {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5723
                startIter = startIter.asType(iteratorType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5724
                nextVal = nextRaw.asType(nextValType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5725
            } catch (WrongMethodTypeException ex) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5726
                throw new IllegalArgumentException(ex);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5727
            }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5728
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5729
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5730
        MethodHandle retv = null, step = body;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5731
        if (returnType != void.class) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5732
            // the simple thing first:  in (I V A...), drop the I to get V
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5733
            retv = dropArguments(identity(returnType), 0, Iterator.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5734
            // body type signature (V T A...), internal loop types (I V A...)
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5735
            step = swapArguments(body, 0, 1);  // swap V <-> T
37602
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  5736
        }
3a9532bbd89e 8152667: MHs.iteratedLoop(...) throws unexpected WMTE, disallows Iterator subclasses, generates inconsistent loop result type
mhaupt
parents: 37539
diff changeset
  5737
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5738
        MethodHandle[]
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5739
            iterVar    = { startIter, null, hasNext, retv },
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5740
            bodyClause = { init, filterArgument(step, 0, nextVal) };
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5741
        return loop(iterVar, bodyClause);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5742
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5743
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5744
    private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5745
        Objects.requireNonNull(body);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5746
        MethodType bodyType = body.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5747
        Class<?> returnType = bodyType.returnType();
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5748
        List<Class<?>> internalParamList = bodyType.parameterList();
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5749
        // strip leading V value if present
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5750
        int vsize = (returnType == void.class ? 0 : 1);
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5751
        if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5752
            // argument list has no "V" => error
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5753
            MethodType expected = bodyType.insertParameterTypes(0, returnType);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5754
            throw misMatchedTypes("body function", bodyType, expected);
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5755
        } else if (internalParamList.size() <= vsize) {
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5756
            // missing T type => error
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5757
            MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5758
            throw misMatchedTypes("body function", bodyType, expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5759
        }
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5760
        List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5761
        Class<?> iterableType = null;
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5762
        if (iterator != null) {
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5763
            // special case; if the body handle only declares V and T then
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5764
            // the external parameter list is obtained from iterator handle
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5765
            if (externalParamList.isEmpty()) {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5766
                externalParamList = iterator.type().parameterList();
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5767
            }
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5768
            MethodType itype = iterator.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5769
            if (!Iterator.class.isAssignableFrom(itype.returnType())) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5770
                throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5771
            }
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5772
            if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5773
                MethodType expected = methodType(itype.returnType(), externalParamList);
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5774
                throw misMatchedTypes("iterator parameters", itype, expected);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5775
            }
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5776
        } else {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5777
            if (externalParamList.isEmpty()) {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5778
                // special case; if the iterator handle is null and the body handle
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5779
                // only declares V and T then the external parameter list consists
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5780
                // of Iterable
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5781
                externalParamList = Arrays.asList(Iterable.class);
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5782
                iterableType = Iterable.class;
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5783
            } else {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5784
                // special case; if the iterator handle is null and the external
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5785
                // parameter list is not empty then the first parameter must be
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5786
                // assignable to Iterable
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5787
                iterableType = externalParamList.get(0);
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5788
                if (!Iterable.class.isAssignableFrom(iterableType)) {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5789
                    throw newIllegalArgumentException(
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5790
                            "inferred first loop argument must inherit from Iterable: " + iterableType);
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5791
                }
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5792
            }
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5793
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5794
        if (init != null) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5795
            MethodType initType = init.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5796
            if (initType.returnType() != returnType ||
41829
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5797
                    !initType.effectivelyIdenticalParameters(0, externalParamList)) {
224facf0da6e 8167974: MethodHandles.iteratedLoop(...) fails with CCE in the case of iterating over array
psandoz
parents: 41207
diff changeset
  5798
                throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5799
            }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5800
        }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5801
        return iterableType;  // help the caller a bit
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5802
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5803
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5804
    /*non-public*/ static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5805
        // there should be a better way to uncross my wires
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5806
        int arity = mh.type().parameterCount();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5807
        int[] order = new int[arity];
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5808
        for (int k = 0; k < arity; k++)  order[k] = k;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5809
        order[i] = j; order[j] = i;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5810
        Class<?>[] types = mh.type().parameterArray();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5811
        Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5812
        MethodType swapType = methodType(mh.type().returnType(), types);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5813
        return permuteArguments(mh, swapType, order);
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5814
    }
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5815
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5816
    /**
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5817
     * 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
  5818
     * 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
  5819
     * 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
  5820
     * 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
  5821
     * 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
  5822
     * {@code try-finally} handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5823
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5824
     * 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
  5825
     * The first is the exception thrown during the
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5826
     * 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
  5827
     * 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
  5828
     * 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
  5829
     * 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
  5830
     * (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
  5831
     * 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
  5832
     * <p>
36112
e71e97060bf5 8150360: augment/correct MethodHandle API documentation
mhaupt
parents: 35772
diff changeset
  5833
     * 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
  5834
     * 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
  5835
     * two extra leading parameters:<ul>
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5836
     * <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
  5837
     * <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
  5838
     * the result from the execution of the {@code target} handle.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5839
     * 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
  5840
     * </ul>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5841
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5842
     * 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
  5843
     * 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
  5844
     * 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
  5845
     * the cleanup.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5846
     * <blockquote><pre>{@code
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5847
     * V target(A..., B...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5848
     * V cleanup(Throwable, V, A...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5849
     * V adapter(A... a, B... b) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5850
     *   V result = (zero value for V);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5851
     *   Throwable throwable = null;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5852
     *   try {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5853
     *     result = target(a..., b...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5854
     *   } catch (Throwable t) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5855
     *     throwable = t;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5856
     *     throw t;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5857
     *   } finally {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5858
     *     result = cleanup(throwable, result, a...);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5859
     *   }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5860
     *   return result;
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5861
     * }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5862
     * }</pre></blockquote>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5863
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5864
     * Note that the saved arguments ({@code a...} in the pseudocode) cannot
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5865
     * 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
  5866
     * from the caller to the cleanup, if it is invoked.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5867
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5868
     * 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
  5869
     * always throws.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5870
     * To create such a throwing cleanup, compose the cleanup logic
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5871
     * with {@link #throwException throwException},
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5872
     * 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
  5873
     * <p>
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5874
     * Note that {@code tryFinally} never converts exceptions into normal returns.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5875
     * 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
  5876
     * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5877
     * to capture an outgoing exception, and then wrap with {@code tryFinally}.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5878
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5879
     * @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
  5880
     * @param cleanup the handle that is invoked in the finally block.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5881
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5882
     * @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
  5883
     * @throws NullPointerException if any argument is null
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5884
     * @throws IllegalArgumentException if {@code cleanup} does not accept
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5885
     *          the required leading arguments, or if the method handle types do
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5886
     *          not match in their return types and their
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5887
     *          corresponding trailing parameters
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5888
     *
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5889
     * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5890
     * @since 9
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5891
     */
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5892
    public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5893
        List<Class<?>> targetParamTypes = target.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5894
        List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5895
        Class<?> rtype = target.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5896
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5897
        tryFinallyChecks(target, cleanup);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5898
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5899
        // 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
  5900
        // 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
  5901
        // target parameter list.
f6abe5d4bb1d 8150829: Enhanced drop-args, identity and default constant, varargs adjustment
srastogi
parents: 37343
diff changeset
  5902
        cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5903
41125
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  5904
        // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
88d76c8db1fa 8161211: better inlining support for loop bytecode intrinsics
mhaupt
parents: 40810
diff changeset
  5905
        return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5906
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5907
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5908
    private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5909
        Class<?> rtype = target.type().returnType();
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5910
        if (rtype != cleanup.type().returnType()) {
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5911
            throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5912
        }
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5913
        MethodType cleanupType = cleanup.type();
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5914
        if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5915
            throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5916
        }
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5917
        if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5918
            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
  5919
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5920
        // 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
  5921
        // target parameter list.
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5922
        int cleanupArgIndex = rtype == void.class ? 1 : 2;
41207
813a335bcb0c 8151179: address issues raised by JCK team on JEP 274 API
mhaupt
parents: 41125
diff changeset
  5923
        if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
33874
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5924
            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
  5925
                    cleanup.type(), target.type());
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5926
        }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5927
    }
46651fd30c0b 8139885: implement JEP 274: enhanced method handles
mhaupt
parents: 32649
diff changeset
  5928
2707
5a17df307cbc 6829144: JSR 292 JVM features need a provisional Java API
jrose
parents:
diff changeset
  5929
}