Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ This repository has multiple entry points that may trigger compilation/build beh
* `WurstLanguageServer` wires LSP protocol handlers.
* `LanguageWorker` serializes requests and file-change reconciliation.
* `ModelManagerImpl` owns project model state (wurst files, dependencies, diagnostics).
* An edit which changes nothing but bodies of functions, constructors, destructors and init blocks is moved into the unit of the model (`BodyOnlyEdit`): the importers keep what they resolved, only that unit is checked again, and its module instantiations survive the check, because the importers point into them. Bodies of modules and interfaces, global initialisers, Jass and anything else count as declarations; nothing in a module the unit declares may move (every user holds a copy with its positions), and every module use must have expanded without an error (expansion reports it only once). Any other change of such a unit, or of what it depends on, invalidates it as before. `BodyOnlyEditTests` and `IncrementalModelOracleTests` compare it with a build from scratch.
* An edit which changes nothing but bodies of functions, constructors, destructors and init blocks is moved into the unit of the model (`BodyOnlyEdit`): importers keep what they resolved, only that unit is checked again, and its module instantiations survive because importers point into them. Bodies of modules and interfaces and global initialisers count as declarations. Nothing in a module the unit declares may move (every user holds a copy with its positions), and every module use must have expanded without an error (expansion reports it only once). Pure Jass units keep their declarations across function-body edits that leave variable-event wrapper candidates unchanged. Map builds can validate just those Jass units when all other selected units are checked. `BodyOnlyEditTests`, `IncrementalModelOracleTests` and `MapModelReuseTests` cover reuse against a fresh build.
* Add, replace, remove or purge compilation units of the managed model only through `ModelManager` (`retainCompilationUnits` for purges), never by mutating `getModel()`: lookups from other threads rely on its `modelLock`. A copy from `ModelManager.copy` can be changed freely.
* Lua hot-reload compilations retain pre-lowering IM through `IncrementalImTranslation`. Unchanged bodies keep their
AST nodes and refresh their positions; changed bodies update the retained input only while declaration dependencies
Expand Down
15 changes: 8 additions & 7 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,12 @@ Notes; finished-work narrative does not.
- **Incremental map-script declarations and build source policy.** Run, editor build and CLI build use
the managed model; cancellation is honored at safe boundaries around shared AST preparation and
throughout the private IM/backend work. See `docs/RUNMAP_PERFORMANCE.md`. What is left:
a `.j` change makes `calculateCUsToUpdate` return the whole model, and a compilation
swaps the map script with the project config applied into the model (`replaceBaseScriptWithConfig`).
The swap changes only function bodies (`config`, `InitCustomPlayerSlots`, ...) yet invalidates every
attribute, so the first compilation of a model checks all of it again; later ones skip the check. The
a `.j` declaration change makes `calculateCUsToUpdate` return the whole model. A configured map script
that changes only function bodies keeps its declarations in place and is validated on its own when
the rest of the selected model is already checked. Changes to variable-event wrapper candidates still
invalidate callers. The
CLI loads the project without checking it, swaps the script in and checks once (`ModelManager.loadProject`,
`checkProject`); the language server has checked its model before it knows the map, so its first
run still checks again. The swap's own cost in the language server was not isolated: on castle fight
`checkProject`). The swap's own cost in the language server was not isolated: on Castle Fight
without optimisations the first build of a model takes 21 s and later ones 11 to 12 s in one JVM, and
the stage samples show most of the difference in passes the swap does not touch, so JIT warm-up. Next,
keep the unchanged top-level declarations of a changed Jass file and re-check only the units which
Expand Down Expand Up @@ -241,7 +240,9 @@ Notes; finished-work narrative does not.
ownership requires a restart. New
snapshots also require a restart when compile-time evaluation observes integer object/handle identities;
integer fields and keys cannot be relocated safely onto the live allocator.
- The first reload after a command-line start checks the whole model again (about 47 s on Castle Fight).
- The first reload after a command-line start previously checked the whole model again (about 47 s on Castle Fight).
A Castle Fight title-only control reused the checked model. The normal config injection still checks the whole
model because it introduces three top-level Jass functions. See [offline measurements](docs/RUNMAP_PERFORMANCE.md#first-reload-after-map-config-injection).
Generated object-data functions ship whole. Measure smaller representations without splitting effectful
initialization incorrectly.
- The 6 Nov harness smoke run proved VS Code save, refusal, recovery and matching game receipts on
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
* checked again.
* <p>
* The bodies of a module and of an interface are not bodies in this sense: a module is copied into every class
* using it, and whether an interface function has a body decides whether it is abstract. A unit declaring Jass
* names is never edited in place either, because every unit sees them.
* using it, and whether an interface function has a body decides whether it is abstract. A pure Jass unit can
* retain its declarations when only function bodies change.
*/
final class BodyOnlyEdit {

Expand All @@ -27,7 +27,14 @@ private BodyOnlyEdit() {
/** Whether {@code fresh} differs from {@code old} in nothing but bodies, see {@link BodyOnlyEdit}. */
static boolean applies(CompilationUnit old, CompilationUnit fresh) {
if (!old.getJassDecls().isEmpty() || !fresh.getJassDecls().isEmpty()) {
return false;
if (!old.getPackages().isEmpty() || !fresh.getPackages().isEmpty()) {
return false;
}
JassToplevelDeclarations a = old.getJassDecls().copy();
JassToplevelDeclarations b = fresh.getJassDecls().copy();
normaliseJass(a);
normaliseJass(b);
return a.structuralEquals(b);
}
if (!modulesExpandedCleanly(old.getPackages())) {
return false;
Expand All @@ -45,10 +52,31 @@ static boolean applies(CompilationUnit old, CompilationUnit fresh) {
* and receive the new positions, so retained translation inputs still refer to the managed model.
*/
static void apply(CompilationUnit old, CompilationUnit fresh) {
transplant(old.getJassDecls(), fresh.getJassDecls(), false);
transplant(old.getPackages(), fresh.getPackages(), false);
old.setCuInfo(fresh.getCuInfo());
}

private static void normaliseJass(JassToplevelDeclarations declarations) {
for (JassToplevelDeclaration declaration : declarations) {
// Wrapper detection affects validation of callers in other files.
boolean mayDefineWrapper = declaration instanceof FuncDef function && callsVariableEvent(function.getBody());
normalise(declaration, mayDefineWrapper);
}
}

private static boolean callsVariableEvent(Element e) {
if (e instanceof ExprFunctionCall call && call.getFuncName().equals("TriggerRegisterVariableEvent")) {
return true;
}
for (int i = 0; i < e.size(); i++) {
if (callsVariableEvent(e.get(i))) {
return true;
}
}
return false;
}

/**
* Whether every class and module of the unit got an instantiation for each module it uses, without an error.
* Expanding a module reports what is wrong with its use only while it expands, and an edit in place keeps the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ default boolean isChecked(WurstModel model, Collection<CompilationUnit> units) {
return isFullyChecked(model);
}

/** Units requiring validation when compiling the selected view of a managed model. */
default Collection<CompilationUnit> unitsToCheckForBuild(WurstModel model, Collection<CompilationUnit> units) {
return units;
}

/** Record a successful check without claiming excluded units were checked. */
default void markChecked(WurstModel model, Collection<CompilationUnit> units) {
if (units.size() == model.size() && units.containsAll(model)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1254,6 +1254,25 @@ public boolean isChecked(WurstModel checkedModel, Collection<CompilationUnit> un
}
}

@Override
public Collection<CompilationUnit> unitsToCheckForBuild(WurstModel checkedModel, Collection<CompilationUnit> units) {
synchronized (modelLock) {
if (checkedModel == null || checkedModel != model) {
return units;
}
List<CompilationUnit> dirty = new ArrayList<>();
for (CompilationUnit unit : units) {
if (uncheckedUnits.contains(unit)) {
if (!bodyEdited.contains(unit) || unit.getJassDecls().isEmpty()) {
return units;
}
dirty.add(unit);
}
}
return dirty;
}
}

@Override
public void markChecked(WurstModel checkedModel, Collection<CompilationUnit> units) {
synchronized (modelLock) {
Expand Down Expand Up @@ -1408,7 +1427,7 @@ private Set<CompilationUnit> calculateCUsToUpdate(Collection<CompilationUnit> ch
Set<CompilationUnit> result = new TreeSet<>(Comparator.comparing(cu -> cu.getCuInfo().getFile()));
result.addAll(changed);

if (oldJassNames || changed.stream().anyMatch(ModelManagerImpl::declaresJassNames)) {
if (oldJassNames || changed.stream().anyMatch(cu -> declaresJassNames(cu) && !isBodyEdited(cu))) {
// Jass names are visible everywhere, so everything must be checked again:
result.addAll(model);
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,10 @@ private static void checkModel(ModelManager modelManager, WurstCompilerJassImpl
compiler.adoptCheckedModel(model, units);
return;
}
boolean validated = compiler.checkProg(model, units, units);
Collection<CompilationUnit> toCheck = sameChecks ? modelManager.unitsToCheckForBuild(model, units) : units;
boolean validated = compiler.checkProg(model, toCheck, units);
if (sameChecks && validated && compiler.getErrorHandler().getErrorCount() == 0) {
modelManager.markChecked(model, units);
modelManager.markChecked(model, toCheck);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import de.peeeq.wurstio.languageserver.*;
import de.peeeq.wurstio.languageserver.requests.*;
import de.peeeq.wurstscript.RunArgs;
import de.peeeq.wurstscript.ast.CompilationUnit;
import de.peeeq.wurstscript.ast.WurstModel;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.gui.WurstGui;
Expand All @@ -18,6 +19,7 @@
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CancellationException;
Expand Down Expand Up @@ -193,6 +195,8 @@ public void excludedVariableEventsDoNotPreserveSelectedGlobals(boolean build, bo
+ "function configuredHelper takes nothing returns integer\nreturn 2\nendfunction\n");
assertFalse(compile(request, project, new WurstGuiCliImpl()).contains("selectedGlobal"),
"validation of a changed configured script must also use the selected view");
assertTrue(project.manager.lastBuildCheck.contains(project.manager.getCompilationUnit(WFile.create(project.source))),
"a generated top-level Jass function changes the names visible to every selected unit");
}

@Test(dataProvider = "commands")
Expand Down Expand Up @@ -435,29 +439,55 @@ public void changedConfiguredScriptIsCheckedBeforeReusingTheModel(boolean build,
File baseScript = new File(project.root, "wurst/war3map.j");
String base = configuredScript(1);
Files.writeString(baseScript.toPath(), base);
project.manager.reconcile(project.manager.syncCompilationUnitContent(WFile.create(baseScript), base));
WFile mapSource = WFile.create(baseScript);
project.manager.reconcile(project.manager.syncCompilationUnitContent(mapSource, base));
var originalMapUnit = project.manager.getCompilationUnit(mapSource);
String main = source(7) + "public int fromMap = getConfigured()\n"
+ "init\n BJDebugMsg(I2S(fromMap))\n";
Files.writeString(project.source.toPath(), main);
project.manager.reconcile(project.manager.syncCompilationUnitContent(WFile.create(project.source), main));
List<String> args = lua ? List.of("-lua") : List.of("-noPJass");
List<String> args = lua ? List.of("-lua", "-luaHotReload") : List.of("-noPJass");
Probe request = build ? new BuildProbe(project.root, args) : new RunProbe(project.root, args);

Files.writeString(project.script.toPath(), configuredScript(2));
String first = compile(request, project, new WurstGuiCliImpl());
assertSame(project.manager.getCompilationUnit(mapSource), originalMapUnit,
"changing only a configured Jass body must keep the declarations the project already resolved");
assertEquals(project.manager.lastBuildCheck, List.of(originalMapUnit));
assertTrue(project.manager.isFullyChecked(project.manager.getModel()));
Files.writeString(project.script.toPath(), configuredScript(3));
String changed = compile(request, project, new WurstGuiCliImpl());
assertNotEquals(changed, first);
assertEquals(compile(request, project, new WurstGuiCliImpl()), changed);
var manifestPath = project.root.toPath().resolve("_build/luaHotReload/manifest.json");
String manifest = lua ? Files.readString(manifestPath) : "";

Project fresh = new Project(project.root, project.source, project.script, new CountingManager(project.root));
fresh.manager.buildProject();
Probe freshRequest = build ? new BuildProbe(project.root, args) : new RunProbe(project.root, args);
assertEquals(compile(freshRequest, fresh, new WurstGuiCliImpl()), changed);
if (lua) {
assertEquals(Files.readString(manifestPath), manifest);
}
assertEquals(project.manager.cleanCalls, 0);
}

@Test
public void configuredJassBodyThatDefinesAVariableEventWrapperRechecksCallers() throws Exception {
Project project = project();
WFile mapSource = WFile.create(new File(project.root, "wurst/war3map.j"));
String script = Files.readString(mapSource.getFile().toPath())
+ "function forwardEvent takes string name returns event\n return null\nendfunction\n";
project.manager.reconcile(project.manager.syncCompilationUnitContent(mapSource, script));
var originalMapUnit = project.manager.getCompilationUnit(mapSource);
String edited = script.replace("return null", "return TriggerRegisterVariableEvent(null, name, null, 0.0)");
Files.writeString(project.script.toPath(), edited);
compile(new RunProbe(project.root, List.of("-lua")), project, new WurstGuiCliImpl());
assertNotSame(project.manager.getCompilationUnit(mapSource), originalMapUnit);
assertTrue(project.manager.lastBuildCheck.contains(project.manager.getCompilationUnit(WFile.create(project.source))),
"a change in wrapper status can change validation of callers");
}

@Test(dataProvider = "commands")
public void onlyImportedDependencyPackagesAreCompiled(boolean build, boolean lua) throws Exception {
Project project = project();
Expand Down Expand Up @@ -576,8 +606,13 @@ private record Project(File root, File source, File script, CountingManager mana

private static class CountingManager extends ModelManagerImpl {
int cleanCalls;
List<CompilationUnit> lastBuildCheck = List.of();
CountingManager(File root) { super(root, new BufferManager()); }
@Override public void clean() { cleanCalls++; super.clean(); }
@Override public void markChecked(WurstModel model, Collection<CompilationUnit> units) {
lastBuildCheck = List.copyOf(units);
super.markChecked(model, units);
}
}

private interface Probe {
Expand Down
14 changes: 14 additions & 0 deletions docs/RUNMAP_PERFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,17 @@ Raw artifacts are retained under the compiler's ignored `temp/`: `runmap-{castle
`runmap-{castle,zombie}-{0,1,2}.jfr`, `runmap-{castle,zombie}-2-report.log`, and the equivalent
`runmap-{castle,zombie}-control*` logs/recordings. `runmap-{castle,zombie}-normal.lua` preserves the comparison
outputs. Earlier `map-*-cold*` recordings measure optimized CLI builds and are outside this RunMap analysis.

## First reload after map config injection

On 6 Nov, a compile-only Windows probe loaded the pinned Castle Fight replay fixture as the editor
does, then compiled its first Lua reload against the script produced by the normal config injector.
The baseline (`bf5d7fd0b`) and the body-only reuse change (`f6727bf3b`) both checked all 758 units.
The injector introduced `InitCustomPlayerSlots`, `InitCustomTeams` and `InitAllyPriorities` as top-level
functions, so a full check was required. The typecheck stage took 2.85 s and 2.97 s, respectively.

As a control, the same fixture started from the already configured script and applied a different
map title. The baseline checked 758 units in 4.95 s. Body-only reuse checked one unit in 0.23 s.
Each measurement came from one fresh JVM run. These are compiler stage observations, with no game launch or
save-to-game measurement. The next first-reload optimization needs to handle Jass declaration
additions without overlooking cross-file name resolution or diagnostics.
Loading