-
Notifications
You must be signed in to change notification settings - Fork 435
/
GenericsSTCTest.groovy
957 lines (846 loc) · 31.7 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
/*
* Copyright 2003-2012 the original author or authors.
*
* Licensed 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
/**
* Unit tests for static type checking : generics.
*
* @author Cedric Champeau
*/
class GenericsSTCTest extends StaticTypeCheckingTestCase {
void testDeclaration() {
assertScript '''
List test = new LinkedList<String>()
'''
}
void testDeclaration5() {
assertScript '''
Map<String,Integer> obj = new HashMap<String,Integer>()
'''
}
void testDeclaration6() {
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)
''', "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
''', 'Cannot find matching method java.util.List#leftShift(int)'
}
void testAddOnList2UsingLeftShift() {
assertScript '''
List<String> list = []
list << 'Hello'
'''
assertScript '''
List<Integer> list = []
list << 1
'''
}
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'
''', 'Cannot find matching method java.util.LinkedList#add(java.lang.String)'
}
void testAddOnListWithDiamondAndWrongTypeUsingLeftShift() {
shouldFailWithMessages '''
List<Integer> list = new LinkedList<>()
list << 'Hello'
''', 'Cannot find matching method java.util.LinkedList#leftShift(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 testReturnTypeInferenceWithMethodGenerics() {
assertScript '''
List<Long> list = Arrays.asList([0L,0L] as Long[])
'''
}
void testReturnTypeInferenceWithMethodGenericsAndVarArg() {
assertScript '''
List<Long> list = Arrays.asList(0L,0L)
'''
}
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 find matching method java.util.LinkedList#<init>(java.util.List <java.lang.Integer>)'
}
void testCompatibleGenericAssignmentWithInferrence() {
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'
}
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())
'''
}
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)
'''
}
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())
''', 'Cannot find matching method java.util.HashMap#put(java.lang.String, java.lang.Object)'
}
void testPutMethodWithPrimitiveValueAndArrayPut() {
assertScript '''
Map<String, Integer> map = new HashMap<String,Integer>()
map['hello'] = 1
'''
}
void testShouldComplainAboutToInteger() {
shouldFailWithMessages '''
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()
''', 'Cannot find matching method java.io.Serializable#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 find matching method groovy.transform.stc.GenericsSTCTest$ClassA#bar'
}
// 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 org.codehaus.groovy.runtime.DefaultGroovyMethods#addAll(java.util.Collection <java.lang.String>, java.lang.String[]) with arguments [java.util.List <java.lang.String>, 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
@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
assert type.genericsTypes[1].type == DATE
})
Map<Date, Date> map = new HashMap<>()
'''
}
void testInferDiamondForAssignmentWithDatesAndIllegalKeyUsingPut() {
shouldFailWithMessages '''
@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
assert type.genericsTypes[1].type == DATE
})
Map<Date, Date> map = new HashMap<>()
map.put('foo', new Date())
''', 'Cannot find matching method java.util.HashMap#put(java.lang.String, java.util.Date)'
}
void testInferDiamondForAssignmentWithDatesAndIllegalKeyUsingSquareBracket() {
shouldFailWithMessages '''
@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
assert type.genericsTypes[1].type == DATE
})
Map<Date, Date> map = new HashMap<>()
map['foo'] = new Date()
''', 'Cannot call org.codehaus.groovy.runtime.DefaultGroovyMethods#putAt(java.util.Map <java.util.Date, java.util.Date>, java.util.Date, java.util.Date) with arguments [java.util.HashMap <java.util.Date, java.util.Date>, java.lang.String, java.util.Date]'
}
void testInferDiamondForAssignmentWithDatesAndIllegalValueUsingPut() {
shouldFailWithMessages '''
@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
assert type.genericsTypes[1].type == DATE
})
Map<Date, Date> map = new HashMap<>()
map.put(new Date(), 'foo')
''', 'Cannot find matching method java.util.HashMap#put(java.util.Date, java.lang.String)'
}
void testInferDiamondForAssignmentWithDatesAndIllegalValueUsingSquareBracket() {
shouldFailWithMessages '''
@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
assert type.genericsTypes[1].type == DATE
})
Map<Date, Date> map = new HashMap<>()
map[new Date()] = 'foo'
''', 'Cannot assign value of type java.lang.String to variable of type java.util.Date'
}
void testCallMethodWithParameterizedArrayList() {
assertScript '''
class MyUtility {
def methodOne() {
def someFiles = new ArrayList<File>()
def someString = ''
methodTwo someString, someFiles
}
def methodTwo(String s, List<File> files) {}
}
new MyUtility()
'''
}
void testGenericTypeArrayOfDGMMethod() {
assertScript '''
int[] arr = [0,1,2,3]
assert arr.findAll() == [1,2,3]
'''
}
// GROOVY-5617
void testIntermediateListAssignmentOfGStrings() {
assertScript '''
def test() {
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def type = node.getNodeMetaData(INFERRED_TYPE)
assert type == make(List)
assert type.genericsTypes.length==1
assert type.genericsTypes[0].type == GSTRING_TYPE
})
List<GString> dates = ["${new Date()-1}", "${new Date()}", "${new Date()+1}"]
dates*.toUpperCase()
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def type = node.getNodeMetaData(INFERRED_TYPE)
assert type == make(List)
assert type.genericsTypes.length==1
assert type.genericsTypes[0].type == GSTRING_TYPE
})
List<GString> copied = []
copied.addAll(dates)
List<String> upper = copied*.toUpperCase()
}
test()
'''
}
// GROOVY-5650
void testRegressionInGenericsTypeInference() {
assertScript '''import groovy.transform.stc.GenericsSTCTest.JavaClassSupport as JavaClass
List<JavaClass.StringContainer> containers = new ArrayList<>();
containers.add(new JavaClass.StringContainer());
List<String> strings = JavaClass.unwrap(containers);
'''
}
// In Groovy, we do not throw warnings (in general) and in that situation, not for unchecked
// assignments like in Java
// In the following test, the LHS of the assignment uses generics, while the RHS does not.
// As we have the concept of flow typing too, we are facing a problem: what inferred type is the RHS?
void testUncheckedAssignment() {
assertScript '''
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def ift = node.getNodeMetaData(INFERRED_TYPE)
assert ift == make(List)
assert ift.isUsingGenerics()
def gts = ift.genericsTypes
assert gts.length==1
assert gts[0].type == STRING_TYPE
})
List<String> list = (List) null
'''
}
void testUncheckedAssignmentWithSuperInterface() {
assertScript '''
@ASTTest(phase=INSTRUCTION_SELECTION, value={
def ift = node.getNodeMetaData(INFERRED_TYPE)
assert ift == make(List)
assert ift.isUsingGenerics()
def gts = ift.genericsTypes
assert gts.length==1
assert gts[0].type == STRING_TYPE
})
Iterable<String> list = (List) null
'''
}
void testIncompatibleGenericsForTwoArguments() {
shouldFailWithMessages '''
public <T> void printEqual(T arg1, T arg2) {
println arg1 == arg2
}
printEqual(1, 'foo')
''', '#printEqual(java.lang.Object <T>, java.lang.Object <T>) with arguments [int, java.lang.String]'
}
void testIncompatibleGenericsForTwoArgumentsUsingEmbeddedPlaceholder() {
shouldFailWithMessages '''
public <T> void printEqual(T arg1, List<T> arg2) {
println arg1 == arg2
}
printEqual(1, ['foo'])
''', '#printEqual(java.lang.Object <T>, java.util.List <T>) with arguments [int, java.util.List <java.lang.String>]'
}
void testGroovy5748() {
assertScript '''
interface IStack<T> {
INonEmptyStack<T, ? extends IStack<T>> push(T x)
}
interface IEmptyStack<T> extends IStack<T> {
INonEmptyStack<T, IEmptyStack<T>> push(T x)
}
interface INonEmptyStack<T, TStackBeneath extends IStack<T>> extends IStack<T> {
T getTop()
TStackBeneath pop()
INonEmptyStack<T, INonEmptyStack<T, TStackBeneath>> push(T x)
}
class EmptyStack<T> implements IEmptyStack<T> {
INonEmptyStack<T, IEmptyStack<T>> push(T x) {
new NonEmptyStack<T, IEmptyStack<T>>(x, this)
}
}
class NonEmptyStack<T, TStackBeneath extends IStack<T>>
implements INonEmptyStack<T, TStackBeneath> {
private final TStackBeneath stackBeneathTop;
private final T top
NonEmptyStack(T top, TStackBeneath stackBeneathTop) {
this.top = top
this.stackBeneathTop = stackBeneathTop
}
T getTop() {
top
}
TStackBeneath pop() {
stackBeneathTop
}
INonEmptyStack<T, INonEmptyStack<T, TStackBeneath>> push(T x) {
new NonEmptyStack<T, INonEmptyStack<T, TStackBeneath>>(x, this)
}
}
final IStack<Integer> stack = new EmptyStack<Integer>()
def oneInteger = stack.push(1)
assert oneInteger.getTop() == 1
def twoIntegers = stack.push(1).push(2)
assert twoIntegers.getTop() == 2
def oneIntegerAgain = stack.push(1).push(2).pop()
assert oneIntegerAgain.getTop() == 1 // BOOM!!!!
'''
}
static class MyList extends LinkedList<String> {}
public static class ClassA<T> {
public <X> Class<X> foo(Class<X> classType) {
return classType;
}
public <X> Class<X> bar(Class<T> classType) {
return null;
}
}
public static class JavaClassSupport {
public static class Container<T> {
}
public static class StringContainer extends Container<String> {
}
public static <T> List<T> unwrap(Collection<? extends Container<T>> list) {
}
}
}