• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

wurstscript / WurstScript / 209

25 Oct 2023 11:42AM CUT coverage: 63.746% (-0.01%) from 63.756%
209

Pull #1081

circleci

Frotty
WIP
Pull Request #1081: More performance improvements

17267 of 27087 relevant lines covered (63.75%)

0.64 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/MapRequest.java
1
package de.peeeq.wurstio.languageserver.requests;
2

3
import com.google.common.base.Charsets;
4
import com.google.common.io.Files;
5
import config.WurstProjectConfigData;
6
import de.peeeq.wurstio.Pjass;
7
import de.peeeq.wurstio.TimeTaker;
8
import de.peeeq.wurstio.UtilsIO;
9
import de.peeeq.wurstio.WurstCompilerJassImpl;
10
import de.peeeq.wurstio.languageserver.ConfigProvider;
11
import de.peeeq.wurstio.languageserver.ModelManager;
12
import de.peeeq.wurstio.languageserver.ProjectConfigBuilder;
13
import de.peeeq.wurstio.languageserver.WFile;
14
import de.peeeq.wurstio.mpq.MpqEditor;
15
import de.peeeq.wurstio.mpq.MpqEditorFactory;
16
import de.peeeq.wurstio.utils.W3InstallationData;
17
import de.peeeq.wurstscript.RunArgs;
18
import de.peeeq.wurstscript.WLogger;
19
import de.peeeq.wurstscript.ast.CompilationUnit;
20
import de.peeeq.wurstscript.ast.WImport;
21
import de.peeeq.wurstscript.ast.WPackage;
22
import de.peeeq.wurstscript.ast.WurstModel;
23
import de.peeeq.wurstscript.attributes.CompileError;
24
import de.peeeq.wurstscript.gui.WurstGui;
25
import de.peeeq.wurstscript.jassAst.JassProg;
26
import de.peeeq.wurstscript.jassprinter.JassPrinter;
27
import de.peeeq.wurstscript.luaAst.LuaCompilationUnit;
28
import de.peeeq.wurstscript.parser.WPos;
29
import de.peeeq.wurstscript.utils.LineOffsets;
30
import de.peeeq.wurstscript.utils.Utils;
31
import net.moonlightflower.wc3libs.bin.app.W3I;
32
import net.moonlightflower.wc3libs.port.Orient;
33
import net.openhft.hashing.LongHashFunction;
34
import org.eclipse.lsp4j.MessageParams;
35
import org.eclipse.lsp4j.MessageType;
36
import org.eclipse.lsp4j.services.LanguageClient;
37
import org.jetbrains.annotations.Nullable;
38

39
import java.io.File;
40
import java.io.FileNotFoundException;
41
import java.io.IOException;
42
import java.nio.channels.NonWritableChannelException;
43
import java.nio.charset.StandardCharsets;
44
import java.nio.file.Path;
45
import java.nio.file.Paths;
46
import java.time.Duration;
47
import java.util.*;
48
import java.util.concurrent.CompletableFuture;
49
import java.util.concurrent.atomic.AtomicReference;
50
import java.util.stream.Collectors;
51

52
public abstract class MapRequest extends UserRequest<Object> {
53
    protected final ConfigProvider configProvider;
54
    protected final @Nullable
55
    Optional<File> map;
56
    protected final List<String> compileArgs;
57
    protected final WFile workspaceRoot;
58
    protected final RunArgs runArgs;
59
    protected final Optional<String> wc3Path;
60
    protected final W3InstallationData w3data;
61
    protected final TimeTaker timeTaker;
62

63
    /**
64
     * makes the compilation slower, but more safe by discarding results from the editor and working on a copy of the model
65
     */
66
    protected SafetyLevel safeCompilation = SafetyLevel.KindOfSafe;
×
67

68
    public TimeTaker getTimeTaker() {
69
        return timeTaker;
×
70
    }
71

72

73
    enum SafetyLevel {
×
74
        QuickAndDirty, KindOfSafe;
×
75
    }
76

77
    public static class CompilationResult {
×
78
        public File script;
79
        public File w3i;
80
    }
81

82
    public MapRequest(ConfigProvider configProvider, Optional<File> map, List<String> compileArgs, WFile workspaceRoot,
83
            Optional<String> wc3Path) {
×
84
        this.configProvider = configProvider;
×
85
        this.map = map;
×
86
        this.compileArgs = compileArgs;
×
87
        this.workspaceRoot = workspaceRoot;
×
88
        this.runArgs = new RunArgs(compileArgs);
×
89
        this.wc3Path = wc3Path;
×
90
        this.w3data = getBestW3InstallationData();
×
91
        if (runArgs.isMeasureTimes()) {
×
92
            this.timeTaker = new TimeTaker.Recording();
×
93
        } else {
94
            this.timeTaker = new TimeTaker.Default();
×
95
        }
96
    }
×
97

98
    @Override
99
    public void handleException(LanguageClient languageClient, Throwable err, CompletableFuture<Object> resFut) {
100
        if (err instanceof RequestFailedException) {
×
101
            RequestFailedException rfe = (RequestFailedException) err;
×
102
            languageClient.showMessage(new MessageParams(rfe.getMessageType(), rfe.getMessage()));
×
103
            resFut.complete(new Object());
×
104
        } else {
×
105
            super.handleException(languageClient, err, resFut);
×
106
        }
107
    }
×
108

109
    protected File compileMap(File projectFolder, WurstGui gui, Optional<File> mapCopy, RunArgs runArgs, WurstModel model,
110
                              WurstProjectConfigData projectConfigData, boolean isProd) {
111
        try (@Nullable MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy)) {
×
112
            if (mpqEditor != null && !mpqEditor.canWrite()) {
×
113
                WLogger.severe("The supplied map is invalid/corrupted/protected and Wurst cannot write to it.\n" +
×
114
                    "Please supply a valid .w3x input map that can be opened in the world editor.");
115
                throw new NonWritableChannelException();
×
116
            }
117
            WurstCompilerJassImpl compiler = new WurstCompilerJassImpl(timeTaker, projectFolder, gui, mpqEditor, runArgs);
×
118
            compiler.setMapFile(mapCopy);
×
119
            purgeUnimportedFiles(model);
×
120

121
            gui.sendProgress("Check program");
×
122
            compiler.checkProg(model);
×
123

124
            if (gui.getErrorCount() > 0) {
×
125
                throw new RequestFailedException(MessageType.Warning, "Could not compile project: ", gui.getErrorList().get(0));
×
126
            }
127

128
            print("translating program ... ");
×
129
            compiler.translateProgToIm(model);
×
130

131
            if (gui.getErrorCount() > 0) {
×
132
                throw new RequestFailedException(MessageType.Error, "Could not compile project (error in translation): " + gui.getErrorList().get(0));
×
133
            }
134

135
            timeTaker.measure("Runinng Compiletime Functions", () -> compiler.runCompiletime(projectConfigData, isProd, runArgs.isCompiletimeCache()));
×
136

137
            if (runArgs.isLua()) {
×
138
                print("translating program to Lua ... ");
×
139
                Optional<LuaCompilationUnit> luaCode = Optional.ofNullable(compiler.transformProgToLua());
×
140

141
                if (!luaCode.isPresent()) {
×
142
                    print("Could not compile project\n");
×
143
                    throw new RuntimeException("Could not compile project (error in LUA translation)");
×
144
                }
145

146
                StringBuilder sb = new StringBuilder();
×
147
                luaCode.get().print(sb, 0);
×
148

149
                String compiledMapScript = sb.toString();
×
150
                File buildDir = getBuildDir();
×
151
                File outFile = new File(buildDir, "compiled.lua");
×
152
                Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile);
×
153
                return outFile;
×
154

155
            } else {
156
                print("translating program to jass ... ");
×
157
                compiler.transformProgToJass();
×
158

159
                Optional<JassProg> jassProg = Optional.ofNullable(compiler.getProg());
×
160
                if (!jassProg.isPresent()) {
×
161
                    print("Could not compile project\n");
×
162
                    throw new RuntimeException("Could not compile project (error in JASS translation)");
×
163
                }
164

165
                gui.sendProgress("Printing program");
×
166
                JassPrinter printer = new JassPrinter(!runArgs.isOptimize(), jassProg.get());
×
167
                String compiledMapScript = printer.printProg();
×
168
                File buildDir = getBuildDir();
×
169
                File outFile = new File(buildDir, "compiled.j.txt");
×
170
                Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile);
×
171

172
                if (!runArgs.isDisablePjass()) {
×
173
                    gui.sendProgress("Running PJass");
×
174
                    Pjass.Result pJassResult = Pjass.runPjass(outFile,
×
175
                        new File(buildDir, "common.j").getAbsolutePath(),
×
176
                        new File(buildDir, "blizzard.j").getAbsolutePath());
×
177
                    WLogger.info(pJassResult.getMessage());
×
178
                    if (!pJassResult.isOk()) {
×
179
                        for (CompileError err : pJassResult.getErrors()) {
×
180
                            gui.sendError(err);
×
181
                        }
×
182
                        throw new RuntimeException("Could not compile project (PJass error)");
×
183
                    }
184
                }
185

186
                if (runArgs.isHotStartmap()) {
×
187
                    gui.sendProgress("Running JHCR");
×
188
                    return runJassHotCodeReload(outFile);
×
189
                }
190
                return outFile;
×
191
            }
192
        } catch (Exception e) {
×
193
            throw new RuntimeException(e);
×
194
        }
195
    }
196

197
    private File runJassHotCodeReload(File mapScript) throws IOException, InterruptedException {
198
        File buildDir = getBuildDir();
×
199
        File commonJ = new File(buildDir, "common.j");
×
200
        File blizzardJ = new File(buildDir, "blizzard.j");
×
201

202
        if (!commonJ.exists()) {
×
203
            throw new IOException("Could not find file " + commonJ.getAbsolutePath());
×
204
        }
205

206
        if (!blizzardJ.exists()) {
×
207
            throw new IOException("Could not find file " + blizzardJ.getAbsolutePath());
×
208
        }
209

210
        ProcessBuilder pb = new ProcessBuilder(configProvider.getJhcrExe(), "init", commonJ.getName(), blizzardJ.getName(), mapScript.getName());
×
211
        pb.directory(buildDir);
×
212
        Utils.exec(pb, Duration.ofSeconds(30), System.err::println);
×
213
        return new File(buildDir, "jhcr_war3map.j");
×
214
    }
215

216
    /**
217
     * removes everything compilation unit which is neither
218
     * - inside a wurst folder
219
     * - a jass file
220
     * - imported by a file in a wurst folder
221
     */
222
    private void purgeUnimportedFiles(WurstModel model) {
223

224
        Set<CompilationUnit> imported = model.stream()
×
225
            .filter(cu -> isInWurstFolder(cu.getCuInfo().getFile()) || cu.getCuInfo().getFile().endsWith(".j")).collect(Collectors.toSet());
×
226
        addImports(imported, imported);
×
227

228
        model.removeIf(cu -> !imported.contains(cu));
×
229
    }
×
230

231
    private boolean isInWurstFolder(String file) {
232
        Path p = Paths.get(file);
×
233
        Path w;
234
        try {
235
            w = workspaceRoot.getPath();
×
236
        } catch (FileNotFoundException e) {
×
237
            return false;
×
238
        }
×
239
        return p.startsWith(w)
×
240
            && java.nio.file.Files.exists(p)
×
241
            && Utils.isWurstFile(file);
×
242
    }
243

244
    protected File getBuildDir() {
245
        File buildDir;
246
        try {
247
            buildDir = new File(workspaceRoot.getFile(), "_build");
×
248
        } catch (FileNotFoundException e) {
×
249
            throw new RuntimeException("Cannot get build dir", e);
×
250
        }
×
251
        if (!buildDir.exists()) {
×
252
            UtilsIO.mkdirs(buildDir);
×
253
        }
254
        return buildDir;
×
255
    }
256

257
    private void addImports(Set<CompilationUnit> result, Set<CompilationUnit> toAdd) {
258
        Set<CompilationUnit> imported =
×
259
            toAdd.stream()
×
260
                .flatMap((CompilationUnit cu) -> cu.getPackages().stream())
×
261
                .flatMap((WPackage p) -> p.getImports().stream())
×
262
                .map(WImport::attrImportedPackage)
×
263
                .filter(Objects::nonNull)
×
264
                .map(WPackage::attrCompilationUnit)
×
265
                .collect(Collectors.toSet());
×
266
        boolean changed = result.addAll(imported);
×
267
        if (changed) {
×
268
            // recursive call terminates, as there are only finitely many compilation units
269
            addImports(result, imported);
×
270
        }
271
    }
×
272

273
    protected void print(String s) {
274
        WLogger.info(s);
×
275
    }
×
276

277
    protected void println(String s) {
278
        WLogger.info(s);
×
279
    }
×
280

281

282
    protected File compileScript(WurstGui gui, ModelManager modelManager, List<String> compileArgs, Optional<File> mapCopy,
283
                                 WurstProjectConfigData projectConfigData, boolean isProd, File scriptFile) throws Exception {
284
        RunArgs runArgs = new RunArgs(compileArgs);
×
285
        gui.sendProgress("Compiling Script");
×
286
        print("Compile Script : ");
×
287
        for (File dep : modelManager.getDependencyWurstFiles()) {
×
288
            WLogger.info("dep: " + dep.getPath());
×
289
        }
×
290
        print("Dependencies done.");
×
291
        if (safeCompilation != RunMap.SafetyLevel.QuickAndDirty) {
×
292
            // it is safer to rebuild the project, instead of taking the current editor state
293
            gui.sendProgress("Cleaning project");
×
294
            modelManager.clean();
×
295
            gui.sendProgress("Building project");
×
296
            modelManager.buildProject();
×
297
        }
298

299
        if (modelManager.hasErrors()) {
×
300
            for (CompileError compileError : modelManager.getParseErrors()) {
×
301
                gui.sendError(compileError);
×
302
            }
×
303
            throw new RequestFailedException(MessageType.Warning, "Cannot run code with syntax errors.");
×
304
        }
305

306
        WurstModel model = modelManager.getModel();
×
307
        if (safeCompilation != RunMap.SafetyLevel.QuickAndDirty) {
×
308
            // compilation will alter the model (e.g. remove unused imports),
309
            // so it is safer to create a copy
310
            model = ModelManager.copy(model);
×
311
        }
312

313
        return compileMap(modelManager.getProjectPath(), gui, mapCopy, runArgs, model, projectConfigData, isProd);
×
314
    }
315

316

317
    protected CompilationResult compileScript(ModelManager modelManager, WurstGui gui, Optional<File> testMap, WurstProjectConfigData projectConfigData, File buildDir, boolean isProd) throws Exception {
318
        if (testMap.isPresent() && testMap.get().exists()) {
×
319
            boolean deleteOk = testMap.get().delete();
×
320
            if (!deleteOk) {
×
321
                throw new RequestFailedException(MessageType.Error, "Could not delete old mapfile: " + testMap);
×
322
            }
323
        }
324
        if (map.isPresent() && testMap.isPresent()) {
×
325
            Files.copy(map.get(), testMap.get());
×
326
        }
327

328
        CompilationResult result;
329

330
        if (runArgs.isHotReload()) {
×
331
            // For hot reload use cached war3map if it exists
332
            result = new CompilationResult();
×
333
            result.script = new File(buildDir, "war3mapj_with_config.j.txt");
×
334
            if (!result.script.exists()) {
×
335
                result.script = new File(new File(workspaceRoot.getFile(), "wurst"), "war3map.j");
×
336
            }
337
            if (!result.script.exists()) {
×
338
                throw new RequestFailedException(MessageType.Error, "Could not find war3map.j file");
×
339
            }
340
        } else {
341
            timeTaker.beginPhase("load map script");
×
342
            File scriptFile = loadMapScript(testMap, modelManager, gui);
×
343
            timeTaker.endPhase();
×
344
            result = applyProjectConfig(gui, testMap, buildDir, projectConfigData, scriptFile);
×
345
        }
346

347

348

349
        // first compile the script:
350
        result.script = compileScript(gui, modelManager, compileArgs, testMap, projectConfigData, isProd, result.script);
×
351

352
        Optional<WurstModel> model = Optional.ofNullable(modelManager.getModel());
×
353
        if (!model.isPresent()
×
354
                || model
355
                    .get()
×
356
                    .stream()
×
357
                    .noneMatch((CompilationUnit cu) -> cu.getCuInfo().getFile().endsWith("war3map.j"))) {
×
358
            println("No 'war3map.j' file could be found inside the map nor inside the wurst folder");
×
359
            println("If you compile the map with WurstPack once, this file should be in your wurst-folder. ");
×
360
            println("We will try to start the map now, but it will probably fail. ");
×
361
        }
362
        return result;
×
363
    }
364

365
    private static Long lastMapModified = 0L;
×
366

367
    private File loadMapScript(Optional<File> mapCopy, ModelManager modelManager, WurstGui gui) throws Exception {
368
        File scriptFile = new File(new File(workspaceRoot.getFile(), "wurst"), "war3map.j");
×
369
        // If runargs are no extract, either use existing or throw error
370
        // Otherwise try loading from map, if map was saved with wurst, try existing script, otherwise error
371
        if (!mapCopy.isPresent() || runArgs.isNoExtractMapScript()) {
×
372
            if (scriptFile.exists()) {
×
373
                modelManager.syncCompilationUnit(WFile.create(scriptFile));
×
374
                return scriptFile;
×
375
            } else {
376
                throw new CompileError(new WPos("", new LineOffsets(), 0, 0),
×
377
                    "RunArg noExtractMapScript is set but no mapscript is provided inside the wurst folder");
378
            }
379
        }
380
        long mapLastModified = mapCopy.get().lastModified();
×
381
        if (mapLastModified > lastMapModified) {
×
382
            lastMapModified = mapLastModified;
×
383
            WLogger.info("extracting mapscript");
×
384
            byte[] extractedScript = null;
×
385
            try (@Nullable MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy, true)) {
×
386
                if (mpqEditor.hasFile("war3map.j")) {
×
387
                    extractedScript = mpqEditor.extractFile("war3map.j");
×
388
                }
389
            }
390
            if (extractedScript == null) {
×
391
                if (scriptFile.exists()) {
×
392
                    String msg = "No war3map.j in map file, using old extracted file";
×
393
                    WLogger.info(msg);
×
394
                } else {
×
395
                    CompileError err = new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0),
×
396
                        "No war3map.j found in map file.");
397
                    gui.showInfoMessage(err.getMessage());
×
398
                    WLogger.severe(err);
×
399
                }
×
400
            } else if (new String(extractedScript, StandardCharsets.UTF_8).startsWith(JassPrinter.WURST_COMMENT_RAW)) {
×
401
                WLogger.info("map has already been compiled with wurst");
×
402
                // file generated by wurst, do not use
403
                if (scriptFile.exists()) {
×
404
                    String msg = "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Using war3map.j from Wurst directory instead.";
×
405
                    WLogger.info(msg);
×
406
                } else {
×
407
                    CompileError err = new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0),
×
408
                        "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Please add war3map.j to the wurst directory.");
409
                    gui.showInfoMessage(err.getMessage());
×
410
                    WLogger.severe(err);
×
411
                }
×
412
            } else {
413
                WLogger.info("new map, use extracted");
×
414
                // write mapfile from map to workspace
415
                Files.write(extractedScript, scriptFile);
×
416
            }
417
        } else {
×
418
            System.out.println("Map not modified, not extracting script");
×
419
        }
420

421

422
        return scriptFile;
×
423
    }
424

425
    private CompilationResult applyProjectConfig(WurstGui gui, Optional<File> testMap, File buildDir, WurstProjectConfigData projectConfig, File scriptFile) throws FileNotFoundException {
426
        AtomicReference<CompilationResult> result = new AtomicReference<>();
×
427
        gui.sendProgress("Applying Map Config...");
×
428
        timeTaker.measure("Applying Map Config", () -> {
×
429
            try {
430
                result.set(ProjectConfigBuilder.apply(projectConfig, testMap.get(), scriptFile, buildDir, runArgs, w3data));
×
431
            } catch (IOException e) {
×
432
                throw new RuntimeException(e);
×
433
            }
×
434
        });
×
435
        return result.get();
×
436
    }
437

438
    private W3InstallationData getBestW3InstallationData() throws RequestFailedException {
439
        if (Orient.isLinuxSystem()) {
×
440
            // no Warcraft installation supported on Linux
441
            return new W3InstallationData(Optional.empty(), Optional.empty());
×
442
        }
443
        if (wc3Path.isPresent()) {
×
444
            W3InstallationData w3data = new W3InstallationData(new File(wc3Path.get()));
×
445
            if (!w3data.getWc3PatchVersion().isPresent()) {
×
446
                throw new RequestFailedException(MessageType.Error, "Could not find Warcraft III installation at specified path: " + wc3Path);
×
447
            }
448

449
            return w3data;
×
450
        } else {
451
            return new W3InstallationData();
×
452
        }
453
    }
454

455
    protected void injectMapData(WurstGui gui, Optional<File> testMap, CompilationResult result) throws Exception {
456
        gui.sendProgress("Injecting map data");
×
457
        try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(testMap)) {
×
458
            String mapScriptName;
459
            if (runArgs.isLua()) {
×
460
                mapScriptName = "war3map.lua";
×
461
            } else {
462
                mapScriptName = "war3map.j";
×
463
            }
464
            // delete both original mapscripts, just to be sure:
465
            mpqEditor.deleteFile("war3map.j");
×
466
            mpqEditor.deleteFile("war3map.lua");
×
467
            if (result.w3i != null) {
×
468
                mpqEditor.deleteFile(W3I.GAME_PATH.getName());
×
469
                mpqEditor.insertFile(W3I.GAME_PATH.getName(), result.w3i);
×
470
            }
471
            mpqEditor.insertFile(mapScriptName, result.script);
×
472
        }
473
    }
×
474
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc