LinkerServices.java revision 1551:f3b883bec2d0
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/*
27 * This file is available under and governed by the GNU General Public
28 * License version 2 only, as published by the Free Software Foundation.
29 * However, the following notice accompanied the original version of this
30 * file, and Oracle licenses the original version of this file under the BSD
31 * license:
32 */
33/*
34   Copyright 2009-2013 Attila Szegedi
35
36   Licensed under both the Apache License, Version 2.0 (the "Apache License")
37   and the BSD License (the "BSD License"), with licensee being free to
38   choose either of the two at their discretion.
39
40   You may not use this file except in compliance with either the Apache
41   License or the BSD License.
42
43   If you choose to use this file in compliance with the Apache License, the
44   following notice applies to you:
45
46       You may obtain a copy of the Apache License at
47
48           http://www.apache.org/licenses/LICENSE-2.0
49
50       Unless required by applicable law or agreed to in writing, software
51       distributed under the License is distributed on an "AS IS" BASIS,
52       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
53       implied. See the License for the specific language governing
54       permissions and limitations under the License.
55
56   If you choose to use this file in compliance with the BSD License, the
57   following notice applies to you:
58
59       Redistribution and use in source and binary forms, with or without
60       modification, are permitted provided that the following conditions are
61       met:
62       * Redistributions of source code must retain the above copyright
63         notice, this list of conditions and the following disclaimer.
64       * Redistributions in binary form must reproduce the above copyright
65         notice, this list of conditions and the following disclaimer in the
66         documentation and/or other materials provided with the distribution.
67       * Neither the name of the copyright holder nor the names of
68         contributors may be used to endorse or promote products derived from
69         this software without specific prior written permission.
70
71       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
72       IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
73       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
74       PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
75       BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76       CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77       SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
78       BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
79       WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
80       OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
81       ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
82*/
83
84package jdk.dynalink.linker;
85
86import java.lang.invoke.MethodHandle;
87import java.lang.invoke.MethodHandles;
88import java.lang.invoke.MethodType;
89import jdk.dynalink.DynamicLinker;
90import jdk.dynalink.DynamicLinkerFactory;
91import jdk.dynalink.linker.ConversionComparator.Comparison;
92import jdk.dynalink.linker.support.TypeUtilities;
93
94/**
95 * Interface for services provided to {@link GuardingDynamicLinker} instances by
96 * the {@link DynamicLinker} that owns them.
97 */
98public interface LinkerServices {
99    /**
100     * Similar to {@link MethodHandle#asType(MethodType)} except it also hooks
101     * in method handles produced by all available
102     * {@link GuardingTypeConverterFactory} implementations, providing for
103     * language-specific type coercing of parameters. It will apply
104     * {@link MethodHandle#asType(MethodType)} for all primitive-to-primitive,
105     * wrapper-to-primitive, primitive-to-wrapper conversions as well as for all
106     * upcasts. For all other conversions, it'll insert
107     * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)}
108     * with composite filters provided by {@link GuardingTypeConverterFactory}
109     * implementations.
110     *
111     * @param handle target method handle
112     * @param fromType the types of source arguments
113     * @return a method handle that is a suitable combination of
114     * {@link MethodHandle#asType(MethodType)},
115     * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)},
116     * and {@link MethodHandles#filterReturnValue(MethodHandle, MethodHandle)}
117     * with {@link GuardingTypeConverterFactory}-produced type converters as
118     * filters.
119     */
120    public MethodHandle asType(MethodHandle handle, MethodType fromType);
121
122    /**
123     * Similar to {@link #asType(MethodHandle, MethodType)} except it treats
124     * return value type conversion specially. It only converts the return type
125     * of the method handle when it can be done using a conversion that loses
126     * neither precision nor magnitude, otherwise it leaves it unchanged. These
127     * are the only return value conversions that should be performed by
128     * individual language-specific linkers, and
129     * {@link DynamicLinkerFactory#setPrelinkTransformer(GuardedInvocationTransformer)
130     * pre-link transformer of the dynamic linker} should implement the strategy
131     * for dealing with potentially lossy return type conversions in a manner
132     * specific to the language runtime where the call site is located.
133     *
134     * @param handle target method handle
135     * @param fromType the types of source arguments
136     * @return a method handle that is a suitable combination of
137     * {@link MethodHandle#asType(MethodType)}, and
138     * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)}
139     * with {@link GuardingTypeConverterFactory}-produced type converters as filters.
140     */
141    public default MethodHandle asTypeLosslessReturn(final MethodHandle handle, final MethodType fromType) {
142        final Class<?> handleReturnType = handle.type().returnType();
143        return asType(handle, TypeUtilities.isConvertibleWithoutLoss(handleReturnType, fromType.returnType()) ?
144                fromType : fromType.changeReturnType(handleReturnType));
145    }
146
147    /**
148     * Given a source and target type, returns a method handle that converts
149     * between them. Never returns null; in worst case it will return an
150     * identity conversion (that might fail for some values at runtime). You
151     * rarely need to use this method directly and should mostly rely on
152     * {@link #asType(MethodHandle, MethodType)} instead. This method is needed
153     * when you need to reuse existing type conversion machinery outside the
154     * context of processing a link request.
155     * @param sourceType the type to convert from
156     * @param targetType the type to convert to
157     * @return a method handle performing the conversion.
158     */
159    public MethodHandle getTypeConverter(Class<?> sourceType, Class<?> targetType);
160
161    /**
162     * Returns true if there might exist a conversion between the requested
163     * types (either an automatic JVM conversion, or one provided by any
164     * available {@link GuardingTypeConverterFactory}), or false if there
165     * definitely does not exist a conversion between the requested types. Note
166     * that returning true does not guarantee that the conversion will succeed
167     * at runtime for all values (especially if the "from" or "to" types are
168     * sufficiently generic), but returning false guarantees that it would fail.
169     *
170     * @param from the source type for the conversion
171     * @param to the target type for the conversion
172     * @return true if there can be a conversion, false if there can not.
173     */
174    public boolean canConvert(Class<?> from, Class<?> to);
175
176    /**
177     * Creates a guarded invocation delegating back to the {@link DynamicLinker}
178     * that exposes this linker services object. The dynamic linker will then
179     * itself delegate the linking to all of its managed
180     * {@link GuardingDynamicLinker}s including potentially this one if no
181     * linker responds earlier, so beware of infinite recursion. You'll
182     * typically craft the link request so that it will be different than the
183     * one you are currently trying to link.
184     *
185     * @param linkRequest a request for linking the invocation
186     * @return a guarded invocation linked by some of the guarding dynamic
187     * linkers managed by the top-level dynamic linker. Can be null if no
188     * available linker is able to link the invocation. You will typically use
189     * the elements of the returned invocation to compose your own invocation.
190     * @throws Exception in case the top-level linker throws an exception
191     */
192    public GuardedInvocation getGuardedInvocation(LinkRequest linkRequest) throws Exception;
193
194    /**
195     * Determines which of the two type conversions from a source type to the
196     * two target types is preferred. This is used for dynamic overloaded method
197     * resolution. If the source type is convertible to exactly one target type
198     * with a method invocation conversion, it is chosen, otherwise available
199     * {@link ConversionComparator}s are consulted.
200     * @param sourceType the source type.
201     * @param targetType1 one potential target type
202     * @param targetType2 another potential target type.
203     * @return one of Comparison constants that establish which &ndash; if any
204     * &ndash; of the target types is preferable for the conversion.
205     */
206    public Comparison compareConversion(Class<?> sourceType, Class<?> targetType1, Class<?> targetType2);
207
208    /**
209     * Modifies the method handle so that any parameters that can receive
210     * potentially internal language runtime objects will have a filter added on
211     * them to prevent them from escaping, potentially by wrapping them. It can
212     * also potentially add an unwrapping filter to the return value. Basically
213     * transforms the method handle using the transformer configured by
214     * {@link DynamicLinkerFactory#setInternalObjectsFilter(MethodHandleTransformer)}.
215     * @param target the target method handle
216     * @return a method handle with parameters and/or return type potentially
217     * filtered for wrapping and unwrapping.
218     */
219    public MethodHandle filterInternalObjects(final MethodHandle target);
220}
221