/
AsCollectionsTest.java
593 lines (516 loc) 路 19.8 KB
/
AsCollectionsTest.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
/*
* Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.api.test.host;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.HostAccess;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.TruffleLanguage;
import com.oracle.truffle.api.TruffleLanguage.Env;
import com.oracle.truffle.api.interop.InteropException;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.InvalidArrayIndexException;
import com.oracle.truffle.api.interop.TruffleObject;
import com.oracle.truffle.api.interop.UnknownIdentifierException;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.library.ExportLibrary;
import com.oracle.truffle.api.library.ExportMessage;
import com.oracle.truffle.api.test.polyglot.ProxyLanguage;
import com.oracle.truffle.tck.tests.TruffleTestAssumptions;
@SuppressWarnings({"rawtypes", "unchecked"})
public class AsCollectionsTest {
private static final InteropLibrary INTEROP = InteropLibrary.getFactory().getUncached();
@BeforeClass
public static void runWithWeakEncapsulationOnly() {
TruffleTestAssumptions.assumeWeakEncapsulation();
}
private Context context;
private Env env;
@Before
public void enterContext() {
context = Context.newBuilder().allowHostAccess(HostAccess.ALL).build();
ProxyLanguage.setDelegate(new ProxyLanguage() {
@Override
protected LanguageContext createContext(Env contextEnv) {
env = contextEnv;
return super.createContext(contextEnv);
}
});
context.initialize(ProxyLanguage.ID);
context.enter();
}
@After
public void leaveContext() {
context.leave();
context.close();
}
protected <T> T asJavaObject(Class<T> type, TruffleObject truffleObject) {
return context.asValue(truffleObject).as(type);
}
protected TruffleObject asTruffleObject(Object javaObj) {
return (TruffleObject) env.asGuestValue(javaObj);
}
@Test
public void testAsList() {
List origList = Arrays.asList(new String[]{"a", "b", "c"});
TruffleObject to = new ListBasedTO(origList);
assertTrue(INTEROP.hasArrayElements(to));
List interopList = asJavaObject(List.class, to);
assertEquals(origList.size(), interopList.size());
assertEquals(origList.toString(), new ArrayList<>(interopList).toString());
assertEquals(origList.toString(), interopList.toString());
// Test get out of bounds
try {
interopList.get(1000);
fail();
} catch (IndexOutOfBoundsException ioobex) {
// O.K.
}
// Test set out of bounds
try {
interopList.set(1000, "1000");
fail();
} catch (IndexOutOfBoundsException ioobex) {
// O.K.
}
// Test add is unsupported
try {
interopList.add("d");
fail();
} catch (UnsupportedOperationException ex) {
// O.K.
}
// Test add is unsupported
try {
interopList.add(0, "e");
fail();
} catch (UnsupportedOperationException ex) {
// O.K.
}
Object old = interopList.set(1, "bbb");
assertEquals("b", old);
assertEquals("bbb", interopList.get(1));
}
@Test
public void testAsExpandableList() {
ArrayList origList = new ArrayList(4);
origList.add("a");
origList.add("b");
origList.add("c");
TruffleObject to = new ExpandableListBasedTO(origList);
assertTrue(INTEROP.hasArrayElements(to));
List interopList = asJavaObject(List.class, to);
assertEquals(origList.size(), interopList.size());
assertEquals(origList.toString(), new ArrayList<>(interopList).toString());
assertEquals(origList.toString(), interopList.toString());
// Test get out of bounds
try {
interopList.get(3);
fail();
} catch (IndexOutOfBoundsException ioobex) {
// O.K.
}
// Test set out of bounds
try {
interopList.set(3, "1000");
fail();
} catch (IndexOutOfBoundsException ioobex) {
// O.K.
}
Object old = interopList.set(1, "bbb");
assertEquals("b", old);
assertEquals("bbb", interopList.get(1));
// Test add out of bounds
try {
interopList.add(1000, "1000");
fail();
} catch (IndexOutOfBoundsException ioobex) {
// O.K.
}
try {
interopList.add(-1, "-1");
fail();
} catch (IndexOutOfBoundsException ioobex) {
// O.K.
}
// test add/append with no index given
interopList.add("ccc");
assertEquals("ccc", interopList.get(3));
// test add minimum index
interopList.add(0, "ddd");
// test add in between index
interopList.add(1, "eee");
// test add maximum index
interopList.add(6, "fff");
assertEquals("ddd", interopList.get(0));
assertEquals("eee", interopList.get(1));
assertEquals("a", interopList.get(2));
assertEquals("bbb", interopList.get(3));
assertEquals("c", interopList.get(4));
assertEquals("ccc", interopList.get(5));
assertEquals("fff", interopList.get(6));
}
@Test
public void testAsMap() {
Map<String, String> origMap = new LinkedHashMap<>();
for (int i = 10; i <= 100; i += 10) {
origMap.put(Integer.toString(i), Integer.toHexString(i));
}
TruffleObject to = new MapBasedTO(origMap);
assertFalse(INTEROP.hasArrayElements(to));
Map interopMap = asJavaObject(Map.class, to);
assertEquals(origMap.size(), interopMap.size());
assertEquals(origMap.toString(), new LinkedHashMap<>(interopMap).toString());
assertEquals(origMap.toString(), interopMap.toString());
assertNull(interopMap.get("unknown"));
Object old = interopMap.put("10", "101010");
assertEquals("a", old);
assertEquals("101010", interopMap.get("10"));
old = interopMap.put("new", "news");
assertNull(old);
assertEquals("news", interopMap.get("new"));
}
@Test
public void testAsJavaObjectMapArray() {
MapBasedTO to = new MapBasedTO(Collections.singletonMap("foo", "bar"));
MapBasedTO[] array = new MapBasedTO[]{to};
Map<?, ?>[] result = asJavaObject(Map[].class, asTruffleObject(array));
assertEquals(1, result.length);
assertEquals(1, result[0].size());
assertEquals("bar", result[0].get("foo"));
}
@Test
public void testAsJavaObjectListArray() {
ListBasedTO to = new ListBasedTO(Collections.singletonList("bar"));
ListBasedTO[] array = new ListBasedTO[]{to};
List<?>[] result = asJavaObject(List[].class, asTruffleObject(array));
assertEquals(1, result.length);
assertEquals(1, result[0].size());
assertEquals("bar", result[0].get(0));
}
public static class Validator {
@HostAccess.Export
public boolean validateMap(Map<String, Object> mapGen, Map mapRaw) {
for (Map map : new Map[]{mapGen, mapRaw}) {
assertEquals(1, map.size());
assertEquals("bar", map.get("foo"));
}
return true;
}
@HostAccess.Export
public boolean validateArrayOfMap(Map<String, Object>[] arrayOfMapGen, Map[] arrayOfMapRaw) {
for (Map[] arrayOfMap : new Map[][]{arrayOfMapGen, arrayOfMapRaw}) {
assertEquals(1, arrayOfMap.length);
Map map = arrayOfMap[0];
assertEquals(1, map.size());
assertEquals("bar", map.get("foo"));
}
return true;
}
@HostAccess.Export
public boolean validateListOfMap(List<Map<String, Object>> listOfMapGen, List<Map> listOfMapRaw) {
for (List<Map> listOfMap : new List[]{listOfMapGen, listOfMapRaw}) {
assertEquals(1, listOfMap.size());
Map map = listOfMap.get(0);
assertEquals(1, map.size());
assertEquals("bar", map.get("foo"));
}
return true;
}
}
@Test
public void testInvokeMap() throws InteropException {
TruffleObject validator = asTruffleObject(new Validator());
MapBasedTO mapTO = new MapBasedTO(Collections.singletonMap("foo", "bar"));
assertEquals(Boolean.TRUE, INTEROP.invokeMember(validator, "validateMap", mapTO, mapTO));
}
@Test
public void testInvokeArrayOfMap() throws InteropException {
TruffleObject validator = asTruffleObject(new Validator());
MapBasedTO mapTO = new MapBasedTO(Collections.singletonMap("foo", "bar"));
TruffleObject listOfMapTO = new ListBasedTO(Arrays.asList(mapTO));
assertEquals(Boolean.TRUE, INTEROP.invokeMember(validator, "validateArrayOfMap", listOfMapTO, listOfMapTO));
}
@Test
public void testInvokeListOfMap() throws InteropException {
TruffleObject validator = asTruffleObject(new Validator());
MapBasedTO mapTO = new MapBasedTO(Collections.singletonMap("foo", "bar"));
TruffleObject listOfMapTO = new ListBasedTO(Arrays.asList(mapTO));
assertEquals(Boolean.TRUE, INTEROP.invokeMember(validator, "validateListOfMap", listOfMapTO, listOfMapTO));
}
public interface ProxyValidator {
@HostAccess.Export
boolean test(List<Map> list);
}
@Test
public void testInvokeListOfMapProxy() throws InteropException {
TruffleObject validator = asTruffleObject(
Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{ProxyValidator.class}, (p, method, args) -> {
List<Map> listOfMap = (List<Map>) args[0];
assertEquals(1, listOfMap.size());
Map map = listOfMap.get(0);
assertEquals(1, map.size());
assertEquals("bar", map.get("foo"));
return true;
}));
MapBasedTO mapTO = new MapBasedTO(Collections.singletonMap("foo", "bar"));
TruffleObject listOfMapTO = new ListBasedTO(Arrays.asList(mapTO));
assertEquals(Boolean.TRUE, INTEROP.invokeMember(validator, "test", listOfMapTO));
}
@ExportLibrary(InteropLibrary.class)
@SuppressWarnings({"static-method", "unused"})
static final class ListBasedTO implements TruffleObject {
final List list;
ListBasedTO(List list) {
this.list = list;
}
@ExportMessage
boolean hasArrayElements() {
return true;
}
@ExportMessage
@TruffleBoundary
Object readArrayElement(long index) throws UnsupportedMessageException, InvalidArrayIndexException {
try {
return list.get((int) index);
} catch (IndexOutOfBoundsException ioob) {
throw InvalidArrayIndexException.create(index);
}
}
@ExportMessage
@TruffleBoundary
Object writeArrayElement(long index, Object value) throws UnsupportedMessageException, InvalidArrayIndexException {
try {
list.set((int) index, value);
return value;
} catch (IndexOutOfBoundsException ioob) {
throw InvalidArrayIndexException.create(index);
}
}
@ExportMessage
@TruffleBoundary
long getArraySize() {
return list.size();
}
@ExportMessage(name = "isArrayElementReadable")
@ExportMessage(name = "isArrayElementModifiable")
@ExportMessage(name = "isArrayElementInsertable")
boolean isArrayElementReadable(long index) {
return index >= 0 && index < getArraySize();
}
@ExportMessage
boolean hasLanguage() {
return true;
}
@ExportMessage
Class<? extends TruffleLanguage<?>> getLanguage() {
return ProxyLanguage.class;
}
@ExportMessage
@TruffleBoundary
Object toDisplayString(boolean sideEffects) {
return list.toString();
}
}
@ExportLibrary(InteropLibrary.class)
@SuppressWarnings({"static-method", "unused"})
static final class ExpandableListBasedTO implements TruffleObject {
final ArrayList list;
ExpandableListBasedTO(ArrayList list) {
this.list = list;
}
@ExportMessage
boolean hasArrayElements() {
return true;
}
@ExportMessage
@TruffleBoundary
Object readArrayElement(long index) throws InvalidArrayIndexException {
try {
return list.get((int) index);
} catch (IndexOutOfBoundsException ioob) {
throw InvalidArrayIndexException.create(index);
}
}
@ExportMessage
@TruffleBoundary
Object writeArrayElement(long index, Object value) throws InvalidArrayIndexException {
if (index == getArraySize()) {
return list.add(value);
} else {
try {
list.set((int) index, value);
return value;
} catch (IndexOutOfBoundsException ioob) {
throw InvalidArrayIndexException.create(index);
}
}
}
@ExportMessage
@TruffleBoundary
long getArraySize() {
return list.size();
}
@ExportMessage(name = "isArrayElementReadable")
@ExportMessage(name = "isArrayElementModifiable")
boolean isArrayElementReadable(long index) {
return index >= 0 && index < getArraySize();
}
@ExportMessage(name = "isArrayElementInsertable")
boolean isArrayElementModifiable(long index) {
return index >= 0 && index <= getArraySize();
}
@ExportMessage
boolean hasLanguage() {
return true;
}
@ExportMessage
Class<? extends TruffleLanguage<?>> getLanguage() {
return ProxyLanguage.class;
}
@ExportMessage
@TruffleBoundary
Object toDisplayString(boolean sideEffects) {
return list.toString();
}
}
@SuppressWarnings({"static-method", "unused"})
@ExportLibrary(InteropLibrary.class)
static final class MapBasedTO implements TruffleObject {
final Map map;
MapBasedTO(Map map) {
this.map = map;
}
@ExportMessage
boolean hasMembers() {
return true;
}
@ExportMessage
@TruffleBoundary
Object getMembers(boolean includeInternal) throws UnsupportedMessageException {
return new MapKeysTO(map.keySet().toArray());
}
@ExportMessage
@TruffleBoundary
Object readMember(String member) throws UnsupportedMessageException, UnknownIdentifierException {
Object value = map.get(member);
if (value == null) {
throw UnknownIdentifierException.create(member);
} else {
return value;
}
}
@ExportMessage
@TruffleBoundary
void writeMember(String member, Object value) throws UnsupportedMessageException, UnknownIdentifierException {
map.put(member, value);
}
@ExportMessage(name = "isMemberModifiable")
@ExportMessage(name = "isMemberReadable")
@TruffleBoundary
boolean isMemberReadable(String member) {
return member.contains(member);
}
@ExportMessage
@TruffleBoundary
boolean isMemberInsertable(String member) {
return !member.contains(member);
}
@ExportMessage
boolean hasLanguage() {
return true;
}
@ExportMessage
Class<? extends TruffleLanguage<?>> getLanguage() {
return ProxyLanguage.class;
}
@ExportMessage
@TruffleBoundary
Object toDisplayString(boolean sideEffects) {
return map.toString();
}
}
@ExportLibrary(InteropLibrary.class)
static final class MapKeysTO implements TruffleObject {
private final Object[] keys;
MapKeysTO(Object[] keys) {
this.keys = keys;
}
@SuppressWarnings("static-method")
@ExportMessage
boolean hasArrayElements() {
return true;
}
@ExportMessage
boolean isArrayElementReadable(long index) {
return index >= 0 && index < keys.length;
}
@ExportMessage
long getArraySize() {
return keys.length;
}
@ExportMessage
Object readArrayElement(long index) throws InvalidArrayIndexException {
try {
return keys[(int) index];
} catch (IndexOutOfBoundsException e) {
CompilerDirectives.transferToInterpreter();
throw InvalidArrayIndexException.create(index);
}
}
}
}