src/jdk/internal/dynalink/support/TypeConverterFactory.java

Wed, 20 Aug 2014 10:25:28 +0200

author
attila
date
Wed, 20 Aug 2014 10:25:28 +0200
changeset 962
ac62e33a99b0
parent 719
11b83c913cca
child 963
e2497b11a021
permissions
-rw-r--r--

8044638: Tidy up Nashorn codebase for code standards
8055199: Tidy up Nashorn codebase for code standards (August 2014)
Reviewed-by: lagergren, sundar

attila@90 1 /*
attila@90 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
attila@90 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
attila@90 4 *
attila@90 5 * This code is free software; you can redistribute it and/or modify it
attila@90 6 * under the terms of the GNU General Public License version 2 only, as
attila@90 7 * published by the Free Software Foundation. Oracle designates this
attila@90 8 * particular file as subject to the "Classpath" exception as provided
attila@90 9 * by Oracle in the LICENSE file that accompanied this code.
attila@90 10 *
attila@90 11 * This code is distributed in the hope that it will be useful, but WITHOUT
attila@90 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
attila@90 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
attila@90 14 * version 2 for more details (a copy is included in the LICENSE file that
attila@90 15 * accompanied this code).
attila@90 16 *
attila@90 17 * You should have received a copy of the GNU General Public License version
attila@90 18 * 2 along with this work; if not, write to the Free Software Foundation,
attila@90 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
attila@90 20 *
attila@90 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
attila@90 22 * or visit www.oracle.com if you need additional information or have any
attila@90 23 * questions.
attila@90 24 */
attila@90 25
attila@90 26 /*
attila@90 27 * This file is available under and governed by the GNU General Public
attila@90 28 * License version 2 only, as published by the Free Software Foundation.
attila@90 29 * However, the following notice accompanied the original version of this
attila@90 30 * file, and Oracle licenses the original version of this file under the BSD
attila@90 31 * license:
attila@90 32 */
attila@90 33 /*
attila@90 34 Copyright 2009-2013 Attila Szegedi
attila@90 35
attila@90 36 Licensed under both the Apache License, Version 2.0 (the "Apache License")
attila@90 37 and the BSD License (the "BSD License"), with licensee being free to
attila@90 38 choose either of the two at their discretion.
attila@90 39
attila@90 40 You may not use this file except in compliance with either the Apache
attila@90 41 License or the BSD License.
attila@90 42
attila@90 43 If you choose to use this file in compliance with the Apache License, the
attila@90 44 following notice applies to you:
attila@90 45
attila@90 46 You may obtain a copy of the Apache License at
attila@90 47
attila@90 48 http://www.apache.org/licenses/LICENSE-2.0
attila@90 49
attila@90 50 Unless required by applicable law or agreed to in writing, software
attila@90 51 distributed under the License is distributed on an "AS IS" BASIS,
attila@90 52 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
attila@90 53 implied. See the License for the specific language governing
attila@90 54 permissions and limitations under the License.
attila@90 55
attila@90 56 If you choose to use this file in compliance with the BSD License, the
attila@90 57 following notice applies to you:
attila@90 58
attila@90 59 Redistribution and use in source and binary forms, with or without
attila@90 60 modification, are permitted provided that the following conditions are
attila@90 61 met:
attila@90 62 * Redistributions of source code must retain the above copyright
attila@90 63 notice, this list of conditions and the following disclaimer.
attila@90 64 * Redistributions in binary form must reproduce the above copyright
attila@90 65 notice, this list of conditions and the following disclaimer in the
attila@90 66 documentation and/or other materials provided with the distribution.
attila@90 67 * Neither the name of the copyright holder nor the names of
attila@90 68 contributors may be used to endorse or promote products derived from
attila@90 69 this software without specific prior written permission.
attila@90 70
attila@90 71 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
attila@90 72 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
attila@90 73 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
attila@90 74 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
attila@90 75 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
attila@90 76 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
attila@90 77 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
attila@90 78 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
attila@90 79 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
attila@90 80 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
attila@90 81 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
attila@90 82 */
attila@90 83
attila@90 84 package jdk.internal.dynalink.support;
attila@90 85
attila@90 86 import java.lang.invoke.MethodHandle;
attila@90 87 import java.lang.invoke.MethodHandles;
attila@90 88 import java.lang.invoke.MethodType;
attila@90 89 import java.lang.invoke.WrongMethodTypeException;
attila@488 90 import java.security.AccessController;
attila@488 91 import java.security.PrivilegedAction;
attila@90 92 import java.util.LinkedList;
attila@90 93 import java.util.List;
attila@90 94 import jdk.internal.dynalink.linker.ConversionComparator;
attila@90 95 import jdk.internal.dynalink.linker.ConversionComparator.Comparison;
attila@90 96 import jdk.internal.dynalink.linker.GuardedInvocation;
attila@719 97 import jdk.internal.dynalink.linker.GuardedTypeConversion;
attila@90 98 import jdk.internal.dynalink.linker.GuardingTypeConverterFactory;
attila@90 99 import jdk.internal.dynalink.linker.LinkerServices;
attila@90 100
attila@90 101 /**
attila@90 102 * A factory for type converters. This class is the main implementation behind the
attila@90 103 * {@link LinkerServices#asType(MethodHandle, MethodType)}. It manages the known {@link GuardingTypeConverterFactory}
attila@90 104 * instances and creates appropriate converters for method handles.
attila@90 105 *
attila@90 106 * @author Attila Szegedi
attila@90 107 */
attila@90 108 public class TypeConverterFactory {
attila@90 109
attila@90 110 private final GuardingTypeConverterFactory[] factories;
attila@90 111 private final ConversionComparator[] comparators;
attila@90 112
attila@90 113 private final ClassValue<ClassMap<MethodHandle>> converterMap = new ClassValue<ClassMap<MethodHandle>>() {
attila@90 114 @Override
attila@90 115 protected ClassMap<MethodHandle> computeValue(final Class<?> sourceType) {
attila@488 116 return new ClassMap<MethodHandle>(getClassLoader(sourceType)) {
attila@90 117 @Override
attila@962 118 protected MethodHandle computeValue(final Class<?> targetType) {
attila@90 119 try {
attila@90 120 return createConverter(sourceType, targetType);
attila@962 121 } catch (final RuntimeException e) {
attila@90 122 throw e;
attila@962 123 } catch (final Exception e) {
attila@90 124 throw new RuntimeException(e);
attila@90 125 }
attila@90 126 }
attila@90 127 };
attila@90 128 }
attila@90 129 };
attila@90 130
attila@90 131 private final ClassValue<ClassMap<MethodHandle>> converterIdentityMap = new ClassValue<ClassMap<MethodHandle>>() {
attila@90 132 @Override
attila@90 133 protected ClassMap<MethodHandle> computeValue(final Class<?> sourceType) {
attila@488 134 return new ClassMap<MethodHandle>(getClassLoader(sourceType)) {
attila@90 135 @Override
attila@962 136 protected MethodHandle computeValue(final Class<?> targetType) {
attila@90 137 if(!canAutoConvert(sourceType, targetType)) {
attila@719 138 final MethodHandle converter = getCacheableTypeConverter(sourceType, targetType);
attila@719 139 if(converter != IDENTITY_CONVERSION) {
attila@90 140 return converter;
attila@90 141 }
attila@90 142 }
attila@90 143 return IDENTITY_CONVERSION.asType(MethodType.methodType(targetType, sourceType));
attila@90 144 }
attila@90 145 };
attila@90 146 }
attila@90 147 };
attila@90 148
attila@719 149 private final ClassValue<ClassMap<Boolean>> canConvert = new ClassValue<ClassMap<Boolean>>() {
attila@719 150 @Override
attila@719 151 protected ClassMap<Boolean> computeValue(final Class<?> sourceType) {
attila@719 152 return new ClassMap<Boolean>(getClassLoader(sourceType)) {
attila@719 153 @Override
attila@962 154 protected Boolean computeValue(final Class<?> targetType) {
attila@719 155 try {
attila@719 156 return getTypeConverterNull(sourceType, targetType) != null;
attila@962 157 } catch (final RuntimeException e) {
attila@719 158 throw e;
attila@962 159 } catch (final Exception e) {
attila@719 160 throw new RuntimeException(e);
attila@719 161 }
attila@719 162 }
attila@719 163 };
attila@719 164 }
attila@719 165 };
attila@719 166
attila@488 167 private static final ClassLoader getClassLoader(final Class<?> clazz) {
attila@488 168 return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
attila@488 169 @Override
attila@488 170 public ClassLoader run() {
attila@488 171 return clazz.getClassLoader();
attila@488 172 }
attila@494 173 }, ClassLoaderGetterContextProvider.GET_CLASS_LOADER_CONTEXT);
attila@488 174 }
attila@488 175
attila@90 176 /**
attila@90 177 * Creates a new type converter factory from the available {@link GuardingTypeConverterFactory} instances.
attila@90 178 *
attila@90 179 * @param factories the {@link GuardingTypeConverterFactory} instances to compose.
attila@90 180 */
attila@962 181 public TypeConverterFactory(final Iterable<? extends GuardingTypeConverterFactory> factories) {
attila@90 182 final List<GuardingTypeConverterFactory> l = new LinkedList<>();
attila@90 183 final List<ConversionComparator> c = new LinkedList<>();
attila@962 184 for(final GuardingTypeConverterFactory factory: factories) {
attila@90 185 l.add(factory);
attila@90 186 if(factory instanceof ConversionComparator) {
attila@90 187 c.add((ConversionComparator)factory);
attila@90 188 }
attila@90 189 }
attila@90 190 this.factories = l.toArray(new GuardingTypeConverterFactory[l.size()]);
attila@90 191 this.comparators = c.toArray(new ConversionComparator[c.size()]);
attila@90 192
attila@90 193 }
attila@90 194
attila@90 195 /**
attila@90 196 * Similar to {@link MethodHandle#asType(MethodType)} except it also hooks in method handles produced by
attila@90 197 * {@link GuardingTypeConverterFactory} implementations, providing for language-specific type coercing of
attila@90 198 * parameters. It will apply {@link MethodHandle#asType(MethodType)} for all primitive-to-primitive,
attila@90 199 * wrapper-to-primitive, primitive-to-wrapper conversions as well as for all upcasts. For all other conversions,
attila@90 200 * it'll insert {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)} with composite filters
attila@90 201 * provided by {@link GuardingTypeConverterFactory} implementations.
attila@90 202 *
attila@90 203 * @param handle target method handle
attila@90 204 * @param fromType the types of source arguments
attila@90 205 * @return a method handle that is a suitable combination of {@link MethodHandle#asType(MethodType)} and
attila@90 206 * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)} with
attila@90 207 * {@link GuardingTypeConverterFactory} produced type converters as filters.
attila@90 208 */
attila@962 209 public MethodHandle asType(final MethodHandle handle, final MethodType fromType) {
attila@90 210 MethodHandle newHandle = handle;
attila@90 211 final MethodType toType = newHandle.type();
attila@90 212 final int l = toType.parameterCount();
attila@90 213 if(l != fromType.parameterCount()) {
attila@90 214 throw new WrongMethodTypeException("Parameter counts differ: " + handle.type() + " vs. " + fromType);
attila@90 215 }
attila@90 216 int pos = 0;
attila@90 217 final List<MethodHandle> converters = new LinkedList<>();
attila@90 218 for(int i = 0; i < l; ++i) {
attila@90 219 final Class<?> fromParamType = fromType.parameterType(i);
attila@90 220 final Class<?> toParamType = toType.parameterType(i);
attila@90 221 if(canAutoConvert(fromParamType, toParamType)) {
attila@90 222 newHandle = applyConverters(newHandle, pos, converters);
attila@90 223 } else {
attila@90 224 final MethodHandle converter = getTypeConverterNull(fromParamType, toParamType);
attila@90 225 if(converter != null) {
attila@90 226 if(converters.isEmpty()) {
attila@90 227 pos = i;
attila@90 228 }
attila@90 229 converters.add(converter);
attila@90 230 } else {
attila@90 231 newHandle = applyConverters(newHandle, pos, converters);
attila@90 232 }
attila@90 233 }
attila@90 234 }
attila@90 235 newHandle = applyConverters(newHandle, pos, converters);
attila@90 236
attila@90 237 // Convert return type
attila@90 238 final Class<?> fromRetType = fromType.returnType();
attila@90 239 final Class<?> toRetType = toType.returnType();
attila@90 240 if(fromRetType != Void.TYPE && toRetType != Void.TYPE) {
attila@90 241 if(!canAutoConvert(toRetType, fromRetType)) {
attila@90 242 final MethodHandle converter = getTypeConverterNull(toRetType, fromRetType);
attila@90 243 if(converter != null) {
attila@90 244 newHandle = MethodHandles.filterReturnValue(newHandle, converter);
attila@90 245 }
attila@90 246 }
attila@90 247 }
attila@90 248
attila@90 249 // Take care of automatic conversions
attila@90 250 return newHandle.asType(fromType);
attila@90 251 }
attila@90 252
attila@962 253 private static MethodHandle applyConverters(final MethodHandle handle, final int pos, final List<MethodHandle> converters) {
attila@90 254 if(converters.isEmpty()) {
attila@90 255 return handle;
attila@90 256 }
attila@90 257 final MethodHandle newHandle =
attila@90 258 MethodHandles.filterArguments(handle, pos, converters.toArray(new MethodHandle[converters.size()]));
attila@90 259 converters.clear();
attila@90 260 return newHandle;
attila@90 261 }
attila@90 262
attila@90 263 /**
attila@90 264 * Returns true if there might exist a conversion between the requested types (either an automatic JVM conversion,
attila@90 265 * or one provided by any available {@link GuardingTypeConverterFactory}), or false if there definitely does not
attila@90 266 * exist a conversion between the requested types. Note that returning true does not guarantee that the conversion
attila@90 267 * will succeed at runtime (notably, if the "from" or "to" types are sufficiently generic), but returning false
attila@90 268 * guarantees that it would fail.
attila@90 269 *
attila@90 270 * @param from the source type for the conversion
attila@90 271 * @param to the target type for the conversion
attila@90 272 * @return true if there can be a conversion, false if there can not.
attila@90 273 */
attila@90 274 public boolean canConvert(final Class<?> from, final Class<?> to) {
attila@719 275 return canAutoConvert(from, to) || canConvert.get(from).get(to).booleanValue();
attila@90 276 }
attila@90 277
attila@90 278 /**
attila@90 279 * Determines which of the two type conversions from a source type to the two target types is preferred. This is
attila@90 280 * used for dynamic overloaded method resolution. If the source type is convertible to exactly one target type with
attila@90 281 * a method invocation conversion, it is chosen, otherwise available {@link ConversionComparator}s are consulted.
attila@90 282 * @param sourceType the source type.
attila@90 283 * @param targetType1 one potential target type
attila@90 284 * @param targetType2 another potential target type.
attila@90 285 * @return one of Comparison constants that establish which - if any - of the target types is preferable for the
attila@90 286 * conversion.
attila@90 287 */
attila@962 288 public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
attila@962 289 for(final ConversionComparator comparator: comparators) {
attila@90 290 final Comparison result = comparator.compareConversion(sourceType, targetType1, targetType2);
attila@90 291 if(result != Comparison.INDETERMINATE) {
attila@90 292 return result;
attila@90 293 }
attila@90 294 }
attila@90 295 if(TypeUtilities.isMethodInvocationConvertible(sourceType, targetType1)) {
attila@90 296 if(!TypeUtilities.isMethodInvocationConvertible(sourceType, targetType2)) {
attila@90 297 return Comparison.TYPE_1_BETTER;
attila@90 298 }
attila@90 299 } else if(TypeUtilities.isMethodInvocationConvertible(sourceType, targetType2)) {
attila@90 300 return Comparison.TYPE_2_BETTER;
attila@90 301 }
attila@90 302 return Comparison.INDETERMINATE;
attila@90 303 }
attila@90 304
attila@90 305 /**
attila@90 306 * Determines whether it's safe to perform an automatic conversion between the source and target class.
attila@90 307 *
attila@90 308 * @param fromType convert from this class
attila@90 309 * @param toType convert to this class
attila@90 310 * @return true if it's safe to let MethodHandles.convertArguments() to handle this conversion.
attila@90 311 */
attila@90 312 /*private*/ static boolean canAutoConvert(final Class<?> fromType, final Class<?> toType) {
attila@90 313 return TypeUtilities.isMethodInvocationConvertible(fromType, toType);
attila@90 314 }
attila@90 315
attila@962 316 /*private*/ MethodHandle getCacheableTypeConverterNull(final Class<?> sourceType, final Class<?> targetType) {
attila@719 317 final MethodHandle converter = getCacheableTypeConverter(sourceType, targetType);
attila@719 318 return converter == IDENTITY_CONVERSION ? null : converter;
attila@719 319 }
attila@719 320
attila@962 321 /*private*/ MethodHandle getTypeConverterNull(final Class<?> sourceType, final Class<?> targetType) {
attila@719 322 try {
attila@719 323 return getCacheableTypeConverterNull(sourceType, targetType);
attila@962 324 } catch(final NotCacheableConverter e) {
attila@719 325 return e.converter;
attila@719 326 }
attila@719 327 }
attila@719 328
attila@962 329 /*private*/ MethodHandle getCacheableTypeConverter(final Class<?> sourceType, final Class<?> targetType) {
attila@719 330 return converterMap.get(sourceType).get(targetType);
attila@90 331 }
attila@90 332
attila@90 333 /**
attila@90 334 * Given a source and target type, returns a method handle that converts between them. Never returns null; in worst
attila@90 335 * case it will return an identity conversion (that might fail for some values at runtime). You can use this method
attila@90 336 * if you have a piece of your program that is written in Java, and you need to reuse existing type conversion
attila@90 337 * machinery in a non-invokedynamic context.
attila@90 338 * @param sourceType the type to convert from
attila@90 339 * @param targetType the type to convert to
attila@90 340 * @return a method handle performing the conversion.
attila@90 341 */
attila@962 342 public MethodHandle getTypeConverter(final Class<?> sourceType, final Class<?> targetType) {
attila@719 343 try {
attila@719 344 return converterIdentityMap.get(sourceType).get(targetType);
attila@962 345 } catch(final NotCacheableConverter e) {
attila@719 346 return e.converter;
attila@719 347 }
attila@90 348 }
attila@90 349
attila@962 350 /*private*/ MethodHandle createConverter(final Class<?> sourceType, final Class<?> targetType) throws Exception {
attila@90 351 final MethodType type = MethodType.methodType(targetType, sourceType);
attila@90 352 final MethodHandle identity = IDENTITY_CONVERSION.asType(type);
attila@90 353 MethodHandle last = identity;
attila@719 354 boolean cacheable = true;
attila@90 355 for(int i = factories.length; i-- > 0;) {
attila@719 356 final GuardedTypeConversion next = factories[i].convertToType(sourceType, targetType);
attila@90 357 if(next != null) {
attila@719 358 cacheable = cacheable && next.isCacheable();
attila@719 359 final GuardedInvocation conversionInvocation = next.getConversionInvocation();
attila@719 360 conversionInvocation.assertType(type);
attila@719 361 last = conversionInvocation.compose(last);
attila@90 362 }
attila@90 363 }
attila@719 364 if(last == identity) {
attila@719 365 return IDENTITY_CONVERSION;
attila@719 366 }
attila@719 367 if(cacheable) {
attila@719 368 return last;
attila@719 369 }
attila@719 370 throw new NotCacheableConverter(last);
attila@90 371 }
attila@90 372
attila@90 373 /*private*/ static final MethodHandle IDENTITY_CONVERSION = MethodHandles.identity(Object.class);
attila@719 374
attila@719 375 private static class NotCacheableConverter extends RuntimeException {
attila@719 376 final MethodHandle converter;
attila@719 377
attila@719 378 NotCacheableConverter(final MethodHandle converter) {
attila@719 379 super("", null, false, false);
attila@719 380 this.converter = converter;
attila@719 381 }
attila@719 382 }
attila@101 383 }

mercurial