/
GenericsSTCTest.groovy
2348 lines (2067 loc) · 74.8 KB
/
GenericsSTCTest.groovy
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package groovy.transform.stc
import groovy.test.NotYetImplemented
import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit
/**
* Unit tests for static type checking : generics.
*/
class GenericsSTCTest extends StaticTypeCheckingTestCase {
void testDeclaration1() {
assertScript '''
List test = new LinkedList<String>()
'''
}
void testDeclaration2() {
assertScript '''
Map<String,Integer> obj = new HashMap<String,Integer>()
'''
}
void testDeclaration3() {
shouldFailWithMessages '''
Map<String,String> obj = new HashMap<String,Integer>()
''', 'Incompatible generic argument types. Cannot assign java.util.HashMap <String, Integer> to: java.util.Map <String, String>'
}
void testAddOnList() {
shouldFailWithMessages '''
List<String> list = []
list.add(1)
''', "[Static type checking] - Cannot find matching method java.util.List#add(int)"
}
void testAddOnList2() {
assertScript '''
List<String> list = []
list.add 'Hello'
'''
assertScript '''
List<Integer> list = []
list.add 1
'''
}
void testAddOnListWithDiamond() {
assertScript '''
List<String> list = new LinkedList<>()
list.add 'Hello'
'''
}
void testAddOnListUsingLeftShift() {
shouldFailWithMessages '''
List<String> list = []
list << 1
''', '[Static type checking] - Cannot call <T> java.util.List <String>#leftShift(T) with arguments [int] '
}
void testAddOnList2UsingLeftShift() {
assertScript '''
List<String> list = []
list << 'Hello'
'''
assertScript '''
List<Integer> list = []
list << 1
'''
}
void testAddOnListWithParameterizedTypeLeftShift() {
assertScript '''
class Trie<T> {}
List<Trie<String>> list = []
list << new Trie<String>()
'''
}
void testAddOnListWithDiamondUsingLeftShift() {
assertScript '''
List<String> list = new LinkedList<>()
list << 'Hello'
'''
}
void testListInferrenceWithNullElems() {
assertScript '''
List<String> strings = ['a', null]
assert strings == ['a',null]
'''
}
void testListInferrenceWithAllNullElems() {
assertScript '''
List<String> strings = [null, null]
assert strings == [null,null]
'''
}
void testAddOnListWithDiamondAndWrongType() {
shouldFailWithMessages '''
List<Integer> list = new LinkedList<>()
list.add 'Hello'
''', '[Static type checking] - Cannot call java.util.LinkedList <java.lang.Integer>#add(java.lang.Integer) with arguments [java.lang.String]'
}
void testAddOnListWithDiamondAndWrongTypeUsingLeftShift() {
shouldFailWithMessages '''
List<Integer> list = new LinkedList<>()
list << 'Hello'
''', '[Static type checking] - Cannot call <T> java.util.LinkedList <java.lang.Integer>#leftShift(T) with arguments [java.lang.String]'
}
void testAddOnListWithDiamondAndNullUsingLeftShift() {
assertScript '''
List<Integer> list = new LinkedList<>()
list << null
'''
}
void testReturnTypeInference() {
assertScript '''
class Foo<U> {
U method() { }
}
Foo<Integer> foo = new Foo<Integer>()
Integer result = foo.method()
'''
}
void testReturnTypeInferenceWithDiamond() {
assertScript '''
class Foo<U> {
U method() { }
}
Foo<Integer> foo = new Foo<>()
Integer result = foo.method()
'''
}
void testReturnTypeInferenceWithMethodGenerics1() {
assertScript '''
List<Long> list = Arrays.asList([0L,0L] as Long[])
assert list.size() == 2
'''
}
void testReturnTypeInferenceWithMethodGenerics2() {
assertScript '''
List<Long> list = Arrays.asList(0L,0L)
assert list.size() == 2
'''
}
void testReturnTypeInferenceWithMethodGenerics3() {
assertScript '''
Number number = Optional.of(42).get()
assert number.intValue() == 42
'''
}
// GROOVY-9796
void testReturnTypeInferenceWithMethodGenerics4() {
shouldFailWithMessages '''
Number number = Optional.of(42).orElse(Double.NaN)
assert number.intValue() == 42
''', '[Static type checking] - Cannot find matching method java.util.Optional#orElse(double).'
}
void testReturnTypeInferenceWithMethodGenerics5() {
assertScript '''
Number number = Optional.of((Number) 42).orElse(Double.NaN)
assert number.intValue() == 42
'''
}
// GROOVY-9796
void testReturnTypeInferenceWithMethodGenerics6() {
shouldFailWithMessages '''
Number number = Optional.ofNullable((Integer) null).orElse(42d)
assert number.intValue() == 42
''', '[Static type checking] - Cannot find matching method java.util.Optional#orElse(double).'
}
void testReturnTypeInferenceWithMethodGenerics7() {
assertScript '''
Number number = Optional.<Number>ofNullable((Integer) null).orElse(42d)
assert number.intValue() == 42
'''
}
void testDiamondInferrenceFromConstructor() {
assertScript '''
Set< Long > s2 = new HashSet<>()
'''
}
void testDiamondInferrenceFromConstructorWithoutAssignment() {
assertScript '''
new HashSet<>(Arrays.asList(0L,0L));
'''
}
void testDiamondInferrenceFromConstructor2() {
shouldFailWithMessages '''
Set< Number > s3 = new HashSet<>(Arrays.asList(0L,0L));
''', 'Cannot assign java.util.HashSet <java.lang.Long> to: java.util.Set <Number>'
}
void testDiamondInferrenceFromConstructor3() {
assertScript '''
Set<Number> s4 = new HashSet<Number>(Arrays.asList(0L,0L))
'''
}
void testLinkedListWithListArgument() {
assertScript '''
List<String> list = new LinkedList<String>(['1','2','3'])
'''
}
void testLinkedListWithListArgumentAndWrongElementTypes() {
shouldFailWithMessages '''
List<String> list = new LinkedList<String>([1,2,3])
''', 'Cannot call java.util.LinkedList <String>#<init>(java.util.Collection <? extends java.lang.String>) with arguments [java.util.List <java.lang.Integer>]'
}
void testIncompatibleGenericAssignment() {
shouldFailWithMessages '''
List<String> elements = ['a','b', 1]
''', 'Incompatible generic argument types. Cannot assign java.util.List <java.io.Serializable> to: java.util.List <String>'
}
void testGenericAssignmentWithSubClass() {
assertScript '''
List<String> list = new groovy.transform.stc.GenericsSTCTest.MyList()
'''
}
void testGenericAssignmentWithSubClassAndWrongGenericType() {
shouldFailWithMessages '''
List<Integer> list = new groovy.transform.stc.GenericsSTCTest.MyList()
''', 'Incompatible generic argument types'
}
void testAddShouldBeAllowedOnUncheckedGenerics() {
assertScript '''
List list = []
list.add 'Hello'
list.add 2
list.add 'the'
list.add 'world'
'''
}
void testAssignmentShouldFailBecauseOfLowerBound() {
shouldFailWithMessages '''
List<? super Number> list = ['string']
''', 'Number'
}
// GROOVY-9555
void testAssignmentShouldWorkForProperUpperBound() {
assertScript '''
interface I<T> {
}
class C implements I<Object> {
}
interface Factory {
def <T extends I> T getInstance(Class<T> clazz)
}
void test(Factory f) {
C c = f.getInstance(C)
assert c instanceof C
assert c instanceof I
}
test { Class clazz -> clazz.newInstance() }
'''
config.with {
targetDirectory = File.createTempDir()
jointCompilationOptions = [stubDir: File.createTempDir()]
}
File parentDir = File.createTempDir()
try {
def a = new File(parentDir, 'Face.java')
a.write '''
public interface Face<T> {
}
'''
def b = new File(parentDir, 'Impl.java')
b.write '''
public class Impl implements Face<Object> {
}
'''
def c = new File(parentDir, 'Supplier.java')
c.write '''
public interface Supplier {
public <T extends Face> T getInstance(Class<T> clazz);
}
'''
def d = new File(parentDir, 'Tester.groovy')
d.write '''
void test(Supplier s) {
def x = s.getInstance(Impl)
assert x instanceof Impl
assert x instanceof Face
}
test { Class clazz -> clazz.newInstance() }
'''
def loader = new GroovyClassLoader(this.class.classLoader)
def cu = new JavaAwareCompilationUnit(config, loader)
cu.addSources(a, b, c, d)
cu.compile()
loader.loadClass('Tester').main()
} finally {
parentDir.deleteDir()
config.targetDirectory.deleteDir()
config.jointCompilationOptions.stubDir.deleteDir()
}
}
void testGroovy5154() {
assertScript '''
class Foo {
def say() {
FooWithGenerics f
FooBound fb
f.say(fb)
}
}
class FooWithGenerics {
def <T extends FooBound> void say(T p) {
}
}
class FooBound {
}
new Foo()
'''
}
void testGroovy5154WithSubclass() {
assertScript '''
class Foo {
def say() {
FooWithGenerics f
FooBound2 fb
f.say(fb)
}
}
class FooWithGenerics {
def <T extends FooBound> void say(T p) {
}
}
class FooBound {
}
class FooBound2 extends FooBound {}
new Foo()
'''
}
void testGroovy5154WithIncorrectType() {
shouldFailWithMessages '''
class Foo {
def say() {
FooWithGenerics f
Object fb
f.say(fb)
}
}
class FooWithGenerics {
def <T extends FooBound> void say(T p) {
}
}
class FooBound {
}
new Foo()
''', 'Cannot find matching method FooWithGenerics#say(java.lang.Object)'
}
void testVoidReturnTypeInferrence() {
assertScript '''
Object m() {
def s = '1234'
println 'Hello'
}
'''
}
// GROOVY-5237
void testGenericTypeArgumentAsField() {
assertScript '''
class Container<T> {
private T initialValue
Container(T initialValue) { this.initialValue = initialValue }
T get() { initialValue }
}
Container<Date> c = new Container<Date>(new Date())
long time = c.get().time
'''
}
void testReturnAnntationClass() {
assertScript '''
import java.lang.annotation.Documented
Documented annotation = Deprecated.getAnnotation(Documented)
'''
}
void testReturnListOfParameterizedType() {
assertScript '''
class A {}
class B extends A { void bar() {} }
public <T extends A> List<T> foo() { [] }
List<B> list = foo()
list.add(new B())
'''
}
// GROOVY-6126
void testChoosesCorrectMethodOfParameterizedReturnType() {
assertScript '''
class Loader {
public <T> T load(Class<T> entityClass, Serializable id) {entityClass.newInstance()}
public void load(final Object entity, final Serializable id) {}
}
class MyClass<D> {
Class<D> persistentClass
Loader hibernateTemplate = new Loader()
MyClass(Class<D> c) {
this.persistentClass = c
}
D load(Serializable id) {
id = convertIdentifier(id)
if (id != null) {
return hibernateTemplate.load(persistentClass, id)
}
}
Serializable convertIdentifier(Serializable s) {"1"}
}
class Foo{}
MyClass<Foo> mc = new MyClass(Foo)
Foo foo = mc.load("2")'''
}
void testMethodCallWithClassParameterUsingClassLiteralArg() {
assertScript '''
class A {}
class B extends A {}
class Foo {
void m(Class<? extends A> clazz) {}
}
new Foo().m(B)
'''
}
void testMethodCallWithClassParameterUsingClassLiteralArgWithoutWrappingClass() {
assertScript '''
class A {}
class B extends A {}
void m(Class<? extends A> clazz) {}
m(B)
'''
}
// GROOVY-9460
void testMethodCallWithClassParameterUnbounded() {
assertScript '''
class Bar {
static void baz(Class<?> target) {
}
}
class Foo<D> { // cannot be "T" because that matches type parameter in Class
void test(Class<D> param) {
Bar.baz(param) // Cannot call Bar#baz(java.lang.Class<?>) with arguments [java.lang.Class<D>]
}
}
new Foo<String>().test(String.class)
'''
}
void testConstructorCallWithClassParameterUsingClassLiteralArg() {
assertScript '''
class A {}
class B extends A {}
class C extends B {}
class Foo {
Foo(Class<? extends A> clazz) {}
}
new Foo(B)
new Foo(C)
'''
}
void testConstructorCallWithClassParameterUsingClassLiteralArgAndInterface() {
assertScript '''
interface A {}
class B implements A {}
class C extends B {}
class Foo {
Foo(Class<? extends A> clazz) {}
}
new Foo(B)
new Foo(C)
'''
}
void testPutMethodWithPrimitiveValue() {
assertScript '''
Map<String, Integer> map = new HashMap<String,Integer>()
map.put('hello', 1)
'''
}
void testPutMethodWithWrongValueType() {
shouldFailWithMessages '''
Map<String, Integer> map = new HashMap<String,Integer>()
map.put('hello', new Object())
''', '[Static type checking] - Cannot call java.util.HashMap <String, Integer>#put(java.lang.String, java.lang.Integer) with arguments [java.lang.String, java.lang.Object]'
}
void testPutMethodWithPrimitiveValueAndArrayPut() {
assertScript '''
Map<String, Integer> map = new HashMap<String,Integer>()
map['hello'] = 1
'''
}
void testShouldComplainAboutToInteger() {
String code = '''
class Test {
static test2() {
if (new Random().nextBoolean()) {
def a = new ArrayList<String>()
a << "a" << "b" << "c"
return a
} else {
def b = new LinkedList<Number>()
b << 1 << 2 << 3
return b
}
}
static test() {
def result = test2()
result[0].toInteger()
//result[0].toString()
}
}
new Test()
'''
shouldFailWithMessages code,
'Cannot find matching method java.lang.Object#getAt(int)',
'Cannot find matching method java.lang.Object#toInteger()'
}
void testAssignmentOfNewInstance() {
assertScript '''
class Foo {
static Class clazz = Date
public static void main(String... args) {
@ASTTest(phase=INSTRUCTION_SELECTION, value={
assert node.getNodeMetaData(INFERRED_TYPE) == OBJECT_TYPE
})
def obj = clazz.newInstance()
}
}
'''
}
// GROOVY-5415
void testShouldUseMethodGenericType1() {
assertScript '''import groovy.transform.stc.GenericsSTCTest.ClassA
class ClassB {
void bar() {
def ClassA<Long> a = new ClassA<Long>();
a.foo(this.getClass());
}
}
new ClassB()
'''
}
// GROOVY-5415
void testShouldUseMethodGenericType2() {
shouldFailWithMessages '''import groovy.transform.stc.GenericsSTCTest.ClassA
class ClassB {
void bar() {
def ClassA<Long> a = new ClassA<Long>();
a.bar(this.getClass());
}
}
new ClassB()
''', 'Cannot call <X> groovy.transform.stc.GenericsSTCTest$ClassA <Long>#bar(java.lang.Class <Long>) with arguments [java.lang.Class <? extends java.lang.Object>]'
}
// GROOVY-8961
void testShouldUseMethodGenericType3() {
assertScript '''
void setM(List<String> strings) {
}
void test() {
m = Collections.emptyList() // Cannot assign value of type List<T> to variable of List<String>
}
test()
'''
assertScript '''
void setM(Collection<String> strings) {
}
void test() {
m = Collections.emptyList()
}
test()
'''
assertScript '''
void setM(Iterable<String> strings) {
}
void test() {
m = Collections.emptyList()
}
test()
'''
shouldFailWithMessages '''
void setM(List<String> strings) {
}
void test() {
m = Collections.<Integer>emptyList()
}
''', '[Static type checking] - Cannot assign value of type java.util.List <Integer> to variable of type java.util.List <String>'
}
// GROOVY-9734
void testShouldUseMethodGenericType4() {
assertScript '''
void m(List<String> strings) {
}
void test() {
m(Collections.emptyList()) // Cannot call m(List<String>) with arguments [List<T>]
}
test()
'''
assertScript '''
void m(Collection<String> strings) {
}
void test() {
m(Collections.emptyList())
}
test()
'''
assertScript '''
void m(Iterable<String> strings) {
}
void test() {
m(Collections.emptyList())
}
test()
'''
}
// GROOVY-9751
void testShouldUseMethodGenericType5() {
assertScript '''
interface Service {
Number transform(String s)
}
void test(Service service) {
Set<Number> numbers = []
List<String> strings = ['1','2','3']
numbers.addAll(strings.collect(service.&transform))
}
test({ String s -> Integer.valueOf(s) } as Service)
'''
}
void testShouldUseMethodGenericType6() {
assertScript '''
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def type = node.rightExpression.getNodeMetaData(INFERRED_TYPE)
assert type.equals(CLOSURE_TYPE)
assert type.getGenericsTypes()[0].getType().equals(STRING_TYPE)
})
def ptr = "".&toString
'''
assertScript '''
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def type = node.rightExpression.getNodeMetaData(INFERRED_TYPE)
assert type.equals(CLOSURE_TYPE)
assert type.getGenericsTypes()[0].getType().equals(Double_TYPE)
})
def ptr = Math.&abs
'''
}
// GROOVY-9762
void testShouldUseMethodGenericType7() {
for (toList in ['{ list(it) }', 'o -> list(o)', 'this.&list', 'this::list']) {
assertScript """
def <T> List<T> list(T item) {
return [item]
}
def test() {
Optional<Integer> opt = Optional.ofNullable(1)
List<Integer> ret = opt.map($toList).get()
return ret
}
assert test() == [1]
"""
}
}
// GROOVY-9803
void testShouldUseMethodGenericType8() {
assertScript '''
def opt = Optional.of(42)
.map(Collections::singleton)
.map(x -> x.first().intValue()) // Cannot find matching method java.lang.Object#intValue()
assert opt.get() == 42
'''
// same as above but with separate type parameter name for each location
assertScript '''
abstract class A<I,O> {
abstract O apply(I input)
}
class C<T> {
static <U> C<U> of(U item) {
new C<U>()
}
def <V> C<V> map(A<? super T, ? super V> func) {
new C<V>()
}
}
class D {
static <W> Set<W> wrap(W o) {
}
}
void test() {
def c = C.of(42)
def d = c.map(D.&wrap)
def e = d.map(x -> x.first().intValue())
}
test()
'''
}
// GROOVY-5516
void testAddAllWithCollectionShouldBeAllowed() {
assertScript '''import org.codehaus.groovy.transform.stc.ExtensionMethodNode
List<String> list = ['a','b','c']
Collection<String> e = list.findAll { it }
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def dmt = node.rightExpression.getNodeMetaData(DIRECT_METHOD_CALL_TARGET)
assert dmt instanceof ExtensionMethodNode == false
assert dmt.name == 'addAll'
assert dmt.declaringClass == make(List)
})
boolean r = list.addAll(e)
'''
}
void testAddAllWithCollectionShouldNotBeAllowed() {
shouldFailWithMessages '''
List<String> list = ['a','b','c']
Collection<Integer> e = (Collection<Integer>) [1,2,3]
boolean r = list.addAll(e)
''', 'Cannot call java.util.List <java.lang.String>#addAll(java.util.Collection <? extends java.lang.String>) with arguments [java.util.Collection <Integer>]'
}
// GROOVY-5528
void testAssignmentToInterfaceFromUserClassWithGenerics() {
assertScript '''class UserList<T> extends LinkedList<T> {}
List<String> list = new UserList<String>()
'''
}
// GROOVY-5559
void testGStringInListShouldNotBeConsideredAsAString() {
assertScript '''import org.codehaus.groovy.ast.tools.WideningCategories.LowestUpperBoundClassNode as LUB
def bar = 1
@ASTTest(phase=INSTRUCTION_SELECTION, value={
assert node.getNodeMetaData(INFERRED_TYPE) == LIST_TYPE
assert node.getNodeMetaData(INFERRED_TYPE).genericsTypes[0].type instanceof LUB
})
def list = ["foo", "$bar"]
'''
shouldFailWithMessages '''import org.codehaus.groovy.ast.tools.WideningCategories.LowestUpperBoundClassNode as LUB
def bar = 1
@ASTTest(phase=INSTRUCTION_SELECTION, value={
assert node.getNodeMetaData(INFERRED_TYPE) == LIST_TYPE
assert node.getNodeMetaData(INFERRED_TYPE).genericsTypes[0].type instanceof LUB
})
List<String> list = ["foo", "$bar"]
''', 'You are trying to use a GString'
shouldFailWithMessages '''
def bar = 1
@ASTTest(phase=INSTRUCTION_SELECTION, value={
assert node.getNodeMetaData(INFERRED_TYPE) == LIST_TYPE
assert node.getNodeMetaData(INFERRED_TYPE).genericsTypes[0].type == GSTRING_TYPE
})
List<String> list = ["$bar"] // single element means no LUB
''', 'You are trying to use a GString'
}
// GROOVY-5559: related behaviour
void testGStringString() {
assertScript '''
int i = 1
@ASTTest(phase=INSTRUCTION_SELECTION, value={
assert node.getNodeMetaData(INFERRED_TYPE) == GSTRING_TYPE
})
def str = "foo$i"
assert str == 'foo1'
'''
}
// GROOVY-5594
void testMapEntryUsingPropertyNotation() {
assertScript '''
Map.Entry<Date, Integer> entry = null
@ASTTest(phase=INSTRUCTION_SELECTION, value={
assert node.getNodeMetaData(INFERRED_TYPE) == make(Date)
})
def k = entry?.key
@ASTTest(phase=INSTRUCTION_SELECTION, value={
assert node.getNodeMetaData(INFERRED_TYPE) == Integer_TYPE
})
def v = entry?.value
'''
}
void testInferenceFromMap() {
assertScript '''
Map<Date, Integer> map = [:]
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def infType = node.getNodeMetaData(INFERRED_TYPE)
assert infType == make(Set)
def entryInfType = infType.genericsTypes[0].type
assert entryInfType == make(Map.Entry)
assert entryInfType.genericsTypes[0].type == make(Date)
assert entryInfType.genericsTypes[1].type == Integer_TYPE
})
def entries = map?.entrySet()
'''
}
void testInferenceFromListOfMaps() {
assertScript '''
List<Map<Date, Integer>> maps = []
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def listType = node.getNodeMetaData(INFERRED_TYPE)
assert listType == Iterator_TYPE
def infType = listType.genericsTypes[0].type
assert infType == make(Map)
assert infType.genericsTypes[0].type == make(Date)
assert infType.genericsTypes[1].type == Integer_TYPE
})
def iter = maps?.iterator()
'''
}
void testAssignNullMapWithGenerics() {
assertScript '''
Map<String, Integer> foo = null
Integer result = foo?.get('a')
'''
}
void testAssignNullListWithGenerics() {
assertScript '''
List<Integer> foo = null
Integer result = foo?.get(0)
'''
}
void testAssignNullListWithGenericsWithSequence() {
assertScript '''
List<Integer> foo = [1]
foo = null
Integer result = foo?.get(0)
'''
}
void testMethodCallWithArgumentUsingNestedGenerics() {
assertScript '''
ThreadLocal<Map<Integer, String>> cachedConfigs = new ThreadLocal<Map<Integer, String>>()
def configs = new HashMap<Integer, String>()
cachedConfigs.set configs
'''
}
void testInferDiamondUsingAIC() {
shouldFailWithMessages '''
Map<String,Date> map = new HashMap<>() {}
''', 'Cannot use diamond <> with anonymous inner classes'
}
// GROOVY-5614
void testInferDiamondForFields() {
assertScript '''
class Rules {
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def type = node.initialExpression.getNodeMetaData(INFERRED_TYPE)
assert type == make(HashMap)
assert type.genericsTypes.length == 2
assert type.genericsTypes[0].type == Integer_TYPE
assert type.genericsTypes[1].type == make(Date)
})
final Map<Integer, Date> bindings1 = new HashMap<>();
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def type = node.initialExpression.getNodeMetaData(INFERRED_TYPE)
assert type == make(HashMap)
assert type.genericsTypes.length == 2
assert type.genericsTypes[0].type == STRING_TYPE
assert type.genericsTypes[1].type == STRING_TYPE
})
final Map<String, String> bindings2 = new HashMap<>();
}
def r = new Rules()
r.bindings1[3] = new Date()
assert r.bindings1.containsKey(3)
r.bindings2['a'] = 'A'
r.bindings2.put('b', 'B')
'''
}
void testInferDiamondForAssignment() {
assertScript '''
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def type = node.getNodeMetaData(INFERRED_TYPE)
assert type == make(HashMap)
assert type.genericsTypes.length == 2
assert type.genericsTypes[0].type == STRING_TYPE
assert type.genericsTypes[1].type == STRING_TYPE
type = node.rightExpression.getNodeMetaData(INFERRED_TYPE)
assert type == make(HashMap)
assert type.genericsTypes.length == 2
assert type.genericsTypes[0].type == STRING_TYPE
assert type.genericsTypes[1].type == STRING_TYPE
})
Map<String, String> map = new HashMap<>()
'''
}
void testInferDiamondForAssignmentWithDates() {
assertScript '''
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def DATE = make(Date)
def type = node.getNodeMetaData(INFERRED_TYPE)
assert type == make(HashMap)
assert type.genericsTypes.length == 2
assert type.genericsTypes[0].type == DATE
assert type.genericsTypes[1].type == DATE
type = node.rightExpression.getNodeMetaData(INFERRED_TYPE)
assert type == make(HashMap)
assert type.genericsTypes.length == 2
assert type.genericsTypes[0].type == DATE