-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathModelManagerImpl.java
More file actions
827 lines (722 loc) · 28.9 KB
/
ModelManagerImpl.java
File metadata and controls
827 lines (722 loc) · 28.9 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
package de.peeeq.wurstio.languageserver;
import com.google.common.base.Charsets;
import com.google.common.collect.*;
import com.google.common.io.Files;
import de.peeeq.wurstio.ModelChangedException;
import de.peeeq.wurstio.WurstCompilerJassImpl;
import de.peeeq.wurstio.utils.FileUtils;
import de.peeeq.wurstscript.RunArgs;
import de.peeeq.wurstscript.WLogger;
import de.peeeq.wurstscript.ast.*;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.gui.WurstGui;
import de.peeeq.wurstscript.gui.WurstGuiLogger;
import de.peeeq.wurstscript.utils.Utils;
import de.peeeq.wurstscript.validation.GlobalCaches;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* keeps a version of the model which is always the most recent one
*/
public class ModelManagerImpl implements ModelManager {
private final BufferManager bufferManager;
private volatile @Nullable WurstModel model;
private final File projectPath;
// dependency folders (folders mentioned in wurst.dependencies)
private final Set<File> dependencies = Sets.newLinkedHashSet();
// private WurstGui gui = new WurstGuiLogger();
private final List<Consumer<PublishDiagnosticsParams>> onCompilationResultListeners = new ArrayList<>();
// compile errors for each file
private final Map<WFile, List<CompileError>> parseErrors = new LinkedHashMap<>();
// other errors for each file
private final Map<WFile, List<CompileError>> otherErrors = new LinkedHashMap<>();
// hashcode for each compilation unit content as string
private final Map<WFile, Integer> fileHashcodes = new HashMap<>();
// file for each compilation unit
private final WeakHashMap<CompilationUnit, WFile> compilationunitFile = new WeakHashMap<>();
public ModelManagerImpl(File projectPath, BufferManager bufferManager) {
this.projectPath = projectPath;
this.bufferManager = bufferManager;
}
private WurstModel newModel(CompilationUnit cu, WurstGui gui) {
try {
CompilationUnit commonJ = compileFromJar(gui, "common.j");
CompilationUnit blizzardJ = compileFromJar(gui, "blizzard.j");
return Ast.WurstModel(blizzardJ, commonJ, cu);
} catch (IOException e) {
WLogger.severe(e);
return Ast.WurstModel(cu);
}
}
private List<CompilationUnit> getJassdocCUs(Path jassdoc, WurstGui gui) {
ArrayList<CompilationUnit> units = new ArrayList<>();
WurstCompilerJassImpl comp = new WurstCompilerJassImpl(projectPath, gui, null, RunArgs.defaults());
for (File f : jassdoc.toFile().listFiles()) {
if (f.getName().endsWith(".j") && ! f.getName().startsWith("builtin-types")) {
try (InputStreamReader reader = new FileReader(f)) {
CompilationUnit cu = comp.parse(f.getAbsolutePath(), reader);
cu.getCuInfo().setFile(getCanonicalPath(f));
units.add(cu);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return units;
}
@Override
public Changes removeCompilationUnit(WFile resource) {
WurstModel model2 = model;
List<CompilationUnit> toRemove = new ArrayList<>();
if (model2 != null) {
for (CompilationUnit compilationUnit : model2) {
if (wFile(compilationUnit).equals(resource)) {
toRemove.add(compilationUnit);
}
}
model2.removeAll(toRemove);
}
// Always clear state and diagnostics for removed files.
clearFileState(resource);
reportErrors("remove cu ", resource, Collections.emptyList());
toRemove.forEach(compilationunitFile::remove);
return new Changes(
java.util.Collections.singletonList(resource),
toRemove.stream()
.flatMap(cu -> cu.getPackages().stream())
.map(WPackage::getName)
.collect(Collectors.toList())
);
}
@Override
public void clean() {
fileHashcodes.clear();
parseErrors.clear();
model = null;
dependencies.clear();
WLogger.info("Clean done.");
}
/**
* does a full build, reading whole directory
*/
@Override
public void buildProject() {
try {
WurstGui gui = new WurstGuiLogger();
readDependencies(gui);
if (!projectPath.exists()) {
throw new RuntimeException("Folder " + projectPath + " does not exist!");
}
File wurstFolder = new File(projectPath, "wurst");
if (!wurstFolder.exists()) {
System.err.println("No wurst folder found, using complete directory instead.");
wurstFolder = projectPath;
}
processWurstFiles(wurstFolder);
resolveImports(gui);
doTypeCheck(gui);
} catch (IOException e) {
WLogger.severe(e);
throw new ModelManagerException(e);
}
}
private void processWurstFiles(File dir) {
for (File f : getFiles(dir)) {
if (f.isDirectory()) {
processWurstFiles(f);
} else if (f.getName().endsWith(".wurst") || f.getName().endsWith(".jurst") || f.getName().endsWith(".j")) {
processWurstFile(WFile.create(f));
}
}
}
private File[] getFiles(File dir) {
File[] res = dir.listFiles();
if (res == null) {
return new File[0];
}
return res;
}
private void processWurstFile(WFile f) {
WLogger.debug("processing file " + f);
replaceCompilationUnit(f);
}
private void readDependencies(WurstGui gui) throws IOException {
dependencies.clear();
File depFile = new File(projectPath, "wurst.dependencies");
if (!depFile.exists()) {
WLogger.info("no dependency file found.");
return;
}
dependencies.addAll(WurstCompilerJassImpl.checkDependencyFile(depFile, gui));
WurstCompilerJassImpl.addDependenciesFromFolder(projectPath, dependencies);
}
private String getCanonicalPath(File f) {
try {
return f.getCanonicalPath();
} catch (IOException e) {
WLogger.info(e);
// fall back to absolute path
return f.getAbsolutePath();
}
}
private List<CompilationUnit> getCompilationUnits(List<WFile> fileNames) {
WurstModel model2 = model;
if (model2 == null) {
return Collections.emptyList();
}
List<CompilationUnit> list = new ArrayList<>();
for (CompilationUnit cu : model2) {
if (fileNames.contains(wFile(cu))) {
list.add(cu);
}
}
return list;
}
private List<WFile> getfileNames(Collection<CompilationUnit> compilationUnits) {
List<WFile> list = new ArrayList<>();
for (CompilationUnit compilationUnit : compilationUnits) {
WFile wFile = wFile(compilationUnit);
list.add(wFile);
}
return list;
}
/**
* clear the attributes and module instantiations for all compilation units in the given collection
*/
private void clearCompilationUnits(Collection<CompilationUnit> toCheck) {
WurstModel model2 = model;
if (model2 == null) {
return;
}
model2.clearAttributesLocal();
for (CompilationUnit cu : toCheck) {
clearCompilationUnit(cu);
}
}
private void clearCompilationUnit(CompilationUnit cu) {
cu.clearAttributes();
// clear module instantiations
for (WPackage p : cu.getPackages()) {
for (WEntity elem : p.getElements()) {
if (elem instanceof ClassOrModuleInstanciation) {
clearModuleInstantiation(((ClassOrModuleInstanciation) elem));
}
}
}
}
private void clearModuleInstantiation(ClassOrModuleInstanciation elem) {
elem.getP_moduleInstanciations().clear();
for (ClassDef innerClass : elem.getInnerClasses()) {
clearModuleInstantiation(innerClass);
}
}
/**
* check whether cu imports something from 'toCheck'
*/
private boolean imports(CompilationUnit cu, Set<String> packageNames) {
for (WPackage p : cu.getPackages()) {
if (imports(p, packageNames, false, Sets.newHashSet())) {
return true;
}
}
return false;
}
/**
* check whether p imports something from 'toCheck'
*/
private boolean imports(WPackage p, Set<String> packageNames, boolean onlyPublic, HashSet<WPackage> visited) {
if (visited.contains(p)) {
return false;
}
visited.add(p);
for (WImport imp : p.getImports()) {
if ((!onlyPublic || imp.getIsPublic()) && packageNames.contains(imp.getPackagename())) {
return true;
} else {
WPackage importedPackage = imp.attrImportedPackage();
if ((!onlyPublic || imp.getIsPublic())
&& importedPackage != null
&& imports(importedPackage, packageNames, true, visited)) {
return true;
}
}
}
return false;
}
private void doTypeCheck(WurstGui gui) {
WurstCompilerJassImpl comp = getCompiler(gui);
long time = System.currentTimeMillis();
if (gui.getErrorCount() > 0) {
reportErrorsForProject("build project, doTypecheck, early", gui);
WLogger.info("finished typechecking* in " + (System.currentTimeMillis() - time) + "ms");
return;
}
@Nullable
WurstModel model2 = model;
if (model2 == null) {
return;
}
try {
model2.clearAttributes();
comp.addImportedLibs(model2, this::addCompilationUnit);
comp.checkProg(model2);
} catch (CompileError e) {
gui.sendError(e);
}
WLogger.info("finished typechecking in " + (System.currentTimeMillis() - time) + "ms");
reportErrorsForProject("build project, doTypecheck, end", gui);
}
private CompilationUnit addCompilationUnit(File file) {
WFile wFile = WFile.create(file);
try {
String contents = new String(java.nio.file.Files.readAllBytes(file.toPath()), UTF_8);
return replaceCompilationUnit(wFile, contents, true);
} catch (IOException e) {
WLogger.severe(e);
return null;
}
}
private void reportErrorsForProject(String extra, WurstGui gui) {
Multimap<WFile, CompileError> typeErrors = ArrayListMultimap.create();
for (CompileError e : gui.getErrorsAndWarnings()) {
typeErrors.put(WFile.create(e.getSource().getFile()), e);
}
Set<WFile> files = ImmutableSet.<WFile>builder()
.addAll(parseErrors.keySet())
.addAll(typeErrors.keySet())
.build();
for (WFile file : files) {
List<CompileError> errors = ImmutableList.<CompileError>builder()
.addAll(parseErrors.getOrDefault(file, Collections.emptyList()))
.addAll(typeErrors.get(file))
.build();
reportErrors(extra, file, errors);
}
}
private void reportErrorsForFiles(List<WFile> filenames, WurstGui gui) {
Multimap<WFile, CompileError> typeErrors = ArrayListMultimap.create();
for (CompileError e : gui.getErrorsAndWarnings()) {
typeErrors.put(WFile.create(e.getSource().getFile()), e);
}
for (WFile file : filenames) {
List<CompileError> errors = new ArrayList<>(parseErrors.getOrDefault(file, Collections.emptyList()));
errors.addAll(typeErrors.get(file));
reportErrors("partial ", file, errors);
}
}
private void reportErrors(String extra, WFile filename, List<CompileError> errors) {
PublishDiagnosticsParams cr = Convert.createDiagnostics(extra, filename, errors);
otherErrors.put(filename, ImmutableList.copyOf(errors));
for (Consumer<PublishDiagnosticsParams> consumer : onCompilationResultListeners) {
consumer.accept(cr);
}
}
private WurstCompilerJassImpl getCompiler(WurstGui gui) {
RunArgs runArgs = RunArgs.defaults();
runArgs.addLibDirs(dependencies);
WurstCompilerJassImpl comp = new WurstCompilerJassImpl(projectPath, gui, null, runArgs);
comp.setHasCommonJ(true);
return comp;
}
private void updateModel(CompilationUnit cu, WurstGui gui) {
parseErrors.put(wFile(cu), new ArrayList<>(gui.getErrorsAndWarnings()));
WurstModel model2 = model;
if (model2 == null) {
model = newModel(cu, gui);
} else {
ListIterator<CompilationUnit> it = model2.listIterator();
boolean updated = false;
while (it.hasNext()) {
CompilationUnit c = it.next();
if (wFile(c).equals(wFile(cu))) {
// get old provided packages:
Set<String> oldPackages = providedPackages(c);
Set<CompilationUnit> mustUpdate = calculateCUsToUpdate(Collections.singletonList(cu), oldPackages, model2);
clearCompilationUnits(mustUpdate);
// replace old compilationunit with new one:
it.set(cu);
updated = true;
break;
}
}
if (!updated) {
model2.add(cu);
}
}
//doTypeCheckPartial(gui, false, ImmutableList.of(cu.getFile()));
}
private Set<String> providedPackages(CompilationUnit c) {
Set<String> set = new HashSet<>();
for (WPackage wPackage : c.getPackages()) {
String name = wPackage.getName();
set.add(name);
}
return set;
}
private CompilationUnit compileFromJar(WurstGui gui, String filename) throws IOException {
InputStream source = this.getClass().getResourceAsStream("/" + filename);
File sourceFile;
if (source == null) {
WLogger.severe("could not find " + filename + " in jar");
System.err.println("could not find " + filename + " in jar");
sourceFile = new File("./resources/" + filename);
} else {
try {
File buildDir = getBuildDir();
//noinspection ResultOfMethodCallIgnored
buildDir.mkdirs();
sourceFile = new File(buildDir, filename);
if (!sourceFile.exists()) {
java.nio.file.Files.copy(source, sourceFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} finally {
source.close();
}
}
WurstCompilerJassImpl comp = getCompiler(gui);
try (InputStreamReader reader = new FileReader(sourceFile)) {
CompilationUnit cu = comp.parse(sourceFile.getAbsolutePath(), reader);
cu.getCuInfo().setFile(getCanonicalPath(sourceFile));
return cu;
}
}
private File getBuildDir() {
return new File(projectPath, "_build");
}
private void resolveImports(WurstGui gui) {
WurstCompilerJassImpl comp = getCompiler(gui);
try {
WurstModel m = model;
if (m == null) {
return;
}
m.clearAttributes();
comp.addImportedLibs(m, this::addCompilationUnit);
} catch (CompileError e) {
gui.sendError(e);
}
}
private void replaceCompilationUnit(WFile filename) {
File f;
try {
f = filename.getFile();
} catch (FileNotFoundException e) {
WLogger.info("Cannot replaceCompilationUnit for " + filename + "\n" + e);
return;
}
if (!f.exists()) {
removeCompilationUnit(filename);
return;
}
try {
String contents = Files.toString(f, Charsets.UTF_8);
bufferManager.updateFile(WFile.create(f), contents);
replaceCompilationUnit(filename, contents, true);
} catch (IOException e) {
WLogger.severe(e);
throw new ModelManagerException(e);
}
}
@Override
public Changes syncCompilationUnitContent(WFile filename, String contents) {
WLogger.info("sync contents for " + filename);
Set<String> oldPackages = declaredPackages(filename);
replaceCompilationUnit(filename, contents, false);
return new Changes(io.vavr.collection.HashSet.of(filename), oldPackages);
}
private Set<String> declaredPackages(WFile f) {
WurstModel model = this.model;
if (model == null) {
return Collections.emptySet();
}
for (CompilationUnit cu : model) {
if (wFile(cu).equals(f)) {
Set<String> set = new HashSet<>();
for (WPackage wPackage : cu.getPackages()) {
String name = wPackage.getName();
set.add(name);
}
return set;
}
}
return Collections.emptySet();
}
@Override
public CompilationUnit replaceCompilationUnitContent(WFile filename, String contents, boolean reportErrors) {
return replaceCompilationUnit(filename, contents, reportErrors);
}
@Override
public Changes syncCompilationUnit(WFile f) {
WLogger.info("syncCompilationUnit File " + f);
Set<String> oldPackages = declaredPackages(f);
replaceCompilationUnit(f);
WLogger.info("replaced file " + f);
WurstGui gui = new WurstGuiLogger();
doTypeCheckPartial(gui, ImmutableList.of(f), oldPackages);
return new Changes(io.vavr.collection.HashSet.of(f), oldPackages);
}
private CompilationUnit replaceCompilationUnit(WFile filename, String contents, boolean reportErrors) {
if (!isInWurstFolder(filename)) {
return null;
}
if (fileHashcodes.containsKey(filename)) {
int oldHash = fileHashcodes.get(filename);
if (oldHash == contents.hashCode()) {
CompilationUnit existing = getCompilationUnit(filename);
if (existing != null) {
// no change
WLogger.trace(() -> "CU " + filename + " was unchanged.");
return existing;
}
// Stale hash cache after remove/move; CU is gone, so reparse.
WLogger.info("CU hash unchanged but model entry missing for " + filename + ", reparsing.");
} else {
WLogger.info("CU changed. oldHash = " + oldHash + " == " + contents.hashCode());
}
}
WLogger.trace(() -> "replace CU " + filename);
WurstGui gui = new WurstGuiLogger();
WurstCompilerJassImpl c = getCompiler(gui);
CompilationUnit cu = c.parse(filename.toString(), new StringReader(contents));
cu.getCuInfo().setFile(filename.toString());
updateModel(cu, gui);
fileHashcodes.put(filename, contents.hashCode());
if (reportErrors) {
if (gui.getErrorCount() > 0) {
WLogger.info("found " + gui.getErrorCount() + " errors in file " + filename);
}
ImmutableList.Builder<CompileError> errors = ImmutableList.<CompileError>builder()
.addAll(gui.getErrorsAndWarnings());
if (otherErrors.containsKey(filename)) {
errors.addAll(otherErrors.get(filename));
}
reportErrors("sync cu " + filename, filename, errors.build());
}
return cu;
}
private void clearFileState(WFile file) {
parseErrors.remove(file);
otherErrors.remove(file);
fileHashcodes.remove(file);
}
@Override
public CompilationUnit getCompilationUnit(WFile filename) {
List<CompilationUnit> matches = getCompilationUnits(Collections.singletonList(filename));
if (matches.isEmpty()) {
WLogger.info("compilation unit not found: " + filename);
return null;
}
return matches.get(0);
}
@Override
public WurstModel getModel() {
return model;
}
@Override
public boolean hasErrors() {
return errorStream().findAny().isPresent();
}
@Override
public String getFirstErrorDescription() {
Optional<CompileError> first = errorStream().findFirst();
return first.map(CompileError::toString).orElse("no errors");
}
@Override
public List<CompileError> getParseErrors() {
return parseErrorStream().collect(Collectors.toList());
}
private Stream<CompileError> parseErrorStream() {
return parseErrors.values().stream()
.flatMap(Collection::stream)
.filter(err -> err.getErrorType() == CompileError.ErrorType.ERROR);
}
private Stream<CompileError> otherErrorStream() {
return otherErrors.values().stream()
.flatMap(Collection::stream)
.filter(err -> err.getErrorType() == CompileError.ErrorType.ERROR);
}
private Stream<CompileError> errorStream() {
return Streams.concat(parseErrorStream(), otherErrorStream());
}
@Override
public void onCompilationResult(Consumer<PublishDiagnosticsParams> f) {
onCompilationResultListeners.add(f);
}
private void doTypeCheckPartial(WurstGui gui, List<WFile> toCheckFilenames, Set<String> oldPackages) {
WLogger.info("do typecheck partial of " + toCheckFilenames);
WurstCompilerJassImpl comp = getCompiler(gui);
List<CompilationUnit> toCheck = getCompilationUnits(toCheckFilenames);
WurstModel model2 = model;
if (model2 == null) {
return;
}
Collection<CompilationUnit> toCheckRec = calculateCUsToUpdate(toCheck, oldPackages, model2);
partialTypecheck(model2, toCheckRec, gui, comp);
}
@Override
public void reconcile(Changes changes) {
WurstModel model2 = model;
if (model2 == null) {
return;
}
Collection<CompilationUnit> toCheck1 = new HashSet<>();
for (CompilationUnit cu : model2) {
if (changes.getAffectedFiles().contains(WFile.create(cu.getCuInfo().getFile()))) {
toCheck1.add(cu);
}
}
Set<String> oldPackageNames = changes.getAffectedPackageNames().toJavaSet();
Collection<CompilationUnit> toCheckRec = calculateCUsToUpdate(toCheck1, oldPackageNames, model2);
WurstGui gui = new WurstGuiLogger();
WurstCompilerJassImpl comp = getCompiler(gui);
partialTypecheck(model2, toCheckRec, gui, comp);
}
private void partialTypecheck(WurstModel model2, Collection<CompilationUnit> toCheckRec, WurstGui gui, WurstCompilerJassImpl comp) {
try {
clearCompilationUnits(toCheckRec);
comp.addImportedLibs(model2, this::addCompilationUnit);
comp.checkProg(model2, toCheckRec);
} catch (ModelChangedException e) {
// model changed, early return
return;
} catch (CompileError e) {
gui.sendError(e);
}
List<WFile> fileNames = getfileNames(toCheckRec);
reportErrorsForFiles(fileNames, gui);
}
/**
* Calculates compilation
*
*
* @param changed the set of compilation units that were changed
* @param oldPackages packages that were provided before the update (which might have been removed now)
* @param model the complete AST
* @return the set of compilation units that might be affected by the changes, including the changed compilation units
*/
private Set<CompilationUnit> calculateCUsToUpdate(Collection<CompilationUnit> changed, Set<String> oldPackages, WurstModel model) {
Set<CompilationUnit> result = new TreeSet<>(Comparator.comparing(cu -> cu.getCuInfo().getFile()));
result.addAll(changed);
boolean b = false;
for (CompilationUnit compilationUnit : changed) {
if (compilationUnit.getCuInfo().getFile().endsWith(".j")) {
b = true;
break;
}
}
if (b) {
// when plain Jass files are changed, everything must be checked again:
result.addAll(model);
return result;
}
// get packages provided by the changed CUs
Stream<String> providedPackages = changed.stream()
.flatMap(cu -> cu.getPackages().stream())
.map(WPackage::getName);
// affected packages are new ones and old ones
Set<String> affectedPackages = Stream.concat(providedPackages, oldPackages.stream())
.collect(Collectors.toSet());
addPossiblyAffectedPackages(affectedPackages, model, result);
return result;
}
/**
* Add all packages that directly or indirectly depend on the providedPackages
*/
private void addPossiblyAffectedPackages(Collection<String> providedPackages, WurstModel model, Set<CompilationUnit> result) {
nextCu:
for (CompilationUnit compilationUnit : model) {
if (result.contains(compilationUnit)) {
continue;
}
for (WPackage p : compilationUnit.getPackages()) {
for (WImport imp : p.getImports()) {
String importedPackage = imp.getPackagenameId().getName();
if (providedPackages.contains(importedPackage)) {
result.add(compilationUnit);
continue nextCu;
}
}
}
}
addTransitiveDeps(result, model);
}
/**
* Add all compilation units that transitively depend on the units in result
*/
private void addTransitiveDeps(Set<CompilationUnit> result, WurstModel model) {
Multimap<CompilationUnit, CompilationUnit> dependencyMap = calculateDirectDependencies(model);
ArrayDeque<CompilationUnit> todo = new ArrayDeque<>(result);
while (!todo.isEmpty()) {
CompilationUnit cu = todo.remove();
Collection<CompilationUnit> directDeps = dependencyMap.get(cu);
for (CompilationUnit c : directDeps) {
if (result.add(c)) {
todo.add(c);
}
}
}
}
/**
* Calculates a map from a compilation unit to the compilation units that directly depend on it.
* E.g. if package A imports C and package B imports C, then
* result.get(C) would return A and B
**/
private Multimap<CompilationUnit, CompilationUnit> calculateDirectDependencies(WurstModel model) {
Multimap<CompilationUnit, CompilationUnit> result = HashMultimap.create();
Map<String, CompilationUnit> cuForPackage = new HashMap<>();
for (CompilationUnit cu : model) {
for (WPackage p : cu.getPackages()) {
cuForPackage.put(p.getName(), cu);
}
}
for (CompilationUnit cu : model) {
for (WPackage p : cu.getPackages()) {
for (WImport i : p.getImports()) {
CompilationUnit dep = cuForPackage.get(i.getPackagename());
if (dep != null) {
result.put(dep, cu);
}
}
}
}
return result;
}
@Override
public synchronized Set<File> getDependencyWurstFiles() {
Set<File> result = Sets.newHashSet();
for (File dep : dependencies) {
addDependencyWurstFiles(result, dep);
}
return result;
}
private void addDependencyWurstFiles(Set<File> result, File file) {
if (file.isDirectory()) {
for (File child : getFiles(file)) {
addDependencyWurstFiles(result, child);
}
} else if (Utils.isWurstFile(file)) {
result.add(file);
}
}
private WFile wFile(CompilationUnit cu) {
return compilationunitFile.computeIfAbsent(cu, c -> WFile.create(cu.getCuInfo().getFile()));
}
/**
* checks if the given file is in the wurst folder or inside a dependency
*/
private boolean isInWurstFolder(WFile file) {
return Stream.concat(Stream.of(projectPath), dependencies.stream()).anyMatch(p ->
FileUtils.isInDirectoryTrans(file, WFile.create(new File(p, "wurst"))));
}
public File getProjectPath() {
return projectPath;
}
}