/
StaticTypeCheckingSupport.java
2438 lines (2241 loc) · 112 KB
/
StaticTypeCheckingSupport.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 org.apache.groovy.util.Maps;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.GenericsType.GenericsTypeName;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.Variable;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MapExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.tools.GenericsUtils;
import org.codehaus.groovy.ast.tools.ParameterUtils;
import org.codehaus.groovy.ast.tools.WideningCategories;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.Phases;
import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl;
import org.codehaus.groovy.syntax.Types;
import org.codehaus.groovy.tools.GroovyClass;
import org.codehaus.groovy.transform.trait.Traits;
import groovyjarjarasm.asm.Opcodes;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.regex.Matcher;
import static java.lang.Math.min;
import static org.apache.groovy.ast.tools.ClassNodeUtils.addGeneratedMethod;
import static org.apache.groovy.ast.tools.ClassNodeUtils.samePackageName;
import static org.codehaus.groovy.ast.ClassHelper.BigDecimal_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.BigInteger_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Boolean_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Byte_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.CLASS_Type;
import static org.codehaus.groovy.ast.ClassHelper.CLOSURE_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Character_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Double_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Enum_Type;
import static org.codehaus.groovy.ast.ClassHelper.Float_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.GROOVY_OBJECT_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.GSTRING_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Integer_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Long_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Number_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.OBJECT_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.STRING_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.Short_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.VOID_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.boolean_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.byte_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.char_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.double_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.findSAM;
import static org.codehaus.groovy.ast.ClassHelper.float_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.getUnwrapper;
import static org.codehaus.groovy.ast.ClassHelper.getWrapper;
import static org.codehaus.groovy.ast.ClassHelper.int_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.isNumberType;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveType;
import static org.codehaus.groovy.ast.ClassHelper.isSAMType;
import static org.codehaus.groovy.ast.ClassHelper.long_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.make;
import static org.codehaus.groovy.ast.ClassHelper.makeWithoutCaching;
import static org.codehaus.groovy.ast.ClassHelper.short_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.void_WRAPPER_TYPE;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.asBoolean;
import static org.codehaus.groovy.syntax.Types.BITWISE_AND;
import static org.codehaus.groovy.syntax.Types.BITWISE_AND_EQUAL;
import static org.codehaus.groovy.syntax.Types.BITWISE_OR;
import static org.codehaus.groovy.syntax.Types.BITWISE_OR_EQUAL;
import static org.codehaus.groovy.syntax.Types.BITWISE_XOR;
import static org.codehaus.groovy.syntax.Types.BITWISE_XOR_EQUAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_EQUAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_GREATER_THAN;
import static org.codehaus.groovy.syntax.Types.COMPARE_GREATER_THAN_EQUAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_IDENTICAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_LESS_THAN;
import static org.codehaus.groovy.syntax.Types.COMPARE_LESS_THAN_EQUAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_NOT_EQUAL;
import static org.codehaus.groovy.syntax.Types.COMPARE_NOT_IDENTICAL;
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.INTDIV;
import static org.codehaus.groovy.syntax.Types.INTDIV_EQUAL;
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_SHIFT;
import static org.codehaus.groovy.syntax.Types.LEFT_SHIFT_EQUAL;
import static org.codehaus.groovy.syntax.Types.LEFT_SQUARE_BRACKET;
import static org.codehaus.groovy.syntax.Types.LOGICAL_AND;
import static org.codehaus.groovy.syntax.Types.LOGICAL_OR;
import static org.codehaus.groovy.syntax.Types.MATCH_REGEX;
import static org.codehaus.groovy.syntax.Types.MINUS;
import static org.codehaus.groovy.syntax.Types.MINUS_EQUAL;
import static org.codehaus.groovy.syntax.Types.MOD;
import static org.codehaus.groovy.syntax.Types.MOD_EQUAL;
import static org.codehaus.groovy.syntax.Types.MULTIPLY;
import static org.codehaus.groovy.syntax.Types.MULTIPLY_EQUAL;
import static org.codehaus.groovy.syntax.Types.PLUS;
import static org.codehaus.groovy.syntax.Types.PLUS_EQUAL;
import static org.codehaus.groovy.syntax.Types.POWER;
import static org.codehaus.groovy.syntax.Types.POWER_EQUAL;
import static org.codehaus.groovy.syntax.Types.RIGHT_SHIFT;
import static org.codehaus.groovy.syntax.Types.RIGHT_SHIFT_EQUAL;
import static org.codehaus.groovy.syntax.Types.RIGHT_SHIFT_UNSIGNED;
import static org.codehaus.groovy.syntax.Types.RIGHT_SHIFT_UNSIGNED_EQUAL;
/**
* Support methods for {@link StaticTypeCheckingVisitor}.
*/
public abstract class StaticTypeCheckingSupport {
protected static final ClassNode Matcher_TYPE = makeWithoutCaching(Matcher.class);
protected static final ClassNode ArrayList_TYPE = makeWithoutCaching(ArrayList.class);
protected static final ClassNode Collection_TYPE = makeWithoutCaching(Collection.class);
protected static final ClassNode Deprecated_TYPE = makeWithoutCaching(Deprecated.class);
protected static final ExtensionMethodCache EXTENSION_METHOD_CACHE = ExtensionMethodCache.INSTANCE;
protected static final Map<ClassNode, Integer> NUMBER_TYPES = Maps.of(
byte_TYPE, 0,
Byte_TYPE, 0,
short_TYPE, 1,
Short_TYPE, 1,
int_TYPE, 2,
Integer_TYPE, 2,
Long_TYPE, 3,
long_TYPE, 3,
float_TYPE, 4,
Float_TYPE, 4,
double_TYPE, 5,
Double_TYPE, 5
);
protected static final Map<String, Integer> NUMBER_OPS = Maps.of(
"plus", PLUS,
"minus", MINUS,
"multiply", MULTIPLY,
"div", DIVIDE,
"or", BITWISE_OR,
"and", BITWISE_AND,
"xor", BITWISE_XOR,
"mod", MOD,
"intdiv", INTDIV,
"leftShift", LEFT_SHIFT,
"rightShift", RIGHT_SHIFT,
"rightShiftUnsigned", RIGHT_SHIFT_UNSIGNED
);
protected static final ClassNode GSTRING_STRING_CLASSNODE = WideningCategories.lowestUpperBound(
STRING_TYPE,
GSTRING_TYPE
);
/**
* This is for internal use only. When an argument method is null, we cannot determine its type, so
* we use this one as a wildcard.
*/
protected static final ClassNode UNKNOWN_PARAMETER_TYPE = make("<unknown parameter type>");
/**
* This comparator is used when we return the list of methods from DGM which name correspond to a given
* name. As we also lookup for DGM methods of superclasses or interfaces, it may be possible to find
* two methods which have the same name and the same arguments. In that case, we should not add the method
* from superclass or interface otherwise the system won't be able to select the correct method, resulting
* in an ambiguous method selection for similar methods.
*/
protected static final Comparator<MethodNode> DGM_METHOD_NODE_COMPARATOR = new Comparator<MethodNode>() {
@Override
public int compare(final MethodNode o1, final MethodNode o2) {
if (o1.getName().equals(o2.getName())) {
Parameter[] o1ps = o1.getParameters();
Parameter[] o2ps = o2.getParameters();
if (o1ps.length == o2ps.length) {
boolean allEqual = true;
for (int i = 0; i < o1ps.length && allEqual; i++) {
allEqual = o1ps[i].getType().equals(o2ps[i].getType());
}
if (allEqual) {
if (o1 instanceof ExtensionMethodNode && o2 instanceof ExtensionMethodNode) {
return compare(((ExtensionMethodNode) o1).getExtensionMethodNode(), ((ExtensionMethodNode) o2).getExtensionMethodNode());
}
return 0;
}
} else {
return o1ps.length - o2ps.length;
}
}
return 1;
}
};
public static void clearExtensionMethodCache() {
EXTENSION_METHOD_CACHE.cache.clearAll();
}
// GRECLIPSE add
public static void clearExtensionMethodCache(final ClassLoader loader) {
EXTENSION_METHOD_CACHE.cache.remove(loader);
}
// GRECLIPSE end
/**
* Returns true for expressions of the form x[...]
*
* @param expression an expression
* @return true for array access expressions
*/
protected static boolean isArrayAccessExpression(final Expression expression) {
return expression instanceof BinaryExpression && isArrayOp(((BinaryExpression) expression).getOperation().getType());
}
/**
* Called on method call checks in order to determine if a method call corresponds to the
* idiomatic o.with { ... } structure
*
* @param name name of the method called
* @param arguments method call arguments
* @return true if the name is "with" and arguments consist of a single closure
*/
public static boolean isWithCall(final String name, final Expression arguments) {
if ("with".equals(name) && arguments instanceof ArgumentListExpression) {
List<Expression> args = ((ArgumentListExpression) arguments).getExpressions();
if (args.size() == 1 && args.get(0) instanceof ClosureExpression) {
return true;
}
}
return false;
}
/**
* Given a variable expression, returns the ultimately accessed variable.
*
* @param ve a variable expression
* @return the target variable
*/
protected static Variable findTargetVariable(final VariableExpression ve) {
Variable accessedVariable = ve.getAccessedVariable();
if (accessedVariable != null && accessedVariable != ve) {
if (accessedVariable instanceof VariableExpression) {
return findTargetVariable((VariableExpression) accessedVariable);
}
return accessedVariable;
}
return ve;
}
/**
* @deprecated Use {@link #findDGMMethodsForClassNode(ClassLoader, ClassNode, String)} instead
*/
@Deprecated
protected static Set<MethodNode> findDGMMethodsForClassNode(final ClassNode clazz, final String name) {
return findDGMMethodsForClassNode(MetaClassRegistryImpl.class.getClassLoader(), clazz, name);
}
public static Set<MethodNode> findDGMMethodsForClassNode(final ClassLoader loader, final ClassNode clazz, final String name) {
TreeSet<MethodNode> accumulator = new TreeSet<>(DGM_METHOD_NODE_COMPARATOR);
findDGMMethodsForClassNode(loader, clazz, name, accumulator);
return accumulator;
}
/**
* @deprecated Use {@link #findDGMMethodsForClassNode(ClassLoader, ClassNode, String, TreeSet)} instead
*/
@Deprecated
protected static void findDGMMethodsForClassNode(final ClassNode clazz, final String name, final TreeSet<MethodNode> accumulator) {
findDGMMethodsForClassNode(MetaClassRegistryImpl.class.getClassLoader(), clazz, name, accumulator);
}
protected static void findDGMMethodsForClassNode(final ClassLoader loader, final ClassNode clazz, final String name, final TreeSet<MethodNode> accumulator) {
List<MethodNode> fromDGM = EXTENSION_METHOD_CACHE.get(loader).get(clazz.getName());
if (fromDGM != null) {
for (MethodNode node : fromDGM) {
if (node.getName().equals(name)) accumulator.add(node);
}
}
for (ClassNode node : clazz.getInterfaces()) {
findDGMMethodsForClassNode(loader, node, name, accumulator);
}
if (clazz.isArray()) {
ClassNode componentClass = clazz.getComponentType();
if (!componentClass.equals(OBJECT_TYPE) && !isPrimitiveType(componentClass)) {
if (componentClass.isInterface()) {
findDGMMethodsForClassNode(loader, OBJECT_TYPE.makeArray(), name, accumulator);
} else {
findDGMMethodsForClassNode(loader, componentClass.getSuperClass().makeArray(), name, accumulator);
}
}
}
if (clazz.getSuperClass() != null) {
findDGMMethodsForClassNode(loader, clazz.getSuperClass(), name, accumulator);
} else if (!clazz.equals(OBJECT_TYPE)) {
findDGMMethodsForClassNode(loader, OBJECT_TYPE, name, accumulator);
}
}
/**
* Checks that arguments and parameter types match.
*
* @return -1 if arguments do not match, 0 if arguments are of the exact type and > 0 when one or more argument is
* not of the exact type but still match
*/
public static int allParametersAndArgumentsMatch(Parameter[] parameters, final ClassNode[] argumentTypes) {
if (parameters == null) {
parameters = Parameter.EMPTY_ARRAY;
}
int dist = 0;
if (argumentTypes.length < parameters.length) {
return -1;
}
// we already know there are at least params.length elements in both arrays
for (int i = 0, n = parameters.length; i < n; i += 1) {
ClassNode paramType = parameters[i].getType();
ClassNode argType = argumentTypes[i];
if (!isAssignableTo(argType, paramType)) {
return -1;
} else if (!paramType.equals(argType)) {
dist += getDistance(argType, paramType);
}
}
return dist;
}
/**
* Checks that arguments and parameter types match, expecting that the number of parameters is strictly greater
* than the number of arguments, allowing possible inclusion of default parameters.
*
* @return -1 if arguments do not match, 0 if arguments are of the exact type and >0 when one or more argument is
* not of the exact type but still match
*/
static int allParametersAndArgumentsMatchWithDefaultParams(final Parameter[] parameters, final ClassNode[] argumentTypes) {
int dist = 0;
ClassNode ptype = null;
// we already know the lengths are equal
for (int i = 0, j = 0, n = parameters.length; i < n; i += 1) {
Parameter param = parameters[i];
ClassNode paramType = param.getType();
ClassNode arg = (j >= argumentTypes.length ? null : argumentTypes[j]);
if (arg == null || !isAssignableTo(arg, paramType)) {
if (!param.hasInitialExpression() && (ptype == null || !ptype.equals(paramType))) {
return -1; // no default value
}
// a default value exists, we can skip this param
ptype = null;
} else {
j += 1;
if (!paramType.equals(arg)) {
dist += getDistance(arg, paramType);
}
if (param.hasInitialExpression()) {
ptype = arg;
} else {
ptype = null;
}
}
}
return dist;
}
/**
* Checks that excess arguments match the vararg signature parameter.
*
* @return -1 if no match, 0 if all arguments matches the vararg type and >0 if one or more vararg argument is
* assignable to the vararg type, but still not an exact match
*/
static int excessArgumentsMatchesVargsParameter(final Parameter[] parameters, final ClassNode[] argumentTypes) {
// we already know parameter length is bigger zero and last is a vargs
// the excess arguments are all put in an array for the vargs call
// so check against the component type
int dist = 0;
ClassNode vargsBase = parameters[parameters.length - 1].getType().getComponentType();
for (int i = parameters.length; i < argumentTypes.length; i += 1) {
if (!isAssignableTo(argumentTypes[i], vargsBase)) return -1;
else dist += getClassDistance(vargsBase, argumentTypes[i]);
}
return dist;
}
/**
* Checks if the last argument matches the vararg type.
*
* @return -1 if no match, 0 if the last argument is exactly the vararg type and 1 if of an assignable type
*/
static int lastArgMatchesVarg(final Parameter[] parameters, final ClassNode... argumentTypes) {
if (!isVargs(parameters)) return -1;
// case length ==0 handled already
// we have now two cases,
// the argument is wrapped in the vargs array or
// the argument is an array that can be used for the vargs part directly
// we test only the wrapping part, since the non wrapping is done already
ClassNode lastParamType = parameters[parameters.length - 1].getType();
ClassNode ptype = lastParamType.getComponentType();
ClassNode arg = argumentTypes[argumentTypes.length - 1];
if (isNumberType(ptype) && isNumberType(arg) && !getWrapper(ptype).equals(getWrapper(arg))) return -1;
return isAssignableTo(arg, ptype) ? min(getDistance(arg, lastParamType), getDistance(arg, ptype)) : -1;
}
/**
* Checks if a class node is assignable to another. This is used for example in
* assignment checks where you want to verify that the assignment is valid.
*
* @return true if the class node is assignable to the other class node, false otherwise
*/
// GRECLIPSE package->public
public static boolean isAssignableTo(ClassNode type, ClassNode toBeAssignedTo) {
if (type == toBeAssignedTo || type == UNKNOWN_PARAMETER_TYPE) return true;
if (isPrimitiveType(type)) type = getWrapper(type);
if (isPrimitiveType(toBeAssignedTo)) toBeAssignedTo = getWrapper(toBeAssignedTo);
if (NUMBER_TYPES.containsKey(type.redirect()) && NUMBER_TYPES.containsKey(toBeAssignedTo.redirect())) {
return NUMBER_TYPES.get(type.redirect()) <= NUMBER_TYPES.get(toBeAssignedTo.redirect());
}
if (type.isArray() && toBeAssignedTo.isArray()) {
return isAssignableTo(type.getComponentType(), toBeAssignedTo.getComponentType());
}
if (type.isDerivedFrom(GSTRING_TYPE) && STRING_TYPE.equals(toBeAssignedTo)) {
return true;
}
if (STRING_TYPE.equals(type) && toBeAssignedTo.isDerivedFrom(GSTRING_TYPE)) {
return true;
}
if (implementsInterfaceOrIsSubclassOf(type, toBeAssignedTo)) {
if (toBeAssignedTo.getGenericsTypes() != null) {
// perform additional check on generics
// ? extends toBeAssignedTo
GenericsType gt = GenericsUtils.buildWildcardType(toBeAssignedTo);
return gt.isCompatibleWith(type);
}
return true;
}
// SAM check
if (type.isDerivedFrom(CLOSURE_TYPE) && isSAMType(toBeAssignedTo)) {
return true;
}
return false;
}
static boolean isVargs(final Parameter[] parameters) {
if (parameters == null || parameters.length == 0) return false;
return (parameters[parameters.length - 1].getType().isArray());
}
public static boolean isCompareToBoolean(final int op) {
return op == COMPARE_LESS_THAN || op == COMPARE_LESS_THAN_EQUAL
|| op == COMPARE_GREATER_THAN || op == COMPARE_GREATER_THAN_EQUAL;
}
static boolean isArrayOp(final int op) {
return op == LEFT_SQUARE_BRACKET;
}
static boolean isBoolIntrinsicOp(final int op) {
switch (op) {
case LOGICAL_AND:
case LOGICAL_OR:
case COMPARE_NOT_IDENTICAL:
case COMPARE_IDENTICAL:
case MATCH_REGEX:
case KEYWORD_INSTANCEOF:
case COMPARE_NOT_INSTANCEOF:
return true;
default:
return false;
}
}
static boolean isPowerOperator(final int op) {
return op == POWER || op == POWER_EQUAL;
}
static String getOperationName(final int op) {
switch (op) {
case COMPARE_EQUAL:
case COMPARE_NOT_EQUAL:
// this is only correct in this context here, normally
// we would have to compile against compareTo if available
// but since we don't compile here, this one is enough
return "equals";
case COMPARE_TO:
case COMPARE_GREATER_THAN:
case COMPARE_GREATER_THAN_EQUAL:
case COMPARE_LESS_THAN:
case COMPARE_LESS_THAN_EQUAL:
return "compareTo";
case BITWISE_AND:
case BITWISE_AND_EQUAL:
return "and";
case BITWISE_OR:
case BITWISE_OR_EQUAL:
return "or";
case BITWISE_XOR:
case BITWISE_XOR_EQUAL:
return "xor";
case PLUS:
case PLUS_EQUAL:
return "plus";
case MINUS:
case MINUS_EQUAL:
return "minus";
case MULTIPLY:
case MULTIPLY_EQUAL:
return "multiply";
case DIVIDE:
case DIVIDE_EQUAL:
return "div";
case INTDIV:
case INTDIV_EQUAL:
return "intdiv";
case MOD:
case MOD_EQUAL:
return "mod";
case POWER:
case POWER_EQUAL:
return "power";
case LEFT_SHIFT:
case LEFT_SHIFT_EQUAL:
return "leftShift";
case RIGHT_SHIFT:
case RIGHT_SHIFT_EQUAL:
return "rightShift";
case RIGHT_SHIFT_UNSIGNED:
case RIGHT_SHIFT_UNSIGNED_EQUAL:
return "rightShiftUnsigned";
case KEYWORD_IN:
return "isCase";
case COMPARE_NOT_IN:
return "isNotCase";
default:
return null;
}
}
static boolean isShiftOperation(final String name) {
return "leftShift".equals(name) || "rightShift".equals(name) || "rightShiftUnsigned".equals(name);
}
/**
* Returns true for operations that are of the class, that given a common type class for left and right, the
* operation "left op right" will have a result in the same type class In Groovy on numbers that is +,-,* as well as
* their variants with equals.
*/
static boolean isOperationInGroup(final int op) {
switch (op) {
case PLUS:
case PLUS_EQUAL:
case MINUS:
case MINUS_EQUAL:
case MULTIPLY:
case MULTIPLY_EQUAL:
return true;
default:
return false;
}
}
static boolean isBitOperator(final int op) {
switch (op) {
case BITWISE_OR_EQUAL:
case BITWISE_OR:
case BITWISE_AND_EQUAL:
case BITWISE_AND:
case BITWISE_XOR_EQUAL:
case BITWISE_XOR:
return true;
default:
return false;
}
}
public static boolean isAssignment(final int op) {
return Types.isAssignment(op);
}
/**
* Returns true or false depending on whether the right classnode can be assigned to the left classnode. This method
* should not add errors by itself: we let the caller decide what to do if an incompatible assignment is found.
*
* @param left the class to be assigned to
* @param right the assignee class
* @return false if types are incompatible
*/
public static boolean checkCompatibleAssignmentTypes(final ClassNode left, final ClassNode right) {
return checkCompatibleAssignmentTypes(left, right, null);
}
public static boolean checkCompatibleAssignmentTypes(final ClassNode left, final ClassNode right, final Expression rightExpression) {
return checkCompatibleAssignmentTypes(left, right, rightExpression, true);
}
public static boolean checkCompatibleAssignmentTypes(final ClassNode left, final ClassNode right, final Expression rightExpression, final boolean allowConstructorCoercion) {
ClassNode leftRedirect = left.redirect();
ClassNode rightRedirect = right.redirect();
if (leftRedirect == rightRedirect) return true;
if (leftRedirect.isArray() && rightRedirect.isArray()) {
return checkCompatibleAssignmentTypes(leftRedirect.getComponentType(), rightRedirect.getComponentType(), rightExpression, false);
}
if (rightRedirect == VOID_TYPE || rightRedirect == void_WRAPPER_TYPE) {
return leftRedirect == VOID_TYPE || leftRedirect == void_WRAPPER_TYPE;
}
if (isNumberType(rightRedirect) || WideningCategories.isNumberCategory(rightRedirect)) {
if (leftRedirect.equals(BigDecimal_TYPE) || leftRedirect.equals(Number_TYPE)) { // GRECLIPSE add -- GROOVY-9935
// any number can be assigned to a big decimal
return true;
}
if (leftRedirect.equals(BigInteger_TYPE)) {
return WideningCategories.isBigIntCategory(getUnwrapper(rightRedirect)) || rightRedirect.isDerivedFrom(BigInteger_TYPE);
}
}
// if rightExpression is null and leftExpression is not a primitive type, it's ok
boolean rightExpressionIsNull = org.apache.groovy.ast.tools.ExpressionUtils.isNullConstant(rightExpression);
if (rightExpressionIsNull && !isPrimitiveType(left)) {
return true;
}
// on an assignment everything that can be done by a GroovyCast is allowed
// anything can be assigned to an Object, String, Boolean or Class typed variable
if (isWildcardLeftHandSide(leftRedirect) && !(left.equals(boolean_TYPE) && rightExpressionIsNull)) return true;
// char as left expression
if (leftRedirect == char_TYPE && rightRedirect == STRING_TYPE) {
if (rightExpression instanceof ConstantExpression) {
String value = rightExpression.getText();
return value.length() == 1;
}
}
if (leftRedirect == Character_TYPE && (rightRedirect == STRING_TYPE || rightExpressionIsNull)) {
return rightExpressionIsNull || (rightExpression instanceof ConstantExpression && rightExpression.getText().length() == 1);
}
// if left is Enum and right is String or GString we do valueOf
if (leftRedirect.isDerivedFrom(Enum_Type) && (rightRedirect == STRING_TYPE || rightRedirect.equals(GSTRING_TYPE))) {
return true;
}
// if right is array, map or collection we try invoking the constructor
if (allowConstructorCoercion && isGroovyConstructorCompatible(rightExpression)) {
// TODO: in case of the array we could maybe make a partial check
if (leftRedirect.isArray() && rightRedirect.isArray()) {
return checkCompatibleAssignmentTypes(leftRedirect.getComponentType(), rightRedirect.getComponentType());
} else if (rightRedirect.isArray() && !leftRedirect.isArray()) {
return false;
}
return true;
}
// simple check on being subclass
if (right.isDerivedFrom(left) || (left.isInterface() && right.implementsInterface(left))) return true;
// if left and right are primitives or numbers allow
if (isPrimitiveType(leftRedirect) && isPrimitiveType(rightRedirect)) return true;
if (isNumberType(leftRedirect) && isNumberType(rightRedirect)) return true;
// left is a float/double and right is a BigDecimal
if (WideningCategories.isFloatingCategory(leftRedirect) && BigDecimal_TYPE.equals(rightRedirect)) {
return true;
}
if (leftRedirect.equals(GROOVY_OBJECT_TYPE) && isBeingCompiled(right)) {
return true;
}
if (left.isGenericsPlaceHolder()) {
// GROOVY-7307
GenericsType[] genericsTypes = left.getGenericsTypes();
if (genericsTypes != null && genericsTypes.length == 1) {
// should always be the case, but safe guard is better
return genericsTypes[0].isCompatibleWith(right);
}
}
// GROOVY-7316: It is an apparently legal thing to allow this. It's not type safe, but it is allowed...
return right.isGenericsPlaceHolder();
}
private static boolean isGroovyConstructorCompatible(final Expression rightExpression) {
return rightExpression instanceof ListExpression
|| rightExpression instanceof MapExpression
|| rightExpression instanceof ArrayExpression;
}
/**
* Tells if a class is one of the "accept all" classes as the left hand side of an
* assignment.
*
* @param node the classnode to test
* @return true if it's an Object, String, boolean, Boolean or Class.
*/
public static boolean isWildcardLeftHandSide(final ClassNode node) {
return (OBJECT_TYPE.equals(node)
|| STRING_TYPE.equals(node)
|| boolean_TYPE.equals(node)
|| Boolean_TYPE.equals(node)
|| CLASS_Type.equals(node));
}
public static boolean isBeingCompiled(final ClassNode node) {
return (node.getCompileUnit() != null);
}
@Deprecated
static boolean checkPossibleLooseOfPrecision(final ClassNode left, final ClassNode right, final Expression rightExpr) {
return checkPossibleLossOfPrecision(left, right, rightExpr);
}
static boolean checkPossibleLossOfPrecision(final ClassNode left, final ClassNode right, final Expression rightExpr) {
if (left == right || left.equals(right)) return false; // identical types
int leftIndex = NUMBER_TYPES.get(left);
int rightIndex = NUMBER_TYPES.get(right);
if (leftIndex >= rightIndex) return false;
// here we must check if the right number is short enough to fit in the left type
if (rightExpr instanceof ConstantExpression) {
Object value = ((ConstantExpression) rightExpr).getValue();
if (!(value instanceof Number)) return true;
Number number = (Number) value;
switch (leftIndex) {
case 0: { // byte
byte val = number.byteValue();
if (number instanceof Short) {
return !Short.valueOf(val).equals(number);
}
if (number instanceof Integer) {
return !Integer.valueOf(val).equals(number);
}
if (number instanceof Long) {
return !Long.valueOf(val).equals(number);
}
if (number instanceof Float) {
return !Float.valueOf(val).equals(number);
}
return !Double.valueOf(val).equals(number);
}
case 1: { // short
short val = number.shortValue();
if (number instanceof Integer) {
return !Integer.valueOf(val).equals(number);
}
if (number instanceof Long) {
return !Long.valueOf(val).equals(number);
}
if (number instanceof Float) {
return !Float.valueOf(val).equals(number);
}
return !Double.valueOf(val).equals(number);
}
case 2: { // integer
int val = number.intValue();
if (number instanceof Long) {
return !Long.valueOf(val).equals(number);
}
if (number instanceof Float) {
return !Float.valueOf(val).equals(number);
}
return !Double.valueOf(val).equals(number);
}
case 3: { // long
long val = number.longValue();
if (number instanceof Float) {
return !Float.valueOf(val).equals(number);
}
return !Double.valueOf(val).equals(number);
}
case 4: { // float
float val = number.floatValue();
return !Double.valueOf(val).equals(number);
}
default: // double
return false; // no possible loose here
}
}
return true; // possible loss of precision
}
static String toMethodParametersString(final String methodName, final ClassNode... parameters) {
StringBuilder sb = new StringBuilder(methodName);
sb.append('(');
if (parameters != null) {
for (int i = 0, n = parameters.length; i < n; i += 1) {
sb.append(prettyPrintType(parameters[i]));
if (i < n - 1) sb.append(", ");
}
}
sb.append(')');
return sb.toString();
}
static String prettyPrintType(ClassNode type) {
if (type.isArray()) {
return prettyPrintType(type.getComponentType()) + "[]";
}
return type.toString(false);
}
public static boolean implementsInterfaceOrIsSubclassOf(final ClassNode type, final ClassNode superOrInterface) {
boolean result = (type.equals(superOrInterface)
|| type.isDerivedFrom(superOrInterface)
|| type.implementsInterface(superOrInterface)
|| type == UNKNOWN_PARAMETER_TYPE);
if (result) {
return true;
}
if (superOrInterface instanceof WideningCategories.LowestUpperBoundClassNode) {
WideningCategories.LowestUpperBoundClassNode cn = (WideningCategories.LowestUpperBoundClassNode) superOrInterface;
result = implementsInterfaceOrIsSubclassOf(type, cn.getSuperClass());
if (result) {
for (ClassNode interfaceNode : cn.getInterfaces()) {
result = type.implementsInterface(interfaceNode);
if (!result) break;
}
}
if (result) return true;
} else if (superOrInterface instanceof UnionTypeClassNode) {
UnionTypeClassNode union = (UnionTypeClassNode) superOrInterface;
for (ClassNode delegate : union.getDelegates()) {
if (implementsInterfaceOrIsSubclassOf(type, delegate)) return true;
}
}
if (type.isArray() && superOrInterface.isArray()) {
return implementsInterfaceOrIsSubclassOf(type.getComponentType(), superOrInterface.getComponentType());
}
if (GROOVY_OBJECT_TYPE.equals(superOrInterface) && !type.isInterface() && isBeingCompiled(type)) {
return true;
}
return false;
}
static int getPrimitiveDistance(ClassNode primA, ClassNode primB) {
return Math.abs(NUMBER_TYPES.get(primA) - NUMBER_TYPES.get(primB));
}
static int getDistance(final ClassNode receiver, final ClassNode compare) {
if (receiver.isArray() && compare.isArray()) {
return getDistance(receiver.getComponentType(), compare.getComponentType());
}
int dist = 0;
ClassNode unwrapReceiver = getUnwrapper(receiver);
ClassNode unwrapCompare = getUnwrapper(compare);
if (isPrimitiveType(unwrapReceiver)
&& isPrimitiveType(unwrapCompare)
&& unwrapReceiver != unwrapCompare) {
dist = getPrimitiveDistance(unwrapReceiver, unwrapCompare);
}
// Add a penalty against boxing or unboxing, to get a resolution similar to JLS 15.12.2
// (http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2).
if (isPrimitiveType(receiver) ^ isPrimitiveType(compare)) {
dist = (dist + 1) << 1;
}
if (unwrapCompare.equals(unwrapReceiver)) return dist;
if (receiver.isArray() && !compare.isArray()) {
// Object[] vs Object
dist += 256;
}
if (receiver == UNKNOWN_PARAMETER_TYPE) {
return dist;
}
// GRECLIPSE add -- GROOVY-9852, GROOVY-9881
if (compare.isInterface()) { MethodNode sam;
if (receiver.implementsInterface(compare)) {
return dist + getMaximumInterfaceDistance(receiver, compare);
} else if (receiver.equals(CLOSURE_TYPE) && (sam = findSAM(compare)) != null) {
// GROOVY-9881: in case of multiple overloads, give preference to equal parameter count
Integer closureParamCount = receiver.getNodeMetaData(StaticTypesMarker.CLOSURE_ARGUMENTS);
if (closureParamCount != null && closureParamCount == sam.getParameters().length) dist -= 1;
return dist + 13; // GROOVY-9852: @FunctionalInterface vs Object
}
}
// GRECLIPSE end
ClassNode ref = isPrimitiveType(receiver) && !isPrimitiveType(compare) ? getWrapper(receiver) : receiver;
while (ref != null) {
if (compare.equals(ref)) {
break;
}
if (compare.isInterface() && ref.implementsInterface(compare)) {
dist += getMaximumInterfaceDistance(ref, compare);
break;
}
ref = ref.getSuperClass();
dist += 1;
if (OBJECT_TYPE.equals(ref))
dist += 1;
dist = (dist + 1) << 1;
}
return dist;
}
private static int getMaximumInterfaceDistance(final ClassNode c, final ClassNode interfaceClass) {
// -1 means a mismatch
if (c == null) return -1;
// 0 means a direct match
if (c.equals(interfaceClass)) return 0;
ClassNode[] interfaces = c.getInterfaces();
int max = -1;
for (ClassNode anInterface : interfaces) {
int sub = getMaximumInterfaceDistance(anInterface, interfaceClass);
// we need to keep the -1 to track the mismatch, a +1
// by any means could let it look like a direct match
// we want to add one, because there is an interface between
// the interface we search for and the interface we are in.
if (sub != -1) {
sub += 1;
}
// we are interested in the longest path only
max = Math.max(max, sub);
}
// we do not add one for super classes, only for interfaces
int superClassMax = getMaximumInterfaceDistance(c.getSuperClass(), interfaceClass);
return Math.max(max, superClassMax);
}
/**
* @deprecated Use {@link #findDGMMethodsByNameAndArguments(ClassLoader, ClassNode, String, ClassNode[], List)} instead
*/
@Deprecated
public static List<MethodNode> findDGMMethodsByNameAndArguments(final ClassNode receiver, final String name, final ClassNode[] args) {
return findDGMMethodsByNameAndArguments(MetaClassRegistryImpl.class.getClassLoader(), receiver, name, args);
}
public static List<MethodNode> findDGMMethodsByNameAndArguments(final ClassLoader loader, final ClassNode receiver, final String name, final ClassNode[] args) {
return findDGMMethodsByNameAndArguments(loader, receiver, name, args, new LinkedList<>());
}
/**
* @deprecated Use {@link #findDGMMethodsByNameAndArguments(ClassLoader, ClassNode, String, ClassNode[], List)} instead
*/
@Deprecated
public static List<MethodNode> findDGMMethodsByNameAndArguments(final ClassNode receiver, final String name, final ClassNode[] args, final List<MethodNode> methods) {
return findDGMMethodsByNameAndArguments(MetaClassRegistryImpl.class.getClassLoader(), receiver, name, args, methods);
}
public static List<MethodNode> findDGMMethodsByNameAndArguments(final ClassLoader loader, final ClassNode receiver, final String name, final ClassNode[] args, final List<MethodNode> methods) {
methods.addAll(findDGMMethodsForClassNode(loader, receiver, name));
return methods.isEmpty() ? methods : chooseBestMethod(receiver, methods, args);