- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathValueConversions.java
612 lines (553 loc) · 19.6 KB
/
ValueConversions.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
/*
* Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
packagesun.invoke.util;
importjava.lang.invoke.MethodHandle;
importjava.lang.invoke.MethodHandles;
importjava.lang.invoke.MethodHandles.Lookup;
importjava.lang.invoke.MethodType;
importjdk.internal.vm.annotation.Stable;
publicclassValueConversions {
privatestaticfinalClass<?> THIS_CLASS = ValueConversions.class;
privatestaticfinalLookupIMPL_LOOKUP = MethodHandles.lookup();
/**
* Thread-safe canonicalized mapping from Wrapper to MethodHandle
* with unsynchronized reads and synchronized writes.
* It's safe to publish MethodHandles by data race because they are immutable.
*/
privatestaticclassWrapperCache {
@Stable
privatefinalMethodHandle[] map = newMethodHandle[Wrapper.COUNT];
publicMethodHandleget(Wrapperw) {
returnmap[w.ordinal()];
}
publicsynchronizedMethodHandleput(finalWrapperw, finalMethodHandlemh) {
MethodHandleprev = map[w.ordinal()];
if (prev != null) {
returnprev;
} else {
map[w.ordinal()] = mh;
returnmh;
}
}
}
privatestaticWrapperCache[] newWrapperCaches(intn) {
WrapperCache[] caches = newWrapperCache[n];
for (inti = 0; i < n; i++)
caches[i] = newWrapperCache();
returncaches;
}
//--- Converting references to values.
// There are several levels of this unboxing conversions:
// no conversions: exactly Integer.valueOf, etc.
// implicit conversions sanctioned by JLS 5.1.2, etc.
// explicit conversions as allowed by explicitCastArguments
staticintunboxInteger(Integerx) {
returnx;
}
staticintunboxInteger(Objectx, booleancast) {
if (xinstanceofIntegeri)
returni;
returnprimitiveConversion(Wrapper.INT, x, cast).intValue();
}
staticbyteunboxByte(Bytex) {
returnx;
}
staticbyteunboxByte(Objectx, booleancast) {
if (xinstanceofByteb)
returnb;
returnprimitiveConversion(Wrapper.BYTE, x, cast).byteValue();
}
staticshortunboxShort(Shortx) {
returnx;
}
staticshortunboxShort(Objectx, booleancast) {
if (xinstanceofShorts)
returns;
returnprimitiveConversion(Wrapper.SHORT, x, cast).shortValue();
}
staticbooleanunboxBoolean(Booleanx) {
returnx;
}
staticbooleanunboxBoolean(Objectx, booleancast) {
if (xinstanceofBooleanb)
returnb;
return (primitiveConversion(Wrapper.BOOLEAN, x, cast).intValue() & 1) != 0;
}
staticcharunboxCharacter(Characterx) {
returnx;
}
staticcharunboxCharacter(Objectx, booleancast) {
if (xinstanceofCharacterc)
returnc;
return (char) primitiveConversion(Wrapper.CHAR, x, cast).intValue();
}
staticlongunboxLong(Longx) {
returnx;
}
staticlongunboxLong(Objectx, booleancast) {
if (xinstanceofLongl)
returnl;
returnprimitiveConversion(Wrapper.LONG, x, cast).longValue();
}
staticfloatunboxFloat(Floatx) {
returnx;
}
staticfloatunboxFloat(Objectx, booleancast) {
if (xinstanceofFloatf)
returnf;
returnprimitiveConversion(Wrapper.FLOAT, x, cast).floatValue();
}
staticdoubleunboxDouble(Doublex) {
returnx;
}
staticdoubleunboxDouble(Objectx, booleancast) {
if (xinstanceofDoubled)
returnd;
returnprimitiveConversion(Wrapper.DOUBLE, x, cast).doubleValue();
}
privatestaticMethodTypeunboxType(Wrapperwrap, intkind) {
if (kind == 0)
returnMethodType.methodType(wrap.primitiveType(), wrap.wrapperType());
returnMethodType.methodType(wrap.primitiveType(), Object.class, boolean.class);
}
privatestaticfinalWrapperCache[] UNBOX_CONVERSIONS = newWrapperCaches(4);
privatestaticMethodHandleunbox(Wrapperwrap, intkind) {
// kind 0 -> strongly typed with NPE
// kind 1 -> strongly typed but zero for null,
// kind 2 -> asType rules: accept multiple box types but only widening conversions with NPE
// kind 3 -> explicitCastArguments rules: allow narrowing conversions, zero for null
WrapperCachecache = UNBOX_CONVERSIONS[kind];
MethodHandlemh = cache.get(wrap);
if (mh != null) {
returnmh;
}
// slow path
switch (wrap) {
caseOBJECT:
caseVOID:
thrownewIllegalArgumentException("unbox "+wrap);
}
// look up the method
Stringname = "unbox" + wrap.wrapperSimpleName();
MethodTypetype = unboxType(wrap, kind);
try {
mh = IMPL_LOOKUP.findStatic(THIS_CLASS, name, type);
} catch (ReflectiveOperationExceptionex) {
mh = null;
}
if (mh != null) {
if (kind > 0) {
booleancast = (kind != 2);
mh = MethodHandles.insertArguments(mh, 1, cast);
}
if (kind == 1) { // casting but exact (null -> zero)
mh = mh.asType(unboxType(wrap, 0));
}
returncache.put(wrap, mh);
}
thrownewIllegalArgumentException("cannot find unbox adapter for " + wrap
+ (kind <= 1 ? " (exact)" : kind == 3 ? " (cast)" : ""));
}
/** Return an exact unboxer for the given primitive type. */
publicstaticMethodHandleunboxExact(Wrappertype) {
returnunbox(type, 0);
}
/** Return an exact unboxer for the given primitive type, with optional null-to-zero conversion.
* The boolean says whether to throw an NPE on a null value (false means unbox a zero).
* The type of the unboxer is of a form like (Integer)int.
*/
publicstaticMethodHandleunboxExact(Wrappertype, booleanthrowNPE) {
returnunbox(type, throwNPE ? 0 : 1);
}
/** Return a widening unboxer for the given primitive type.
* Widen narrower primitive boxes to the given type.
* Do not narrow any primitive values or convert null to zero.
* The type of the unboxer is of a form like (Object)int.
*/
publicstaticMethodHandleunboxWiden(Wrappertype) {
returnunbox(type, 2);
}
/** Return a casting unboxer for the given primitive type.
* Widen or narrow primitive values to the given type, or convert null to zero, as needed.
* The type of the unboxer is of a form like (Object)int.
*/
publicstaticMethodHandleunboxCast(Wrappertype) {
returnunbox(type, 3);
}
privatestaticfinalIntegerZERO_INT = 0, ONE_INT = 1;
//--- Primitive conversions
/**
* Produce a Number which represents the given value {@code x}
* according to the primitive type of the given wrapper {@code wrap}.
* Caller must invoke intValue, byteValue, longValue (etc.) on the result
* to retrieve the desired primitive value.
*/
publicstaticNumberprimitiveConversion(Wrapperwrap, Objectx, booleancast) {
// Maybe merge this code with Wrapper.convert/cast.
Numberres;
if (x == null) {
if (!cast) returnnull;
returnZERO_INT;
}
if (xinstanceofNumbern) {
res = n;
} elseif (xinstanceofBooleanb) {
res = b ? ONE_INT : ZERO_INT;
} elseif (xinstanceofCharacterc) {
res = (int) c;
} else {
// this will fail with the required ClassCastException:
res = (Number) x;
}
Wrapperxwrap = Wrapper.findWrapperType(x.getClass());
if (xwrap == null || !cast && !wrap.isConvertibleFrom(xwrap))
// this will fail with the required ClassCastException:
return (Number) wrap.wrapperType().cast(x);
returnres;
}
/**
* The JVM verifier allows boolean, byte, short, or char to widen to int.
* Support exactly this conversion, from a boxed value type Boolean,
* Byte, Short, Character, or Integer.
*/
publicstaticintwidenSubword(Objectx) {
if (xinstanceofIntegeri)
returni;
elseif (xinstanceofBooleanb)
returnfromBoolean(b);
elseif (xinstanceofCharacterc)
returnc;
elseif (xinstanceofShorts)
returns;
elseif (xinstanceofByteb)
returnb;
else
// Fail with a ClassCastException.
return (int) x;
}
//--- Converting primitives to references
staticIntegerboxInteger(intx) {
returnx;
}
staticByteboxByte(bytex) {
returnx;
}
staticShortboxShort(shortx) {
returnx;
}
staticBooleanboxBoolean(booleanx) {
returnx;
}
staticCharacterboxCharacter(charx) {
returnx;
}
staticLongboxLong(longx) {
returnx;
}
staticFloatboxFloat(floatx) {
returnx;
}
staticDoubleboxDouble(doublex) {
returnx;
}
privatestaticMethodTypeboxType(Wrapperwrap) {
// be exact, since return casts are hard to compose
Class<?> boxType = wrap.wrapperType();
returnMethodType.methodType(boxType, wrap.primitiveType());
}
privatestaticfinalWrapperCache[] BOX_CONVERSIONS = newWrapperCaches(1);
publicstaticMethodHandleboxExact(Wrapperwrap) {
WrapperCachecache = BOX_CONVERSIONS[0];
MethodHandlemh = cache.get(wrap);
if (mh != null) {
returnmh;
}
// look up the method
Stringname = "box" + wrap.wrapperSimpleName();
MethodTypetype = boxType(wrap);
try {
mh = IMPL_LOOKUP.findStatic(THIS_CLASS, name, type);
} catch (ReflectiveOperationExceptionex) {
mh = null;
}
if (mh != null) {
returncache.put(wrap, mh);
}
thrownewIllegalArgumentException("cannot find box adapter for " + wrap);
}
//--- Constant functions
staticvoidignore(Objectx) {
// no value to return; this is an unbox of null
}
privatestaticclassHandles {
staticfinalMethodHandleIGNORE;
static {
try {
MethodTypeidType = MethodType.genericMethodType(1);
MethodTypeignoreType = idType.changeReturnType(void.class);
IGNORE = IMPL_LOOKUP.findStatic(THIS_CLASS, "ignore", ignoreType);
} catch (NoSuchMethodException | IllegalAccessExceptionex) {
thrownewInternalError("uncaught exception", ex);
}
}
}
publicstaticMethodHandleignore() {
returnHandles.IGNORE;
}
//--- Primitive conversions.
// These are supported directly by the JVM, usually by a single instruction.
// In the case of narrowing to a subword, there may be a pair of instructions.
// In the case of booleans, there may be a helper routine to manage a 1-bit value.
// This is the full 8x8 matrix (minus the diagonal).
// narrow double to all other types:
staticfloatdoubleToFloat(doublex) { // bytecode: d2f
return (float) x;
}
staticlongdoubleToLong(doublex) { // bytecode: d2l
return (long) x;
}
staticintdoubleToInt(doublex) { // bytecode: d2i
return (int) x;
}
staticshortdoubleToShort(doublex) { // bytecodes: d2i, i2s
return (short) x;
}
staticchardoubleToChar(doublex) { // bytecodes: d2i, i2c
return (char) x;
}
staticbytedoubleToByte(doublex) { // bytecodes: d2i, i2b
return (byte) x;
}
staticbooleandoubleToBoolean(doublex) {
returntoBoolean((byte) x);
}
// widen float:
staticdoublefloatToDouble(floatx) { // bytecode: f2d
returnx;
}
// narrow float:
staticlongfloatToLong(floatx) { // bytecode: f2l
return (long) x;
}
staticintfloatToInt(floatx) { // bytecode: f2i
return (int) x;
}
staticshortfloatToShort(floatx) { // bytecodes: f2i, i2s
return (short) x;
}
staticcharfloatToChar(floatx) { // bytecodes: f2i, i2c
return (char) x;
}
staticbytefloatToByte(floatx) { // bytecodes: f2i, i2b
return (byte) x;
}
staticbooleanfloatToBoolean(floatx) {
returntoBoolean((byte) x);
}
// widen long:
staticdoublelongToDouble(longx) { // bytecode: l2d
returnx;
}
staticfloatlongToFloat(longx) { // bytecode: l2f
returnx;
}
// narrow long:
staticintlongToInt(longx) { // bytecode: l2i
return (int) x;
}
staticshortlongToShort(longx) { // bytecodes: f2i, i2s
return (short) x;
}
staticcharlongToChar(longx) { // bytecodes: f2i, i2c
return (char) x;
}
staticbytelongToByte(longx) { // bytecodes: f2i, i2b
return (byte) x;
}
staticbooleanlongToBoolean(longx) {
returntoBoolean((byte) x);
}
// widen int:
staticdoubleintToDouble(intx) { // bytecode: i2d
returnx;
}
staticfloatintToFloat(intx) { // bytecode: i2f
returnx;
}
staticlongintToLong(intx) { // bytecode: i2l
returnx;
}
// narrow int:
staticshortintToShort(intx) { // bytecode: i2s
return (short) x;
}
staticcharintToChar(intx) { // bytecode: i2c
return (char) x;
}
staticbyteintToByte(intx) { // bytecode: i2b
return (byte) x;
}
staticbooleanintToBoolean(intx) {
returntoBoolean((byte) x);
}
// widen short:
staticdoubleshortToDouble(shortx) { // bytecode: i2d (implicit 's2i')
returnx;
}
staticfloatshortToFloat(shortx) { // bytecode: i2f (implicit 's2i')
returnx;
}
staticlongshortToLong(shortx) { // bytecode: i2l (implicit 's2i')
returnx;
}
staticintshortToInt(shortx) { // (implicit 's2i')
returnx;
}
// narrow short:
staticcharshortToChar(shortx) { // bytecode: i2c (implicit 's2i')
return (char)x;
}
staticbyteshortToByte(shortx) { // bytecode: i2b (implicit 's2i')
return (byte)x;
}
staticbooleanshortToBoolean(shortx) {
returntoBoolean((byte) x);
}
// widen char:
staticdoublecharToDouble(charx) { // bytecode: i2d (implicit 'c2i')
returnx;
}
staticfloatcharToFloat(charx) { // bytecode: i2f (implicit 'c2i')
returnx;
}
staticlongcharToLong(charx) { // bytecode: i2l (implicit 'c2i')
returnx;
}
staticintcharToInt(charx) { // (implicit 'c2i')
returnx;
}
// narrow char:
staticshortcharToShort(charx) { // bytecode: i2s (implicit 'c2i')
return (short)x;
}
staticbytecharToByte(charx) { // bytecode: i2b (implicit 'c2i')
return (byte)x;
}
staticbooleancharToBoolean(charx) {
returntoBoolean((byte) x);
}
// widen byte:
staticdoublebyteToDouble(bytex) { // bytecode: i2d (implicit 'b2i')
returnx;
}
staticfloatbyteToFloat(bytex) { // bytecode: i2f (implicit 'b2i')
returnx;
}
staticlongbyteToLong(bytex) { // bytecode: i2l (implicit 'b2i')
returnx;
}
staticintbyteToInt(bytex) { // (implicit 'b2i')
returnx;
}
staticshortbyteToShort(bytex) { // bytecode: i2s (implicit 'b2i')
return (short)x;
}
staticcharbyteToChar(bytex) { // bytecode: i2b (implicit 'b2i')
return (char)x;
}
// narrow byte to boolean:
staticbooleanbyteToBoolean(bytex) {
returntoBoolean(x);
}
// widen boolean to all types:
staticdoublebooleanToDouble(booleanx) {
returnfromBoolean(x);
}
staticfloatbooleanToFloat(booleanx) {
returnfromBoolean(x);
}
staticlongbooleanToLong(booleanx) {
returnfromBoolean(x);
}
staticintbooleanToInt(booleanx) {
returnfromBoolean(x);
}
staticshortbooleanToShort(booleanx) {
returnfromBoolean(x);
}
staticcharbooleanToChar(booleanx) {
return (char)fromBoolean(x);
}
staticbytebooleanToByte(booleanx) {
returnfromBoolean(x);
}
// helpers to force boolean into the conversion scheme:
staticbooleantoBoolean(bytex) {
// see javadoc for MethodHandles.explicitCastArguments
return ((x & 1) != 0);
}
staticbytefromBoolean(booleanx) {
// see javadoc for MethodHandles.explicitCastArguments
return (x ? (byte)1 : (byte)0);
}
privatestaticfinalWrapperCache[] CONVERT_PRIMITIVE_FUNCTIONS = newWrapperCaches(Wrapper.COUNT);
publicstaticMethodHandleconvertPrimitive(Wrapperwsrc, Wrapperwdst) {
WrapperCachecache = CONVERT_PRIMITIVE_FUNCTIONS[wsrc.ordinal()];
MethodHandlemh = cache.get(wdst);
if (mh != null) {
returnmh;
}
// slow path
Class<?> src = wsrc.primitiveType();
Class<?> dst = wdst.primitiveType();
MethodTypetype = MethodType.methodType(dst, src);
if (wsrc == wdst) {
mh = MethodHandles.identity(src);
} else {
assert(src.isPrimitive() && dst.isPrimitive());
try {
mh = IMPL_LOOKUP.findStatic(THIS_CLASS, src.getSimpleName()+"To"+capitalize(dst.getSimpleName()), type);
} catch (ReflectiveOperationExceptionex) {
mh = null;
}
}
if (mh != null) {
assert(mh.type() == type) : mh;
returncache.put(wdst, mh);
}
thrownewIllegalArgumentException("cannot find primitive conversion function for " +
src.getSimpleName()+" -> "+dst.getSimpleName());
}
publicstaticMethodHandleconvertPrimitive(Class<?> src, Class<?> dst) {
returnconvertPrimitive(Wrapper.forPrimitiveType(src), Wrapper.forPrimitiveType(dst));
}
privatestaticStringcapitalize(Stringx) {
returnCharacter.toUpperCase(x.charAt(0))+x.substring(1);
}
// handy shared exception makers (they simplify the common case code)
privatestaticInternalErrornewInternalError(Stringmessage, Throwablecause) {
returnnewInternalError(message, cause);
}
}