/
StaticTypeCheckingVisitor.java
4832 lines (4478 loc) · 249 KB
/
StaticTypeCheckingVisitor.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
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 org.codehaus.groovy.transform.stc;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import groovy.lang.IntRange;
import groovy.lang.Range;
import groovy.transform.TypeChecked;
import groovy.transform.TypeCheckingMode;
import groovy.transform.stc.ClosureParams;
import groovy.transform.stc.ClosureSignatureConflictResolver;
import groovy.transform.stc.ClosureSignatureHint;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotatedNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.DynamicVariable;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.Variable;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.CaseStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.EmptyStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.ast.stmt.SwitchStatement;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.ast.tools.GenericsUtils;
import org.codehaus.groovy.ast.tools.WideningCategories;
import org.codehaus.groovy.classgen.ReturnAdder;
import org.codehaus.groovy.classgen.asm.InvocationWriter;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.ErrorCollector;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.MetaClassHelper;
import org.codehaus.groovy.syntax.SyntaxException;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.TokenUtil;
import org.codehaus.groovy.transform.StaticTypesTransformation;
import org.codehaus.groovy.transform.trait.Traits;
import org.codehaus.groovy.util.ListHashMap;
import org.objectweb.asm.Opcodes;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.codehaus.groovy.ast.ClassHelper.*;
import static org.codehaus.groovy.ast.tools.GeneralUtils.args;
import static org.codehaus.groovy.ast.tools.GeneralUtils.binX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
import static org.codehaus.groovy.ast.tools.WideningCategories.LowestUpperBoundClassNode;
import static org.codehaus.groovy.ast.tools.WideningCategories.isBigDecCategory;
import static org.codehaus.groovy.ast.tools.WideningCategories.isBigIntCategory;
import static org.codehaus.groovy.ast.tools.WideningCategories.isDouble;
import static org.codehaus.groovy.ast.tools.WideningCategories.isDoubleCategory;
import static org.codehaus.groovy.ast.tools.WideningCategories.isFloat;
import static org.codehaus.groovy.ast.tools.WideningCategories.isFloatingCategory;
import static org.codehaus.groovy.ast.tools.WideningCategories.isIntCategory;
import static org.codehaus.groovy.ast.tools.WideningCategories.isLongCategory;
import static org.codehaus.groovy.ast.tools.WideningCategories.isNumberCategory;
import static org.codehaus.groovy.ast.tools.WideningCategories.lowestUpperBound;
import static org.codehaus.groovy.syntax.Types.ASSIGN;
import static org.codehaus.groovy.syntax.Types.ASSIGNMENT_OPERATOR;
import static org.codehaus.groovy.syntax.Types.COMPARE_EQUAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_NOT_EQUAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_NOT_IN;
import static org.codehaus.groovy.syntax.Types.COMPARE_NOT_INSTANCEOF;
import static org.codehaus.groovy.syntax.Types.COMPARE_TO;
import static org.codehaus.groovy.syntax.Types.DIVIDE;
import static org.codehaus.groovy.syntax.Types.DIVIDE_EQUAL;
import static org.codehaus.groovy.syntax.Types.ELVIS_EQUAL;
import static org.codehaus.groovy.syntax.Types.EQUAL;
import static org.codehaus.groovy.syntax.Types.FIND_REGEX;
import static org.codehaus.groovy.syntax.Types.KEYWORD_IN;
import static org.codehaus.groovy.syntax.Types.KEYWORD_INSTANCEOF;
import static org.codehaus.groovy.syntax.Types.LEFT_SQUARE_BRACKET;
import static org.codehaus.groovy.syntax.Types.MINUS_MINUS;
import static org.codehaus.groovy.syntax.Types.MOD;
import static org.codehaus.groovy.syntax.Types.MOD_EQUAL;
import static org.codehaus.groovy.syntax.Types.PLUS_PLUS;
import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.*;
/**
* The main class code visitor responsible for static type checking. It will perform various inspections like checking
* assignment types, type inference, ... Eventually, class nodes may be annotated with inferred type information.
*
* @author Cedric Champeau
* @author Jochen Theodorou
*/
public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
private static final boolean DEBUG_GENERATED_CODE = Boolean.valueOf(System.getProperty("groovy.stc.debug", "false"));
private static final AtomicLong UNIQUE_LONG = new AtomicLong();
protected static final Object ERROR_COLLECTOR = ErrorCollector.class;
protected static final ClassNode ITERABLE_TYPE = ClassHelper.make(Iterable.class);
protected static final List<MethodNode> EMPTY_METHODNODE_LIST = Collections.emptyList();
protected static final ClassNode TYPECHECKED_CLASSNODE = ClassHelper.make(TypeChecked.class);
protected static final ClassNode[] TYPECHECKING_ANNOTATIONS = new ClassNode[]{TYPECHECKED_CLASSNODE};
protected static final ClassNode TYPECHECKING_INFO_NODE = ClassHelper.make(TypeChecked.TypeCheckingInfo.class);
protected static final ClassNode DGM_CLASSNODE = ClassHelper.make(DefaultGroovyMethods.class);
protected static final int CURRENT_SIGNATURE_PROTOCOL_VERSION = 1;
protected static final Expression CURRENT_SIGNATURE_PROTOCOL = new ConstantExpression(CURRENT_SIGNATURE_PROTOCOL_VERSION, true);
protected static final MethodNode GET_DELEGATE = CLOSURE_TYPE.getGetterMethod("getDelegate");
protected static final MethodNode GET_OWNER = CLOSURE_TYPE.getGetterMethod("getOwner");
protected static final MethodNode GET_THISOBJECT = CLOSURE_TYPE.getGetterMethod("getThisObject");
protected static final ClassNode DELEGATES_TO = ClassHelper.make(DelegatesTo.class);
protected static final ClassNode DELEGATES_TO_TARGET = ClassHelper.make(DelegatesTo.Target.class);
protected static final ClassNode LINKEDHASHMAP_CLASSNODE = make(LinkedHashMap.class);
protected static final ClassNode CLOSUREPARAMS_CLASSNODE = make(ClosureParams.class);
protected static final ClassNode MAP_ENTRY_TYPE = make(Map.Entry.class);
protected static final ClassNode ENUMERATION_TYPE = make(Enumeration.class);
public static final Statement GENERATED_EMPTY_STATEMENT = new EmptyStatement();
public static final MethodNode CLOSURE_CALL_NO_ARG;
public static final MethodNode CLOSURE_CALL_ONE_ARG;
public static final MethodNode CLOSURE_CALL_VARGS;
static {
// Cache closure call methods
CLOSURE_CALL_NO_ARG = CLOSURE_TYPE.getDeclaredMethod("call", Parameter.EMPTY_ARRAY);
CLOSURE_CALL_ONE_ARG = CLOSURE_TYPE.getDeclaredMethod("call", new Parameter[]{
new Parameter(OBJECT_TYPE, "arg")
});
CLOSURE_CALL_VARGS = CLOSURE_TYPE.getDeclaredMethod("call", new Parameter[]{
new Parameter(OBJECT_TYPE.makeArray(), "args")
});
}
private static final String[] EMPTY_STRING_ARRAY = new String[0];
protected final ReturnAdder.ReturnStatementListener returnListener = new ReturnAdder.ReturnStatementListener() {
public void returnStatementAdded(final ReturnStatement returnStatement) {
if (returnStatement.getExpression() == ConstantExpression.NULL) return;
if (isNullConstant(returnStatement.getExpression())) return;
checkReturnType(returnStatement);
if (typeCheckingContext.getEnclosingClosure()!=null) {
addClosureReturnType(getType(returnStatement.getExpression()));
} else if (typeCheckingContext.getEnclosingMethod() != null) {
} else {
throw new GroovyBugError("Unexpected return statement at "
+ returnStatement.getLineNumber()+":"+returnStatement.getColumnNumber()
+ " "+returnStatement.getText());
}
}
};
protected final ReturnAdder returnAdder = new ReturnAdder(returnListener);
protected TypeCheckingContext typeCheckingContext;
protected DefaultTypeCheckingExtension extension;
public StaticTypeCheckingVisitor(SourceUnit source, ClassNode cn) {
this.typeCheckingContext = new TypeCheckingContext(this);
this.extension = createDefaultTypeCheckingExtension();
this.typeCheckingContext.source = source;
this.typeCheckingContext.pushEnclosingClassNode(cn);
this.typeCheckingContext.pushErrorCollector(source.getErrorCollector());
this.typeCheckingContext.pushTemporaryTypeInfo();
}
private DefaultTypeCheckingExtension createDefaultTypeCheckingExtension() {
DefaultTypeCheckingExtension ext = new DefaultTypeCheckingExtension(this);
ext.addHandler(new TraitTypeCheckingExtension(this));
return ext;
}
// @Override
protected SourceUnit getSourceUnit() {
return typeCheckingContext.source;
}
public void initialize() {
extension.setup();
}
/**
* Returns the current type checking context. The context is used internally by the type
* checker during type checking to store various state data.
*
* @return the type checking context
*/
public TypeCheckingContext getTypeCheckingContext() {
return typeCheckingContext;
}
public void addTypeCheckingExtension(TypeCheckingExtension extension) {
this.extension.addHandler(extension);
}
public void setCompilationUnit(CompilationUnit cu) {
typeCheckingContext.setCompilationUnit(cu);
}
@Override
public void visitClass(final ClassNode node) {
if (shouldSkipClassNode(node)) return;
if (extension.beforeVisitClass(node)) {
extension.afterVisitClass(node);
return;
}
Object type = node.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
if (type != null) {
// transformation has already been run on this class node
// so we'll use a silent collector in order not to duplicate errors
typeCheckingContext.pushErrorCollector();
}
typeCheckingContext.pushEnclosingClassNode(node);
Set<MethodNode> oldVisitedMethod = typeCheckingContext.alreadyVisitedMethods;
typeCheckingContext.alreadyVisitedMethods = new LinkedHashSet<MethodNode>();
super.visitClass(node);
Iterator<InnerClassNode> innerClasses = node.getInnerClasses();
while (innerClasses.hasNext()) {
InnerClassNode innerClassNode = innerClasses.next();
visitClass(innerClassNode);
}
typeCheckingContext.alreadyVisitedMethods = oldVisitedMethod;
node.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, node);
// mark all methods as visited. We can't do this in visitMethod because the type checker
// works in a two pass sequence and we don't want to skip the second pass
for (MethodNode methodNode : node.getMethods()) {
methodNode.putNodeMetaData(StaticTypeCheckingVisitor.class, Boolean.TRUE);
}
for (ConstructorNode constructorNode : node.getDeclaredConstructors()) {
constructorNode.putNodeMetaData(StaticTypeCheckingVisitor.class, Boolean.TRUE);
}
extension.afterVisitClass(node);
}
protected boolean shouldSkipClassNode(final ClassNode node) {
if (isSkipMode(node)) return true;
return false;
}
/**
* Returns the list of type checking annotations class nodes. Subclasses may override this method
* in order to provide additional classes which must be looked up when checking if a method or
* a class node should be skipped.
* <p>
* The default implementation returns {@link TypeChecked}.
*
* @return array of class nodes
*/
protected ClassNode[] getTypeCheckingAnnotations() {
return TYPECHECKING_ANNOTATIONS;
}
public boolean isSkipMode(final AnnotatedNode node) {
if (node == null) return false;
for (ClassNode tca : getTypeCheckingAnnotations()) {
List<AnnotationNode> annotations = node.getAnnotations(tca);
if (annotations != null) {
for (AnnotationNode annotation : annotations) {
Expression value = annotation.getMember("value");
if (value != null) {
if (value instanceof ConstantExpression) {
ConstantExpression ce = (ConstantExpression) value;
if (TypeCheckingMode.SKIP.toString().equals(ce.getValue().toString())) return true;
} else if (value instanceof PropertyExpression) {
PropertyExpression pe = (PropertyExpression) value;
if (TypeCheckingMode.SKIP.toString().equals(pe.getPropertyAsString())) return true;
}
}
}
}
}
if (node instanceof MethodNode) {
return isSkipMode(node.getDeclaringClass());
}
if (isSkippedInnerClass(node)) return true;
return false;
}
/**
* Test if a node is an inner class node, and if it is, then checks if the enclosing method is skipped.
* @param node
* @return true if the inner class node should be skipped
*/
protected boolean isSkippedInnerClass(AnnotatedNode node) {
if (!(node instanceof InnerClassNode)) return false;
MethodNode enclosingMethod = ((InnerClassNode) node).getEnclosingMethod();
return enclosingMethod != null && isSkipMode(enclosingMethod);
}
@Override
public void visitClassExpression(final ClassExpression expression) {
super.visitClassExpression(expression);
ClassNode cn = (ClassNode) expression.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
if (cn == null) {
storeType(expression, getType(expression));
}
}
@SuppressWarnings("unchecked")
private static void addPrivateFieldOrMethodAccess(Expression source, ClassNode cn, StaticTypesMarker type, ASTNode accessedMember) {
Set<ASTNode> set = (Set<ASTNode>) cn.getNodeMetaData(type);
if (set==null) {
set = new LinkedHashSet<ASTNode>();
cn.putNodeMetaData(type, set);
}
set.add(accessedMember);
source.putNodeMetaData(type, accessedMember);
}
/**
* Given a field node, checks if we are accessing or setting a private field from an inner class.
*/
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn, boolean lhsOfAssignment) {
if (fn!=null && Modifier.isPrivate(fn.getModifiers()) &&
(fn.getDeclaringClass() != typeCheckingContext.getEnclosingClassNode() || typeCheckingContext.getEnclosingClosure()!=null) &&
fn.getDeclaringClass().getModule() == typeCheckingContext.getEnclosingClassNode().getModule()) {
StaticTypesMarker marker = lhsOfAssignment ? StaticTypesMarker.PV_FIELDS_MUTATION : StaticTypesMarker.PV_FIELDS_ACCESS;
addPrivateFieldOrMethodAccess(source, fn.getDeclaringClass(), marker, fn);
}
}
/**
* Given a method node, checks if we are calling a private method from an inner class.
*/
private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) {
if (mn==null) {
return;
}
ClassNode declaringClass = mn.getDeclaringClass();
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) {
int mods = mn.getModifiers();
boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule();
String packageName = declaringClass.getPackageName();
if (packageName==null) {
packageName = "";
}
if ((Modifier.isPrivate(mods) && sameModule)) {
addPrivateFieldOrMethodAccess(source, declaringClass, StaticTypesMarker.PV_METHODS_ACCESS, mn);
} else if (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName())
&& !implementsInterfaceOrIsSubclassOf(enclosingClassNode, declaringClass)) {
ClassNode cn = enclosingClassNode;
while ((cn = cn.getOuterClass()) != null) {
if (implementsInterfaceOrIsSubclassOf(cn, declaringClass)) {
addPrivateFieldOrMethodAccess(source, cn, StaticTypesMarker.PV_METHODS_ACCESS, mn);
break;
}
}
}
}
}
private void checkSuperCallFromClosure(Expression call, MethodNode directCallTarget) {
if (call instanceof MethodCallExpression && typeCheckingContext.getEnclosingClosure() != null) {
Expression objectExpression = ((MethodCallExpression)call).getObjectExpression();
if (objectExpression instanceof VariableExpression) {
VariableExpression var = (VariableExpression) objectExpression;
if (var.isSuperExpression()) {
ClassNode current = typeCheckingContext.getEnclosingClassNode();
LinkedList<MethodNode> list = current.getNodeMetaData(StaticTypesMarker.SUPER_MOP_METHOD_REQUIRED);
if (list == null) {
list = new LinkedList<MethodNode>();
current.putNodeMetaData(StaticTypesMarker.SUPER_MOP_METHOD_REQUIRED, list);
}
list.add(directCallTarget);
call.putNodeMetaData(StaticTypesMarker.SUPER_MOP_METHOD_REQUIRED, current);
}
}
}
}
/**
* wrap type in Class<> if usingClass==true
*/
private static ClassNode makeType(ClassNode cn, boolean usingClass) {
if (usingClass) {
ClassNode clazzType = CLASS_Type.getPlainNodeReference();
clazzType.setGenericsTypes(new GenericsType[] {new GenericsType(cn)});
return clazzType;
} else {
return cn;
}
}
private boolean storeTypeForThis(VariableExpression vexp) {
if (vexp == VariableExpression.THIS_EXPRESSION) return true;
if (!vexp.isThisExpression()) return false;
ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();
storeType(vexp, makeType(enclosingClassNode, typeCheckingContext.isInStaticContext));
return true;
}
private boolean storeTypeForSuper(VariableExpression vexp) {
if (vexp == VariableExpression.SUPER_EXPRESSION) return true;
if (!vexp.isSuperExpression()) return false;
ClassNode superClassNode = typeCheckingContext.getEnclosingClassNode().getSuperClass();
storeType(vexp, makeType(superClassNode, typeCheckingContext.isInStaticContext));
return true;
}
@Override
public void visitVariableExpression(VariableExpression vexp) {
super.visitVariableExpression(vexp);
if (storeTypeForThis(vexp)) return;
if (storeTypeForSuper(vexp)) return;
if (vexp.getAccessedVariable() instanceof PropertyNode) {
// we must be careful, because the property node may be of a wrong type:
// if a class contains a getter and a setter of different types or
// overloaded setters, the type of the property node is arbitrary!
if (tryVariableExpressionAsProperty(vexp, vexp.getName())) {
BinaryExpression enclosingBinaryExpression = typeCheckingContext.getEnclosingBinaryExpression();
if (enclosingBinaryExpression != null) {
Expression leftExpression = enclosingBinaryExpression.getLeftExpression();
Expression rightExpression = enclosingBinaryExpression.getRightExpression();
SetterInfo setterInfo = removeSetterInfo(leftExpression);
if (setterInfo != null) {
if (!ensureValidSetter(vexp, leftExpression, rightExpression, setterInfo)) {
return;
}
}
}
}
}
TypeCheckingContext.EnclosingClosure enclosingClosure = typeCheckingContext.getEnclosingClosure();
if (enclosingClosure != null) {
String name = vexp.getName();
if (name.equals("owner") || name.equals("thisObject")) {
storeType(vexp, typeCheckingContext.getEnclosingClassNode());
return;
} else if ("delegate".equals(name)) {
DelegationMetadata md = getDelegationMetadata(enclosingClosure.getClosureExpression());
ClassNode type = typeCheckingContext.getEnclosingClassNode();
if (md!=null) type = md.getType();
storeType(vexp, type);
return;
}
}
if (! (vexp.getAccessedVariable() instanceof DynamicVariable)) return;
// a dynamic variable is either an undeclared variable
// or a member of a class used in a 'with'
DynamicVariable dyn = (DynamicVariable) vexp.getAccessedVariable();
// first, we must check the 'with' context
String dynName = dyn.getName();
if (tryVariableExpressionAsProperty(vexp, dynName)) return;
if (!extension.handleUnresolvedVariableExpression(vexp)) {
addStaticTypeError("The variable [" + vexp.getName() + "] is undeclared.", vexp);
}
}
private boolean tryVariableExpressionAsProperty(final VariableExpression vexp, final String dynName) {
VariableExpression implicitThis = varX("this");
PropertyExpression pe = new PropertyExpression(implicitThis, dynName);
pe.setImplicitThis(true);
if (visitPropertyExpressionSilent(pe, vexp)) {
ClassNode previousIt = vexp.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
vexp.copyNodeMetaData(implicitThis);
vexp.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, previousIt);
storeType(vexp, getType(pe));
Object val = pe.getNodeMetaData(StaticTypesMarker.READONLY_PROPERTY);
if (val!=null) vexp.putNodeMetaData(StaticTypesMarker.READONLY_PROPERTY,val);
val = pe.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER);
if (val!=null) vexp.putNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER,val);
return true;
}
return false;
}
private boolean visitPropertyExpressionSilent(PropertyExpression pe, Expression lhsPart) {
return (existsProperty(pe, !isLHSOfEnclosingAssignment(lhsPart)));
}
@Override
public void visitPropertyExpression(final PropertyExpression pexp) {
if (visitPropertyExpressionSilent(pexp,pexp)) return;
if (!extension.handleUnresolvedProperty(pexp)) {
Expression objectExpression = pexp.getObjectExpression();
addStaticTypeError("No such property: " + pexp.getPropertyAsString() +
" for class: " + findCurrentInstanceOfClass(objectExpression, getType(objectExpression)).toString(false), pexp);
}
}
private boolean isLHSOfEnclosingAssignment(final Expression expression) {
final BinaryExpression ec = typeCheckingContext.getEnclosingBinaryExpression();
return ec != null && ec.getLeftExpression() == expression && isAssignment(ec.getOperation().getType());
}
@Override
public void visitAttributeExpression(final AttributeExpression expression) {
super.visitAttributeExpression(expression);
if (!existsProperty(expression, true) && !extension.handleUnresolvedAttribute(expression)) {
Expression objectExpression = expression.getObjectExpression();
addStaticTypeError("No such property: " + expression.getPropertyAsString() +
" for class: " + findCurrentInstanceOfClass(objectExpression, objectExpression.getType()), expression);
}
}
@Override
public void visitRangeExpression(final RangeExpression expression) {
super.visitRangeExpression(expression);
ClassNode fromType = getWrapper(getType(expression.getFrom()));
ClassNode toType = getWrapper(getType(expression.getTo()));
if (Integer_TYPE.equals(fromType) && Integer_TYPE.equals(toType)) {
storeType(expression, ClassHelper.make(IntRange.class));
} else {
ClassNode rangeType = ClassHelper.make(Range.class).getPlainNodeReference();
rangeType.setGenericsTypes(new GenericsType[] { new GenericsType(WideningCategories.lowestUpperBound(fromType, toType))});
storeType(expression, rangeType);
}
}
@Override
public void visitBinaryExpression(BinaryExpression expression) {
BinaryExpression enclosingBinaryExpression = typeCheckingContext.getEnclosingBinaryExpression();
typeCheckingContext.pushEnclosingBinaryExpression(expression);
try {
final Expression leftExpression = expression.getLeftExpression();
final Expression rightExpression = expression.getRightExpression();
int op = expression.getOperation().getType();
leftExpression.visit(this);
SetterInfo setterInfo = removeSetterInfo(leftExpression);
if (setterInfo != null) {
if (ensureValidSetter(expression, leftExpression, rightExpression, setterInfo)) {
return;
}
} else {
rightExpression.visit(this);
}
ClassNode lType = getType(leftExpression);
ClassNode rType = getType(rightExpression);
if (isNullConstant(rightExpression)) {
if (!isPrimitiveType(lType))
rType = UNKNOWN_PARAMETER_TYPE; // primitive types should be ignored as they will result in another failure
}
BinaryExpression reversedBinaryExpression = binX(rightExpression, expression.getOperation(), leftExpression);
ClassNode resultType = (op==KEYWORD_IN || op==COMPARE_NOT_IN)
?getResultType(rType,op,lType,reversedBinaryExpression)
:getResultType(lType, op, rType, expression);
if (op==KEYWORD_IN || op==COMPARE_NOT_IN) {
// in case of the "in" operator, the receiver and the arguments are reversed
// so we use the reversedExpression and get the target method from it
storeTargetMethod(expression, (MethodNode) reversedBinaryExpression.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET));
} else if (op == LEFT_SQUARE_BRACKET
&& leftExpression instanceof VariableExpression
&& leftExpression.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE)==null) {
storeType(leftExpression, lType);
}
if (resultType == null) {
resultType = lType;
}
// if left expression is a closure shared variable, a second pass should be done
if (leftExpression instanceof VariableExpression) {
VariableExpression leftVar = (VariableExpression) leftExpression;
if (leftVar.isClosureSharedVariable()) {
// if left expression is a closure shared variable, we should check it twice
// see GROOVY-5874
typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<Void>(expression));
}
}
if (lType.isUsingGenerics() && missesGenericsTypes(resultType) && isAssignment(op)) {
// unchecked assignment
// examples:
// List<A> list = new LinkedList()
// List<A> list = []
// Iterable<A> list = new LinkedList()
// in that case, the inferred type of the binary expression is the type of the RHS
// "completed" with generics type information available in the LHS
ClassNode completedType = GenericsUtils.parameterizeType(lType, resultType.getPlainNodeReference());
resultType = completedType;
}
if (isArrayOp(op) &&
enclosingBinaryExpression != null
&& enclosingBinaryExpression.getLeftExpression() == expression
&& isAssignment(enclosingBinaryExpression.getOperation().getType())
&& !lType.isArray()) {
// left hand side of an assignment : map['foo'] = ...
Expression enclosingBE_rightExpr = enclosingBinaryExpression.getRightExpression();
if (!(enclosingBE_rightExpr instanceof ClosureExpression)) {
enclosingBE_rightExpr.visit(this);
}
ClassNode[] arguments = {rType, getType(enclosingBE_rightExpr)};
List<MethodNode> nodes = findMethod(lType.redirect(), "putAt", arguments);
if (nodes.size() == 1) {
typeCheckMethodsWithGenericsOrFail(lType, arguments, nodes.get(0), enclosingBE_rightExpr);
} else if (nodes.isEmpty()) {
addNoMatchingMethodError(lType, "putAt", arguments, enclosingBinaryExpression);
}
}
boolean isEmptyDeclaration = expression instanceof DeclarationExpression && rightExpression instanceof EmptyExpression;
if (!isEmptyDeclaration && isAssignment(op)) {
if (rightExpression instanceof ConstructorCallExpression) {
inferDiamondType((ConstructorCallExpression) rightExpression, lType);
}
ClassNode originType = getOriginalDeclarationType(leftExpression);
typeCheckAssignment(expression, leftExpression, originType, rightExpression, resultType);
// if assignment succeeds but result type is not a subtype of original type, then we are in a special cast handling
// and we must update the result type
if (!implementsInterfaceOrIsSubclassOf(getWrapper(resultType), getWrapper(originType))) {
resultType = originType;
} else if (lType.isUsingGenerics() && !lType.isEnum() && hasRHSIncompleteGenericTypeInfo(resultType)) {
// for example, LHS is List<ConcreteClass> and RHS is List<T> where T is a placeholder
resultType = lType;
}
// make sure we keep primitive types
if (isPrimitiveType(originType) && resultType.equals(getWrapper(originType))) {
resultType = originType;
}
// if we are in an if/else branch, keep track of assignment
if (typeCheckingContext.ifElseForWhileAssignmentTracker != null && leftExpression instanceof VariableExpression
&& !isNullConstant(rightExpression)) {
Variable accessedVariable = ((VariableExpression) leftExpression).getAccessedVariable();
if (accessedVariable instanceof VariableExpression) {
VariableExpression var = (VariableExpression) accessedVariable;
List<ClassNode> types = typeCheckingContext.ifElseForWhileAssignmentTracker.get(var);
if (types == null) {
types = new LinkedList<ClassNode>();
ClassNode type = var.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE);
types.add(type);
typeCheckingContext.ifElseForWhileAssignmentTracker.put(var, types);
}
types.add(resultType);
}
}
storeType(leftExpression, resultType);
// if right expression is a ClosureExpression, store parameter type information
if (leftExpression instanceof VariableExpression) {
if (rightExpression instanceof ClosureExpression) {
Parameter[] parameters = ((ClosureExpression) rightExpression).getParameters();
leftExpression.putNodeMetaData(StaticTypesMarker.CLOSURE_ARGUMENTS, parameters);
} else if (rightExpression instanceof VariableExpression &&
((VariableExpression)rightExpression).getAccessedVariable() instanceof Expression &&
((Expression)((VariableExpression)rightExpression).getAccessedVariable()).getNodeMetaData(StaticTypesMarker.CLOSURE_ARGUMENTS)!=null) {
Variable targetVariable = findTargetVariable((VariableExpression)leftExpression);
if (targetVariable instanceof ASTNode) {
((ASTNode)targetVariable).putNodeMetaData(
StaticTypesMarker.CLOSURE_ARGUMENTS,
((Expression)((VariableExpression)rightExpression).getAccessedVariable()).getNodeMetaData(StaticTypesMarker.CLOSURE_ARGUMENTS));
}
}
}
} else if (op == KEYWORD_INSTANCEOF || op == COMPARE_NOT_INSTANCEOF) {
pushInstanceOfTypeInfo(leftExpression, rightExpression);
}
if (!isEmptyDeclaration) {
storeType(expression, resultType);
}
} finally {
typeCheckingContext.popEnclosingBinaryExpression();
}
}
/**
* Given a binary expression corresponding to an assignment, will check that the type of the RHS matches one
* of the possible setters and if not, throw a type checking error.
* @param expression the assignment expression
* @param leftExpression left expression of the assignment
* @param rightExpression right expression of the assignment
* @param setterInfo possible setters
* @return true if type checking passed
*/
private boolean ensureValidSetter(final Expression expression, final Expression leftExpression, final Expression rightExpression, final SetterInfo setterInfo) {
// for expressions like foo = { ... }
// we know that the RHS type is a closure
// but we must check if the binary expression is an assignment
// because we need to check if a setter uses @DelegatesTo
VariableExpression ve = varX("%", setterInfo.receiverType);
// for compound assignment "x op= y" find type as if it was "x = (x op y)"
final Expression newRightExpression = isCompoundAssignment(expression)
? binX(leftExpression, getOpWithoutEqual(expression), rightExpression)
: rightExpression;
MethodCallExpression call = callX(ve, setterInfo.name, newRightExpression);
call.setImplicitThis(false);
visitMethodCallExpression(call);
MethodNode directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);
if (directSetterCandidate==null) {
// this may happen if there's a setter of type boolean/String/Class, and that we are using the property
// notation AND that the RHS is not a boolean/String/Class
for (MethodNode setter : setterInfo.setters) {
ClassNode type = getWrapper(setter.getParameters()[0].getOriginType());
if (Boolean_TYPE.equals(type) || STRING_TYPE.equals(type) || CLASS_Type.equals(type)) {
call = callX(ve, setterInfo.name, castX(type, newRightExpression));
call.setImplicitThis(false);
visitMethodCallExpression(call);
directSetterCandidate = call.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);
if (directSetterCandidate!=null) {
break;
}
}
}
}
if (directSetterCandidate != null) {
for (MethodNode setter : setterInfo.setters) {
if (setter == directSetterCandidate) {
leftExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, directSetterCandidate);
storeType(leftExpression, getType(newRightExpression));
break;
}
}
} else {
ClassNode firstSetterType = setterInfo.setters.iterator().next().getParameters()[0].getOriginType();
addAssignmentError(firstSetterType, getType(newRightExpression), expression);
return true;
}
return false;
}
private boolean isCompoundAssignment(Expression exp) {
if (!(exp instanceof BinaryExpression)) return false;
int type = ((BinaryExpression) exp).getOperation().getType();
return isAssignment(type) && type != ASSIGN;
}
private Token getOpWithoutEqual(Expression exp) {
if (!(exp instanceof BinaryExpression)) return null; // should never happen
Token op = ((BinaryExpression) exp).getOperation();
int typeWithoutEqual = TokenUtil.removeAssignment(op.getType());
return new Token(typeWithoutEqual, op.getText() /* will do */, op.getStartLine(), op.getStartColumn());
}
protected ClassNode getOriginalDeclarationType(Expression lhs) {
if (lhs instanceof VariableExpression) {
Variable var = findTargetVariable((VariableExpression) lhs);
if (var instanceof PropertyNode) {
// Do NOT trust the type of the property node!
return getType(lhs);
}
if (var instanceof DynamicVariable) return getType(lhs);
return var.getOriginType();
}
if (lhs instanceof FieldExpression) {
return ((FieldExpression) lhs).getField().getOriginType();
}
return getType(lhs);
}
protected void inferDiamondType(final ConstructorCallExpression cce, final ClassNode lType) {
// check if constructor call expression makes use of the diamond operator
ClassNode node = cce.getType();
if (node.isUsingGenerics() && node.getGenericsTypes() != null && node.getGenericsTypes().length == 0) {
ArgumentListExpression argumentListExpression = InvocationWriter.makeArgumentList(cce.getArguments());
if (argumentListExpression.getExpressions().isEmpty()) {
adjustGenerics(lType, node);
} else {
ClassNode type = getType(argumentListExpression.getExpression(0));
if (type.isUsingGenerics()) {
adjustGenerics(type, node);
}
}
// store inferred type on CCE
storeType(cce, node);
}
}
private void adjustGenerics(ClassNode from, ClassNode to) {
GenericsType[] genericsTypes = from.getGenericsTypes();
if (genericsTypes == null) {
// case of: def foo = new HashMap<>()
genericsTypes = to.redirect().getGenericsTypes();
}
GenericsType[] copy = new GenericsType[genericsTypes.length];
for (int i = 0; i < genericsTypes.length; i++) {
GenericsType genericsType = genericsTypes[i];
copy[i] = new GenericsType(
wrapTypeIfNecessary(genericsType.getType()),
genericsType.getUpperBounds(),
genericsType.getLowerBound()
);
}
to.setGenericsTypes(copy);
}
/**
* Stores information about types when [objectOfInstanceof instanceof typeExpression] is visited
*
* @param objectOfInstanceOf the expression which must be checked against instanceof
* @param typeExpression the expression which represents the target type
*/
protected void pushInstanceOfTypeInfo(final Expression objectOfInstanceOf, final Expression typeExpression) {
final Map<Object, List<ClassNode>> tempo = typeCheckingContext.temporaryIfBranchTypeInformation.peek();
Object key = extractTemporaryTypeInfoKey(objectOfInstanceOf);
List<ClassNode> potentialTypes = tempo.get(key);
if (potentialTypes == null) {
potentialTypes = new LinkedList<ClassNode>();
tempo.put(key, potentialTypes);
}
potentialTypes.add(typeExpression.getType());
}
private boolean typeCheckMultipleAssignmentAndContinue(Expression leftExpression, Expression rightExpression) {
// multiple assignment check
if (!(leftExpression instanceof TupleExpression)) return true;
if (!(rightExpression instanceof ListExpression)) {
addStaticTypeError("Multiple assignments without list expressions on the right hand side are unsupported in static type checking mode", rightExpression);
return false;
}
TupleExpression tuple = (TupleExpression) leftExpression;
ListExpression list = (ListExpression) rightExpression;
List<Expression> listExpressions = list.getExpressions();
List<Expression> tupleExpressions = tuple.getExpressions();
if (listExpressions.size() < tupleExpressions.size()) {
addStaticTypeError("Incorrect number of values. Expected:" + tupleExpressions.size() + " Was:" + listExpressions.size(), list);
return false;
}
for (int i = 0, tupleExpressionsSize = tupleExpressions.size(); i < tupleExpressionsSize; i++) {
Expression tupleExpression = tupleExpressions.get(i);
Expression listExpression = listExpressions.get(i);
ClassNode elemType = getType(listExpression);
ClassNode tupleType = getType(tupleExpression);
if (!isAssignableTo(elemType, tupleType)) {
addStaticTypeError("Cannot assign value of type " + elemType.toString(false) + " to variable of type " + tupleType.toString(false), rightExpression);
return false; // avoids too many errors
}
}
return true;
}
private static ClassNode adjustTypeForSpreading(ClassNode inferredRightExpressionType, Expression leftExpression) {
// imagine we have: list*.foo = 100
// then the assignment must be checked against [100], not 100
ClassNode wrappedRHS = inferredRightExpressionType;
if (leftExpression instanceof PropertyExpression && ((PropertyExpression) leftExpression).isSpreadSafe()) {
wrappedRHS = LIST_TYPE.getPlainNodeReference();
wrappedRHS.setGenericsTypes(new GenericsType[]{
new GenericsType(getWrapper(inferredRightExpressionType))
});
}
return wrappedRHS;
}
private boolean addedReadOnlyPropertyError(Expression expr) {
// if expr is of READONLY_PROPERTY_RETURN type, then it means we are on a missing property
if (expr.getNodeMetaData(StaticTypesMarker.READONLY_PROPERTY) == null) return false;
String name;
if (expr instanceof VariableExpression) {
name = ((VariableExpression) expr).getName();
} else {
name = ((PropertyExpression) expr).getPropertyAsString();
}
addStaticTypeError("Cannot set read-only property: " + name, expr);
return true;
}
private void addPrecisionErrors(ClassNode leftRedirect, ClassNode lhsType, ClassNode inferredrhsType, Expression rightExpression) {
if (isNumberType(leftRedirect) && isNumberType(inferredrhsType)) {
if (checkPossibleLooseOfPrecision(leftRedirect, inferredrhsType, rightExpression)) {
addStaticTypeError("Possible loss of precision from " + inferredrhsType + " to " + leftRedirect, rightExpression);
return;
}
}
// if left type is array, we should check the right component types
if (!lhsType.isArray()) return;
ClassNode leftComponentType = lhsType.getComponentType();
ClassNode rightRedirect = rightExpression.getType().redirect();
if (rightRedirect.isArray()) {
ClassNode rightComponentType = rightRedirect.getComponentType();
if (!checkCompatibleAssignmentTypes(leftComponentType, rightComponentType)) {
addStaticTypeError("Cannot assign value of type " + rightComponentType.toString(false) + " into array of type " + lhsType.toString(false), rightExpression);
}
} else if (rightExpression instanceof ListExpression) {
for (Expression element : ((ListExpression) rightExpression).getExpressions()) {
ClassNode rightComponentType = element.getType().redirect();
if (!checkCompatibleAssignmentTypes(leftComponentType, rightComponentType)
&& !(isNullConstant(element) && !isPrimitiveType(leftComponentType))) {
addStaticTypeError("Cannot assign value of type " + rightComponentType.toString(false) + " into array of type " + lhsType.toString(false), rightExpression);
}
}
}
}
private void addListAssignmentConstructorErrors(
ClassNode leftRedirect, ClassNode leftExpressionType,
ClassNode inferredRightExpressionType, Expression rightExpression,
Expression assignmentExpression)
{
// if left type is not a list but right type is a list, then we're in the case of a groovy
// constructor type : Dimension d = [100,200]
// In that case, more checks can be performed
if (rightExpression instanceof ListExpression && !implementsInterfaceOrIsSubclassOf(LIST_TYPE, leftRedirect)) {
ArgumentListExpression argList = args(((ListExpression) rightExpression).getExpressions());
ClassNode[] args = getArgumentTypes(argList);
MethodNode methodNode = checkGroovyStyleConstructor(leftRedirect, args, assignmentExpression);
if (methodNode!=null) {
rightExpression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, methodNode);
}
} else if (!implementsInterfaceOrIsSubclassOf(inferredRightExpressionType, leftRedirect)
&& implementsInterfaceOrIsSubclassOf(inferredRightExpressionType, LIST_TYPE)
&& !isWildcardLeftHandSide(leftExpressionType)) {
if (!extension.handleIncompatibleAssignment(leftExpressionType, inferredRightExpressionType, assignmentExpression)) {
addAssignmentError(leftExpressionType, inferredRightExpressionType, assignmentExpression);
}
}
}
private void addMapAssignmentConstructorErrors(ClassNode leftRedirect, Expression leftExpression, Expression rightExpression) {
// if left type is not a list but right type is a map, then we're in the case of a groovy
// constructor type : A a = [x:2, y:3]
// In this case, more checks can be performed
if (!implementsInterfaceOrIsSubclassOf(leftRedirect, MAP_TYPE) && rightExpression instanceof MapExpression) {
if (!(leftExpression instanceof VariableExpression) || !((VariableExpression) leftExpression).isDynamicTyped()) {
ArgumentListExpression argList = args(rightExpression);
ClassNode[] argTypes = getArgumentTypes(argList);
checkGroovyStyleConstructor(leftRedirect, argTypes, rightExpression);
// perform additional type checking on arguments
MapExpression mapExpression = (MapExpression) rightExpression;
checkGroovyConstructorMap(leftExpression, leftRedirect, mapExpression);
}
}
}
private void checkTypeGenerics(ClassNode leftExpressionType, ClassNode wrappedRHS, Expression rightExpression) {
// last, check generic type information to ensure that inferred types are compatible
if (!leftExpressionType.isUsingGenerics()) return;
// List<Foo> l = new List() is an example for incomplete generics type info
// we assume arity related errors are already handled here.
if (hasRHSIncompleteGenericTypeInfo(wrappedRHS)) return;
GenericsType gt = GenericsUtils.buildWildcardType(leftExpressionType);
if ( UNKNOWN_PARAMETER_TYPE.equals(wrappedRHS) ||
gt.isCompatibleWith(wrappedRHS) ||
isNullConstant(rightExpression)) return;
addStaticTypeError("Incompatible generic argument types. Cannot assign "
+ wrappedRHS.toString(false)
+ " to: " + leftExpressionType.toString(false), rightExpression);
}
private boolean hasGStringStringError(ClassNode leftExpressionType, ClassNode wrappedRHS, Expression rightExpression) {
if (isParameterizedWithString(leftExpressionType) && isParameterizedWithGStringOrGStringString(wrappedRHS)) {
addStaticTypeError("You are trying to use a GString in place of a String in a type which explicitly declares accepting String. " +
"Make sure to call toString() on all GString values.", rightExpression);
return true;
}
return false;
}