-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathWurstValidator.java
More file actions
3220 lines (2857 loc) · 127 KB
/
WurstValidator.java
File metadata and controls
3220 lines (2857 loc) · 127 KB
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
package de.peeeq.wurstscript.validation;
import com.google.common.collect.*;
import de.peeeq.wurstscript.WLogger;
import de.peeeq.wurstscript.ast.*;
import de.peeeq.wurstscript.attributes.CofigOverridePackages;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.attributes.ImplicitFuncs;
import de.peeeq.wurstscript.attributes.OverloadingResolver;
import de.peeeq.wurstscript.attributes.names.DefLink;
import de.peeeq.wurstscript.attributes.names.FuncLink;
import de.peeeq.wurstscript.attributes.names.NameLink;
import de.peeeq.wurstscript.attributes.names.OtherLink;
import de.peeeq.wurstscript.attributes.names.VarLink;
import de.peeeq.wurstscript.gui.ProgressHelper;
import de.peeeq.wurstscript.types.*;
import de.peeeq.wurstscript.utils.Utils;
import de.peeeq.wurstscript.validation.controlflow.DataflowAnomalyAnalysis;
import de.peeeq.wurstscript.validation.controlflow.ReturnsAnalysis;
import io.vavr.Tuple2;
import it.unimi.dsi.fastutil.objects.Reference2BooleanOpenHashMap;
import org.eclipse.jdt.annotation.Nullable;
import java.util.*;
import java.util.stream.Collectors;
import static de.peeeq.wurstscript.attributes.SmallHelpers.superArgs;
/**
* this class validates a wurstscript program
* <p>
* it has visit methods for different elements in the AST and checks whether
* these are correct
* <p>
* the validation phase might not find all errors, code transformation and
* optimization phases might detect other errors because they do a more
* sophisticated analysis of the program
* <p>
* also note that many cases are already caught by the calculation of the
* attributes
*/
public class WurstValidator {
private enum Phase { LIGHT, HEAVY }
private Phase phase = Phase.LIGHT;
private boolean isHeavy() { return phase == Phase.HEAVY; }
private final ArrayList<FunctionLike> heavyFunctions = new ArrayList<>();
private final ArrayList<ExprStatementsBlock> heavyBlocks = new ArrayList<>();
private final WurstModel prog;
private int functionCount;
private int visitedFunctions;
private final Multimap<WScope, WScope> calledFunctions = HashMultimap.create();
private @Nullable Element lastElement = null;
private final HashSet<String> trveWrapperFuncs = new HashSet<>();
private final HashMap<String, HashSet<FunctionCall>> wrapperCalls = new HashMap<>();
private final Map<ClassDef, Map<GlobalVarDef, Integer>> classVarInitOrderCache = new HashMap<>();
public WurstValidator(WurstModel root) {
this.prog = root;
}
public void validate(Collection<CompilationUnit> toCheck) {
try {
functionCount = countFunctions();
visitedFunctions = 0;
heavyFunctions.clear();
heavyBlocks.clear();
GlobalCaches.invalidateFor(prog, toCheck);
lightValidation(toCheck);
heavyValidation();
prog.getErrorHandler().setProgress("Post checks", 0.55);
postChecks(toCheck);
} catch (RuntimeException e) {
WLogger.severe(e);
Element le = lastElement;
if (le != null) {
le.addError("Encountered compiler bug near element " + Utils.printElement(le) + ":\n"
+ Utils.printException(e));
} else {
throw e;
}
}
}
private void heavyValidation() {
// ===== Phase 2: HEAVY (process only collected targets) =====
phase = Phase.HEAVY;
visitedFunctions = 0;
prog.getErrorHandler().setProgress("Validation (control-flow + dataflow)", 0.5);
// functions: returns + DFA + reachability walk inside the function body
for (FunctionLike f : heavyFunctions) {
// returns + DFA
checkUninitializedVars(f);
// reachability: walk only the function body statements
Element body = (f instanceof FunctionImplementation)
? ((FunctionImplementation) f).getBody()
: f; // closures use ExprStatementsBlock path below
walkReachability(body);
}
// closure blocks collected for DFA
for (ExprStatementsBlock b : heavyBlocks) {
new DataflowAnomalyAnalysis(false).execute(b);
walkReachability(b);
}
}
private void lightValidation(Collection<CompilationUnit> toCheck) {
// ===== Phase 1: LIGHT (all regular checks, collect heavy targets) =====
phase = Phase.LIGHT;
prog.getErrorHandler().setProgress("Validation (light)",
ProgressHelper.getValidatorPercent(0, Math.max(1, functionCount)));
for (CompilationUnit cu : toCheck) {
walkTree(cu);
}
// Build CFG once for heavy phase (enables reachability/prev/next attrs)
for (CompilationUnit cu : toCheck) {
computeFlowAttributes(cu);
}
}
/** Visit only statements under root and run checkReachability where applicable. */
private void walkReachability(Element root) {
// fast local traversal; no other checks
Deque<Element> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
Element e = stack.pop();
if (e instanceof WStatement) {
checkReachability((WStatement) e);
}
for (int i = e.size() - 1; i >= 0; i--) {
stack.push(e.get(i));
}
}
}
/**
* checks done after walking the tree
*/
private void postChecks(Collection<CompilationUnit> toCheck) {
checkUnusedImports(toCheck);
ValidateGlobalsUsage.checkGlobalsUsage(toCheck);
ValidateClassMemberUsage.checkClassMembers(toCheck);
ValidateLocalUsage.checkLocalsUsage(toCheck);
for (String wrapper : trveWrapperFuncs) {
if (wrapperCalls.containsKey(wrapper)) {
for (FunctionCall call : wrapperCalls.get(wrapper)) {
if (call.getArgs().size() > 1 && call.getArgs().get(1) instanceof ExprStringVal) {
ExprStringVal varName = (ExprStringVal) call.getArgs().get(1);
TRVEHelper.protectedVariables.add(varName.getValS());
WLogger.info("keep: " + varName.getValS());
} else {
call.addError("Map contains TriggerRegisterVariableEvent with non-constant arguments. Can't be optimized.");
}
}
}
}
}
private void checkUnusedImports(Collection<CompilationUnit> toCheck) {
for (CompilationUnit cu : toCheck) {
for (WPackage p : cu.getPackages()) {
checkUnusedImports(p);
}
}
}
private void checkUnusedImports(WPackage p) {
Set<PackageOrGlobal> used = Sets.newLinkedHashSet();
collectUsedPackages(used, p.getElements());
// String usedToStr =
// used.stream().map(Utils::printElement).sorted().collect(Collectors.joining(",
// "));
// System.out.println("used = " + usedToStr);
// contributed packages for each import
Map<WImport, Set<WPackage>> contributions = new HashMap<>();
for (WImport imp : p.getImports()) {
Set<WPackage> contributedPackages = contributedPackages(imp.attrImportedPackage(), used, new HashSet<>());
contributions.put(imp, contributedPackages);
// System.out.println( imp.getPackagename() + " contributes = " +
// contributedPackages.stream().map(Utils::printElement).sorted().collect(Collectors.joining(",
// ")));
}
// check for imports, which only contribute a subset of some other
// import
for (WImport imp : p.getImports()) {
if (imp.attrImportedPackage() == null || imp.getIsPublic() || imp.getPackagename().equals("Wurst")) {
continue;
}
Set<WPackage> impContributions = contributions.get(imp);
if (impContributions.isEmpty()) {
imp.addWarning("The import " + imp.getPackagename() + " is never used");
} else {
for (WImport imp2 : p.getImports()) {
if (imp == imp2) {
continue;
}
if (contributions.get(imp2).containsAll(impContributions)) {
imp.addWarning("The import " + imp.getPackagename()
+ " can be removed, because it is already included in " + imp2.getPackagename() + ".");
break;
}
}
}
}
}
private Set<WPackage> contributedPackages(WPackage p, Set<PackageOrGlobal> used, Set<WPackage> visited) {
if (p == null) {
return Collections.emptySet();
}
visited.add(p);
Set<WPackage> result = new HashSet<>();
if (used.contains(p)) {
result.add(p);
}
for (WImport imp : p.getImports()) {
WPackage imported = imp.attrImportedPackage();
if (imp.getPackagename().equals("Wurst") || visited.contains(imported)) {
continue;
}
if (imp.getIsPublic()) {
result.addAll(contributedPackages(imported, used, visited));
}
}
return result;
}
private WPackage getConfiguredPackage(Element e) {
PackageOrGlobal p = e.attrNearestPackage();
if(p instanceof WPackage) {
if (p.getModel().attrConfigOverridePackages().containsValue(p)) {
for(WPackage k : p.getModel().attrConfigOverridePackages().keySet()) {
if(p.getModel().attrConfigOverridePackages().get(k).equals(p)) {
return k;
}
}
}
}
return null;
}
private void collectUsedPackages(Set<PackageOrGlobal> used, Element root) {
ArrayDeque<Object> stack = new ArrayDeque<>();
// Push (element, visited=false). Boolean marks "post" processing.
stack.push(Boolean.FALSE);
stack.push(root);
while (!stack.isEmpty()) {
Element e = (Element) stack.pop();
boolean visited = (Boolean) stack.pop();
if (!visited) {
// schedule post-visit
stack.push(Boolean.TRUE);
stack.push(e);
// push children for pre-visit (so they’re processed before e)
for (int i = e.size() - 1; i >= 0; i--) {
Element c = e.get(i);
stack.push(Boolean.FALSE);
stack.push(c);
}
continue;
}
// === post-order node work (same as your original) ===
if (e instanceof FuncRef) {
FuncRef fr = (FuncRef) e;
FuncLink link = fr.attrFuncLink();
if (link != null) {
used.add(link.getDef().attrNearestPackage());
if (link.getDef().attrHasAnnotation("@config")) {
WPackage configPackage = getConfiguredPackage(link.getDef());
if (configPackage != null) {
used.add(configPackage);
}
}
}
}
if (e instanceof NameRef) {
NameRef nr = (NameRef) e;
NameLink def = nr.attrNameLink();
if (def != null && !(def instanceof OtherLink)) {
used.add(def.getDef().attrNearestPackage());
if (def.getDef().attrHasAnnotation("@config")) {
WPackage configPackage = getConfiguredPackage(def.getDef());
if (configPackage != null) {
used.add(configPackage);
}
}
}
}
if (e instanceof TypeRef) {
TypeRef t = (TypeRef) e;
TypeDef def = t.attrTypeDef();
if (def != null) {
used.add(def.attrNearestPackage());
}
}
if (e instanceof ExprBinary) {
ExprBinary binop = (ExprBinary) e;
FuncLink def = binop.attrFuncLink();
if (def != null) {
used.add(def.getDef().attrNearestPackage());
}
}
if (e instanceof Expr) {
WurstType typ = ((Expr) e).attrTyp();
if (typ instanceof WurstTypeNamedScope) {
WurstTypeNamedScope ns = (WurstTypeNamedScope) typ;
NamedScope def = ns.getDef();
if (def != null) {
used.add(def.attrNearestPackage());
}
} else if (typ instanceof WurstTypeTuple) {
TupleDef def = ((WurstTypeTuple) typ).getTupleDef();
used.add(def.attrNearestPackage());
}
}
if (e instanceof ModuleUse) {
ModuleUse mu = (ModuleUse) e;
@Nullable ModuleDef def = mu.attrModuleDef();
if (def != null) {
used.add(def.attrNearestPackage());
}
}
}
}
private void walkTree(Element root) {
ArrayDeque<Element> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
Element e = stack.pop();
lastElement = e;
check(e);
lastElement = null;
// left→right order: push in reverse
for (int i = e.size() - 1; i >= 0; i--) {
stack.push(e.get(i));
}
}
}
private void check(Element e) {
try {
if (e instanceof Annotation)
checkAnnotation((Annotation) e);
if (e instanceof AstElementWithTypeParameters)
checkTypeParameters((AstElementWithTypeParameters) e);
if (e instanceof AstElementWithNameId)
checkName((AstElementWithNameId) e);
if (e instanceof ClassDef) {
checkAbstractMethods((ClassDef) e);
visit((ClassDef) e);
}
if (e instanceof ClassOrModule)
checkConstructorsUnique((ClassOrModule) e);
if (e instanceof CompilationUnit)
checkPackageName((CompilationUnit) e);
if (e instanceof ConstructorDef) {
checkConstructor((ConstructorDef) e);
checkThisConstructorCall((ConstructorDef) e);
checkConstructorSuperCall((ConstructorDef) e);
}
if (e instanceof ExprBinary)
visit((ExprBinary) e);
if (e instanceof ExprClosure)
checkClosure((ExprClosure) e);
if (e instanceof ExprEmpty)
checkExprEmpty((ExprEmpty) e);
if (e instanceof ExprIntVal)
checkIntVal((ExprIntVal) e);
if (e instanceof ExprFuncRef)
checkFuncRef((ExprFuncRef) e);
if (e instanceof ExprFunctionCall) {
checkBannedFunctions((ExprFunctionCall) e);
visit((ExprFunctionCall) e);
}
if (e instanceof ExprMemberMethod)
visit((ExprMemberMethod) e);
if (e instanceof ExprMemberVar)
checkMemberVar((ExprMemberVar) e);
if (e instanceof ExprMemberArrayVar)
checkMemberArrayVar((ExprMemberArrayVar) e);
if (e instanceof ExprNewObject) {
checkNewObj((ExprNewObject) e);
visit((ExprNewObject) e);
}
if (e instanceof ExprNull)
checkExprNull((ExprNull) e);
if (e instanceof ExprVarAccess)
visit((ExprVarAccess) e);
if (e instanceof ExprVarArrayAccess)
checkArrayAccess((ExprVarArrayAccess) e);
if (e instanceof ExtensionFuncDef)
visit((ExtensionFuncDef) e);
if (e instanceof FuncDef)
visit((FuncDef) e);
if (e instanceof FuncRef)
checkFuncRef((FuncRef) e);
if (e instanceof FunctionLike)
checkUninitializedVars((FunctionLike) e);
if (e instanceof GlobalVarDef)
visit((GlobalVarDef) e);
if (e instanceof HasModifier)
checkModifiers((HasModifier) e);
if (e instanceof HasTypeArgs)
checkTypeBinding((HasTypeArgs) e);
if (e instanceof InterfaceDef)
checkInterfaceDef((InterfaceDef) e);
if (e instanceof LocalVarDef) {
checkLocalShadowing((LocalVarDef) e);
visit((LocalVarDef) e);
}
if (e instanceof Modifiers)
visit((Modifiers) e);
if (e instanceof ModuleDef)
visit((ModuleDef) e);
if (e instanceof NameDef) {
nameDefsMustNotBeNamedAfterJassNativeTypes((NameDef) e);
checkConfigOverride((NameDef) e);
}
if (e instanceof NameRef) {
checkImplicitParameter((NameRef) e);
checkNameRef((NameRef) e);
}
if (e instanceof StmtCall)
checkCall((StmtCall) e);
if (e instanceof ExprDestroy)
visit((ExprDestroy) e);
if (e instanceof StmtForRange)
checkForRange((StmtForRange) e);
if (e instanceof StmtIf)
visit((StmtIf) e);
if (e instanceof StmtReturn)
visit((StmtReturn) e);
if (e instanceof StmtSet)
checkStmtSet((StmtSet) e);
if (e instanceof StmtWhile)
visit((StmtWhile) e);
if (e instanceof SwitchStmt)
checkSwitch((SwitchStmt) e);
if (e instanceof TypeExpr)
checkTypeExpr((TypeExpr) e);
if (e instanceof TypeExprArray)
checkCodeArrays((TypeExprArray) e);
if (e instanceof TupleDef)
checkTupleDef((TupleDef) e);
if (e instanceof VarDef)
checkVarDef((VarDef) e);
if (e instanceof WImport)
visit((WImport) e);
if (e instanceof WPackage)
checkPackage((WPackage) e);
if (e instanceof WParameter) {
checkParameter((WParameter) e);
visit((WParameter) e);
}
if (e instanceof WScope)
checkForDuplicateNames((WScope) e);
if (isHeavy() && e instanceof WStatement)
checkReachability((WStatement) e);
if (e instanceof WurstModel)
checkForDuplicatePackages((WurstModel) e);
if (e instanceof WStatements) {
checkForInvalidStmts((WStatements) e);
checkForEmptyBlocks((WStatements) e);
}
if (e instanceof StmtExitwhen)
visit((StmtExitwhen) e);
if (e instanceof StmtContinue)
visit((StmtContinue) e);
} catch (CyclicDependencyError cde) {
cde.printStackTrace();
Element element = cde.getElement();
String attr = cde.getAttributeName().replaceFirst("^attr", "");
WLogger.info(Utils.printElementWithSource(Optional.of(element))
+ " depends on itself when evaluating attribute "
+ attr);
WLogger.info(cde);
throw new CompileError(element.attrSource(),
Utils.printElement(element) + " depends on itself when evaluating attribute " + attr);
}
}
private void checkAbstractMethods(ClassDef c) {
ImmutableMultimap<String, DefLink> nameLinks = c.attrNameLinks();
if (!c.attrIsAbstract()) {
StringBuilder toImplement = new StringBuilder();
// should have no abstract methods
for (DefLink link : nameLinks.values()) {
NameDef f = link.getDef();
if (f.attrIsAbstract()) {
if (f.attrNearestStructureDef() == c) {
Element loc = f;
for (Modifier m : f.getModifiers()) {
if (m instanceof ModAbstract) {
Element x = m;
loc = x;
break;
}
}
loc.addError("Non-abstract class " + c.getName() + " cannot have abstract functions like " + f.getName());
} else if (link instanceof FuncLink) {
FuncLink abstractLink = (FuncLink) link;
if (!hasImplementationInHierarchy(c, abstractLink)) {
toImplement.append("\n ");
toImplement.append(abstractLink.printFunctionTemplate());
}
}
}
}
if (toImplement.length() > 0) {
c.addError("Non-abstract class " + c.getName() + " must implement the following functions:" + toImplement);
}
}
}
private boolean hasImplementationInHierarchy(ClassDef c, FuncLink abstractFunc) {
return findImplementationLink(c, abstractFunc) != null;
}
private @Nullable FuncLink findImplementationLink(ClassDef c, FuncLink abstractFunc) {
FuncLink best = null;
int bestDistance = Integer.MAX_VALUE;
for (NameLink nameLink : c.attrNameLinks().get(abstractFunc.getName())) {
if (!(nameLink instanceof FuncLink)) {
continue;
}
FuncLink candidate = (FuncLink) nameLink;
if (!WurstValidator.canOverride(candidate, abstractFunc, false)) {
continue;
}
FunctionDefinition candidateDef = candidate.getDef();
if (!(candidateDef instanceof FuncDef)) {
continue;
}
if (candidateDef.attrIsAbstract()) {
continue;
}
ClassDef owner = candidateDef.attrNearestClassDef();
if (owner == null) {
continue;
}
int distance = distanceToOwner(c, owner);
if (distance == Integer.MAX_VALUE) {
continue;
}
if (best == null || distance < bestDistance) {
best = candidate;
bestDistance = distance;
}
}
return best;
}
private int distanceToOwner(ClassDef start, ClassDef owner) {
int distance = 0;
ClassDef current = start;
Set<ClassDef> visited = new HashSet<>();
while (current != null && visited.add(current)) {
if (current == owner) {
return distance;
}
WurstTypeClass currentType = current.attrTypC();
if (currentType == null) {
break;
}
WurstTypeClass superType = currentType.extendedClass();
if (superType == null) {
break;
}
current = superType.getClassDef();
distance++;
}
return Integer.MAX_VALUE;
}
private void visit(StmtExitwhen exitwhen) {
Element parent = exitwhen.getParent();
while (parent != null && !(parent instanceof FunctionDefinition)) {
if (parent instanceof StmtForEach) {
StmtForEach forEach = (StmtForEach) parent;
if (forEach.getIn().tryGetNameDef().attrIsVararg()) {
exitwhen.addError("Cannot use break in vararg for each loops.");
}
return;
} else if (parent instanceof LoopStatement) {
return;
}
parent = parent.getParent();
}
exitwhen.addError("Break is not allowed outside of loop statements.");
}
private void visit(StmtContinue stmtContinue) {
Element parent = stmtContinue.getParent();
while (parent != null && !(parent instanceof FunctionDefinition)) {
if (parent instanceof StmtForEach) {
StmtForEach forEach = (StmtForEach) parent;
if (forEach.getIn().tryGetNameDef().attrIsVararg()) {
stmtContinue.addError("Cannot use continue in vararg for each loops.");
}
return;
} else if (parent instanceof LoopStatement) {
return;
}
parent = parent.getParent();
}
stmtContinue.addError("Continue statements must be used inside a loop.");
}
private void checkTupleDef(TupleDef e) {
checkTupleDefCycle(e, new ArrayList<>());
}
private boolean checkTupleDefCycle(TupleDef e, ArrayList<TupleDef> tuples) {
if (tuples.contains(e)) {
return true;
}
tuples.add(e);
try {
for (WParameter param : e.getParameters()) {
WurstType t = param.getTyp().attrTyp();
if (t instanceof WurstTypeTuple) {
WurstTypeTuple tt = (WurstTypeTuple) t;
TupleDef tDef = tt.getTupleDef();
if (checkTupleDefCycle(tDef, tuples)) {
param.addError("Parameter " + param.getName() + " is recursive. This is not allowed for tuples.");
return true;
}
}
}
return false;
} finally {
tuples.remove(e);
}
}
private void checkForInvalidStmts(WStatements stmts) {
for (WStatement s : stmts) {
if (s instanceof ExprVarAccess) {
ExprVarAccess ev = (ExprVarAccess) s;
s.addError("Use of variable " + ev.getVarName() + " is an incomplete statement.");
}
}
}
private void checkForEmptyBlocks(WStatements e) {
Element parent = e.getParent();
// some parent cases to ignore:
if (parent instanceof OnDestroyDef
|| parent instanceof ConstructorDef
|| parent instanceof FunctionDefinition
|| parent instanceof SwitchDefaultCaseStatements
|| parent instanceof SwitchCase) {
return;
}
if (parent instanceof ExprStatementsBlock) {
// for blocks in closures, we have StartFunction and EndFunction statements, so must be > 2 to be nonempty
if (e.size() > 2) {
return;
}
parent.getParent().addWarning("This function has an empty body. Write 'skip' if you intend to leave it empty.");
return;
}
if (!e.isEmpty()) {
return;
}
if (Utils.isJassCode(parent)) {
// no warnings in Jass code
return;
}
if (parent instanceof StmtIf) {
StmtIf stmtIf = (StmtIf) parent;
if (e == stmtIf.getElseBlock() && stmtIf.getHasElse()) {
parent.addWarning("This if-statement has an empty else-block.");
} else if (e == stmtIf.getThenBlock()) {
parent.addWarning("This if-statement has an empty then-block. Write 'skip' if you intend to leave it empty.");
}
return;
}
parent.addWarning("This statement (" + Utils.printElement(parent) + ") contains an empty block. Write 'skip' if you intend to leave it empty.");
}
private void checkName(AstElementWithNameId e) {
String name = e.getNameId().getName();
TypeDef def = e.lookupType(name, false);
if (def != e && def instanceof NativeType) {
e.addError(
"The name '" + name + "' is already used as a native type in " + Utils.printPos(def.getSource()));
} else if (!e.attrSource().getFile().endsWith(".j")) {
switch (name) {
case "int":
case "integer":
case "real":
case "code":
case "boolean":
case "string":
case "handle":
e.addError("The name '" + name + "' is a built-in type and cannot be used here.");
}
}
}
private void checkConfigOverride(NameDef e) {
if (!e.hasAnnotation("@config")) {
return;
}
PackageOrGlobal nearestPackage = e.attrNearestPackage();
if (!(nearestPackage instanceof WPackage)) {
e.addError("Annotation @config can only be used in packages.");
return;
}
WPackage configPackage = (WPackage) nearestPackage;
if (!configPackage.getName().endsWith(CofigOverridePackages.CONFIG_POSTFIX)) {
e.addError(
"Annotation @config can only be used in config packages (package name has to end with '_config').");
return;
}
WPackage origPackage = CofigOverridePackages.getOriginalPackage(configPackage);
if (origPackage == null) {
return;
}
if (e instanceof GlobalVarDef) {
GlobalVarDef v = (GlobalVarDef) e;
NameLink origVar = origPackage.getElements().lookupVarNoConfig(v.getName(), false);
if (origVar == null) {
e.addError("Could not find var " + v.getName() + " in configured package.");
return;
}
if (!v.attrTyp().equalsType(origVar.getTyp(), v)) {
e.addError("Configured variable must have type " + origVar.getTyp() + " but the found type is "
+ v.attrTyp() + ".");
return;
}
if (!origVar.getDef().hasAnnotation("@configurable")) {
e.addWarning("The configured variable " + v.getName() + " is not marked with @configurable.\n"
+ "It is still possible to configure this var but it is not recommended.");
}
} else if (e instanceof FuncDef) {
FuncDef funcDef = (FuncDef) e;
Collection<FuncLink> funcs = origPackage.getElements().lookupFuncsNoConfig(funcDef.getName(), false);
FuncDef configuredFunc = null;
for (NameLink nameLink : funcs) {
if (nameLink.getDef() instanceof FuncDef) {
FuncDef f = (FuncDef) nameLink.getDef();
if (equalSignatures(funcDef, f)) {
configuredFunc = f;
break;
}
}
}
if (configuredFunc == null) {
funcDef.addError("Could not find a function " + funcDef.getName()
+ " with the same signature in the configured package.");
} else {
if (!configuredFunc.hasAnnotation("@configurable")) {
e.addWarning("The configured function " + funcDef.getName() + " is not marked with @configurable.\n"
+ "It is still possible to configure this function but it is not recommended.");
}
}
} else {
e.addError("Configuring " + Utils.printElement(e) + " is not supported by Wurst.");
}
}
private boolean equalSignatures(FuncDef f, FuncDef g) {
if (f.getParameters().size() != g.getParameters().size()) {
return false;
}
if (!f.attrReturnTyp().equalsType(g.attrReturnTyp(), f)) {
return false;
}
for (int i = 0; i < f.getParameters().size(); i++) {
if (!f.getParameters().get(i).attrTyp().equalsType(g.getParameters().get(i).attrTyp(), f)) {
return false;
}
}
return true;
}
private void checkExprEmpty(ExprEmpty e) {
e.addError("Incomplete expression...");
}
private void checkMemberArrayVar(ExprMemberArrayVar e) {
// TODO Auto-generated method stub
}
private void checkNameRef(NameRef e) {
if (e.getVarName().isEmpty()) {
e.addError("Missing variable name.");
}
}
private void checkPackage(WPackage p) {
checkForDuplicateImports(p);
p.attrInitDependencies();
}
private void checkTypeExpr(TypeExpr e) {
if (e instanceof TypeExprResolved) {
return;
}
if (e.isModuleUseTypeArg()) {
return;
}
TypeDef typeDef = e.attrTypeDef();
// check that modules are not used as normal types
if (e.attrTypeDef() instanceof ModuleDef) {
ModuleDef md = (ModuleDef) e.attrTypeDef();
checkModuleTypeUsedCorrectly(e, md);
}
if (typeDef instanceof TypeParamDef) { // references a type parameter
TypeParamDef tp = (TypeParamDef) typeDef;
checkTypeparamsUsedCorrectly(e, tp);
}
// Cross-flavor generics ban inside generic declarations:
checkGenericFlavorCompatibility(e);
}
// --- Generic flavor detection ----------------------------------------------
private enum GenericFlavor { NEW, LEGACY }
/** Returns NEW if all TPs are new style (colon), LEGACY if any exist and none are colon, else null (non-generic). */
private @Nullable GenericFlavor flavorOf(AstElementWithTypeParameters owner) {
TypeParamDefs tps = owner.getTypeParameters();
if (tps == null || tps.size() == 0) return null;
boolean anyNew = false, anyOld = false;
for (TypeParamDef tp : owner.getTypeParameters()) {
if (isTypeParamNewGeneric(tp)) anyNew = true; else anyOld = true;
if (anyNew && anyOld) {
tp.addError("Mixed generic syntax in one declaration is not allowed. Use either <T:> or <T> consistently.");
// Pick a flavor to avoid cascaded errors:
return GenericFlavor.NEW;
}
}
if (anyNew) return GenericFlavor.NEW;
if (anyOld) return GenericFlavor.LEGACY;
return null;
}
/** Returns the flavor of the referenced generic definition, or null if the target is non-generic. */
private @Nullable GenericFlavor flavorOf(TypeDef def) {
if (def instanceof AstElementWithTypeParameters) {
return flavorOf((AstElementWithTypeParameters) def);
}
return null;
}
/** Walk up to the nearest *structure* (ClassDef/InterfaceDef) which actually has type parameters. */
private @Nullable AstElementWithTypeParameters nearestGenericStructureOwner(Element e) {
Element p = e;
while (p != null) {
if (p instanceof ClassDef || p instanceof InterfaceDef) {
AstElementWithTypeParameters a = (AstElementWithTypeParameters) p;
if (a.getTypeParameters() != null && a.getTypeParameters().size() > 0) {
return a;
}
// keep walking if the structure itself has no TPs
}
// IMPORTANT: skip function owners entirely — method generics are allowed to mix.
if (p instanceof FuncDef) {
return null;
}
p = p.getParent();
}
return null;
}
/** For type usages inside ANY generic declaration (class/interface/function),
* ban cross-flavor references (NEW cannot use LEGACY and vice versa). */
private void checkGenericFlavorCompatibility(TypeExpr e) {
// Enforce inside the nearest generic owner: class, interface, or function
AstElementWithTypeParameters owner = nearestGenericOwner(e);
if (owner == null) return;
@Nullable GenericFlavor ownerFlavor = flavorOf(owner);
if (ownerFlavor == null) return; // owner not actually generic
// What type is being referenced?
TypeDef targetDef = e.attrTypeDef();
if (targetDef == null) return;
// Only care when the referenced definition itself is generic
@Nullable GenericFlavor targetFlavor = flavorOf(targetDef);
if (targetFlavor == null) return; // non-generic target → allowed
if (ownerFlavor != targetFlavor) {
String targetKind =
(targetDef instanceof ClassDef) ? "class" :
(targetDef instanceof InterfaceDef) ? "interface" : "type";
String targetName = targetDef.getName();
if (ownerFlavor == GenericFlavor.NEW) {
// owner is <T:> and target is legacy
e.addError("Cannot reference legacy-generic " + targetKind + " '" + targetName
+ "<T>' from a new-generic declaration. Migrate '" + targetName
+ "<T>' to '" + targetName + "<T:>' or convert this declaration to legacy generics.");
} else {
// owner is legacy <T> and target is new
e.addError("Cannot reference new-generic " + targetKind + " '" + targetName
+ "<T:>' from a legacy-generic declaration. Use legacy syntax here or migrate this declaration to new generics.");
}
}
}
/** Walk up and find the *nearest* generic declaration owning the current node (class/interface/func). */
private @Nullable AstElementWithTypeParameters nearestGenericOwner(Element e) {
Element p = e;
while (p != null) {
if (p instanceof FuncDef || p instanceof ClassDef || p instanceof InterfaceDef) {
AstElementWithTypeParameters a = (AstElementWithTypeParameters) p;
if (a.getTypeParameters() != null && a.getTypeParameters().size() > 0) {
return a;
}
}
p = p.getParent();
}
return null;
}
/**
* Checks that module types are only used in valid places
*/
private void checkModuleTypeUsedCorrectly(TypeExpr e, ModuleDef md) {
if (e instanceof TypeExprThis) {
// thistype is allowed, because it is translated to a real type when used
return;
}
if (e.getParent() instanceof TypeExprThis) {
TypeExprThis parent = (TypeExprThis) e.getParent();
if (parent.getScopeType() == e) {
// ModuleName.thistype is allowed
// TODO (maybe check here that it is a parent)
return;
}
}
if (e instanceof TypeExprSimple) {
TypeExprSimple tes = (TypeExprSimple) e;
if (tes.getScopeType() instanceof TypeExpr) {
TypeExpr scopeType = (TypeExpr) tes.getScopeType();
if (scopeType instanceof TypeExprThis
|| scopeType.attrTypeDef() instanceof ModuleDef) {
// thistype.A etc. is allowed
return;
}
}