Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
7482f60
Lua hot reload: callbacks told apart by their order reload, @onHotRel…
Frotty Oct 24, 2026
9b284fa
Lua hot reload: a copy of a callback another one keeps is no move
Frotty Oct 24, 2026
6b076c5
Lua hot reload: a hook runs once, and a failing one leaves the stack-…
Frotty Oct 24, 2026
960e10a
Merge remote-tracking branch 'origin/master' into lua-hot-reload-call…
Frotty Oct 24, 2026
0459fec
Lua hot reload: the session keeps every body sent for callbacks told …
Frotty Oct 24, 2026
9be9fc7
Lua hot reload: keep the storage of every source global, read or not
Frotty Oct 24, 2026
97ba178
Merge branch 'worktree-agent-a6bc403ab0e036d30' into lua-hot-reload-r…
Frotty Oct 24, 2026
057d75a
Lua hot reload: edited constant array literals reload
Frotty Oct 24, 2026
7db7ff2
Merge remote-tracking branch 'origin/master' into lua-hot-reload-real…
Frotty Oct 24, 2026
2dcd972
Merge branch 'worktree-agent-a201090638a4915ef' into lua-hot-reload-r…
Frotty Oct 24, 2026
f19bade
Lua hot reload: a generic static's specialisations are initializer un…
Frotty Oct 24, 2026
0b7c98c
Merge branch 'worktree-agent-a100369ea8a368cad' into lua-hot-reload-r…
Frotty Oct 24, 2026
a68c4ef
Lua hot reload: the specialisations with a unit of their own are a se…
Frotty Oct 24, 2026
cd9d089
Lua hot reload: the poll counts the users playing itself; a map whose…
Frotty Oct 24, 2026
a0e0b61
Lua hot reload: index the storage of globals once; the manifest of a …
Frotty Oct 24, 2026
9f19322
Lua hot reload: a generic static whose several initial values have an…
Frotty Oct 24, 2026
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
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,8 @@ private static boolean isNonZeroConstant(ImExpr e) {
/**
* Removes the globals which no reachable code reads, with the assignments of effect-free values to them. A
* global is needed when reachable code mentions it in any other way (a read, an assignment which may have an
* effect, a call argument), when it is preserved or pinned, and when the effect-free value assigned to a
* effect, a call argument), when it is preserved or pinned, in a hot-reload build when it is a global of the
* source ({@link ImTranslator#isHotReloadSourceGlobal}), and when the effect-free value assigned to a
* needed global or the initialiser of a needed global of blizzard.j or common.j reads it. Those are in no
* function body: the game initialises them, and the interpreters evaluate them when they are first read.
*/
Expand All @@ -306,7 +307,7 @@ void removeUnreadGlobals(ImProg prog, Collection<ImVar> pinned) {
markNeeded(var, needed, pending);
}
for (ImVar var : prog.getGlobals()) {
if (NamePreservation.isPreserved(var)) {
if (NamePreservation.isPreserved(var) || trans.isHotReloadSourceGlobal(var)) {
markNeeded(var, needed, pending);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import de.peeeq.wurstscript.ast.ExprClosure;
import de.peeeq.wurstscript.ast.InterfaceDef;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.intermediatelang.optimizer.SideEffectAnalyzer;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imtojass.ImAttrType;
import de.peeeq.wurstscript.translation.imtojass.TypeRewriteMatcher;
Expand Down Expand Up @@ -2922,6 +2923,17 @@ private void createSpecializedGlobals(ImClass originalClass, GenericTypes generi
};

List<ImSet> specializedInitsForMap = new ArrayList<>(originalInits.size());
// A hot-reload build keeps each source initializer as a unit of its own; each specialisation's
// storage gets a unit of its own too, so a payload can initialise a new one alone. Units compute all of
// one specialisation's initial values before the next, where the program computes each value for every
// specialisation in turn: with several values of which one has an effect (an array literal of calls)
// the order shows, and the specialisations stay in the source unit.
boolean orderUnobservable = originalInits.size() <= 1
|| originalInits.stream().noneMatch(set -> SideEffectAnalyzer.quickcheckHasSideeffects(set.getRight()));
ImFunction sourceUnit = orderUnobservable && parentStmts != null
&& parentStmts.getParent() instanceof ImFunction unit
&& translator.luaGlobalInitializers.get(unit) == originalGlobal ? unit : null;
List<ImSet> unitInits = new ArrayList<>(originalInits.size());

// Create specialized init sets and schedule: insert each right after its corresponding original init set
for (ImSet origSet : originalInits) {
Expand All @@ -2935,7 +2947,9 @@ private void createSpecializedGlobals(ImClass originalClass, GenericTypes generi
// Append after earlier specializations of this initializer. Each invocation of
// createSpecializedGlobals has its own insertion batch; always inserting after
// origSet would therefore reverse specialization discovery/initializer order.
if (parentStmts != null) {
if (sourceUnit != null) {
unitInits.add(specSet);
} else if (parentStmts != null) {
Comment thread
Frotty marked this conversation as resolved.
Resolved
ImStmt insertionPoint = specializedInitializerTails.getOrDefault(origSet, origSet);
IdentityHashMap<ImStmt, List<ImStmt>> byStmt =
insertsByParent.computeIfAbsent(parentStmts, k -> new IdentityHashMap<>());
Expand All @@ -2946,6 +2960,9 @@ private void createSpecializedGlobals(ImClass originalClass, GenericTypes generi
// keep prog.getGlobalInits consistent, but do NOT reuse the tree-attached node elsewhere
specializedInitsForMap.add((ImSet) specSet.copy());
}
if (sourceUnit != null) {
translator.addSpecializedGlobalInitializer(sourceUnit, specializedGlobal, unitInits);
}

prog.getGlobalInits().put(specializedGlobal, specializedInitsForMap);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,12 @@ public <T extends Element> T canonical(T copy) {
/** Complete source global initializers, kept as functions in hot-reload builds before flattening splits them. */
public final Map<ImFunction, ImVar> luaGlobalInitializers = new LinkedHashMap<>();

/** The call of each initializer in {@link #luaGlobalInitializers}, or of the last unit added after it. */
private final Map<ImFunction, ImFunctionCall> luaGlobalInitializerTails = new IdentityHashMap<>();

/** The specialisations of generic statics which {@link #addSpecializedGlobalInitializer} gave a unit of their own. */
private final Set<ImVar> specializationsWithOwnUnit = Collections.newSetFromMap(new IdentityHashMap<>());

/** The stack and depth which -stacktraces instrumentation pushes and pops around every call; empty without it. */
public final Set<ImVar> stackTraceStorage = Collections.newSetFromMap(new IdentityHashMap<>());

Expand Down Expand Up @@ -422,6 +428,23 @@ public List<ImFunction> hotReloadHooks() {
return hooks;
}

/**
* Whether {@code global} is a global of the source which a {@code -luaHotReload} build keeps whether anything reads
* it or not. Its initializer is a unit of the manifest which records the storage it writes; dropping the storage
* of a global nothing reads would change that unit whenever an edit starts or stops reading the global, and a
* payload refuses that. Kept, a global an edit starts to read has the value the map gave it at the start. The
* globals of common.j and blizzard.j and those of generic classes, which the generics specialise, are not
* included. False in any other build.
*/
public boolean isHotReloadSourceGlobal(ImVar global) {
return runArgs.isLuaHotReload()
&& !global.getIsBJ()
&& global.getTrace() instanceof GlobalVarDef
&& isGlobalOf(global)
&& genericStaticOwnerOf(global) == null
&& specialisationOf(global) == null;
}

/**
* The globals this translator created for passes which run later and reach them through its handle, not through
* an access in a body: the variables which manage the instances of a class, which the class elimination builds
Expand Down Expand Up @@ -1577,7 +1600,9 @@ public void addGlobalInitalizer(ImVar v, PackageOrGlobal packageOrGlobal, VarIni
ImVoid(), ImVars(), ImStmts(), flags());
addFunction(initializer);
luaGlobalInitializers.put(initializer, v);
f.getBody().add(ImFunctionCall(trace, initializer, ImTypeArguments(), ImExprs(), false, CallType.NORMAL));
ImFunctionCall call = ImFunctionCall(trace, initializer, ImTypeArguments(), ImExprs(), false, CallType.NORMAL);
f.getBody().add(call);
luaGlobalInitializerTails.put(initializer, call);
f = initializer;
}
if (initialExpr instanceof Expr expr) {
Expand Down Expand Up @@ -1607,6 +1632,52 @@ public void addGlobalInitalizer(ImVar v, PackageOrGlobal packageOrGlobal, VarIni
}
}

/**
* In a hot-reload build, gives a specialisation of a generic static an initializer unit of its own, holding
* {@code initialValues}. It is called right after {@code source}, the unit of the static it was copied from, and
* after the specialisations which got theirs before it, so the initial values are computed in the order one unit
* computed them. Each specialisation is storage of its own, so a payload can initialise a new one alone and keep the
* values of the others; the unit is made here, where the specialised storage is, and not found again in the Lua
* backend. Locals of {@code source} the initial values use become locals of the new unit.
*/
public void addSpecializedGlobalInitializer(ImFunction source, ImVar specialized, List<ImSet> initialValues) {
ImFunctionCall tail = luaGlobalInitializerTails.get(source);
if (tail == null || !(tail.getParent() instanceof ImStmts calls)) {
throw new CompileError(specialized,
"The initializer of " + specialized.getName() + " has no call of its source initializer to follow.");
}
ImFunction initializer = ImFunction(specialized.getTrace(), "init_global_" + specialized.getName(), ImTypeVars(),
ImVars(), ImVoid(), ImVars(), ImStmts(), flags());
addFunction(initializer);
luaGlobalInitializers.put(initializer, specialized);
specializationsWithOwnUnit.add(specialized);
Map<ImVar, ImVar> locals = new IdentityHashMap<>();
for (ImSet initialValue : initialValues) {
initializer.getBody().add(initialValue);
initialValue.accept(new ImHelper.VarReplaceVisitor() {
@Override
ImVar getReplaceVar(ImVar v) {
if (v.getParent() != source.getLocals()) {
return null;
}
return locals.computeIfAbsent(v, original -> {
ImVar copy = original.copy();
initializer.getLocals().add(copy);
return copy;
});
}
});
}
ImFunctionCall call = ImFunctionCall(tail.getTrace(), initializer, ImTypeArguments(), ImExprs(), false, CallType.NORMAL);
for (int i = 0; i < calls.size(); i++) {
if (calls.get(i) == tail) {
calls.add(i + 1, call);
break;
}
}
luaGlobalInitializerTails.put(source, call);
}

public void addGlobalWithInitalizer(ImVar g, ImExpr initial) {
imProg.getGlobals().add(g);
ImSet imSet = ImSet(g.getTrace(), ImVarAccess(g), initial);
Expand Down Expand Up @@ -2248,9 +2319,10 @@ private void calculateCallRelationsAndVariables(boolean includeUsedVariables) {
calculateCallRelations(hook, includeUsedVariables);
}

// Mark externally visible globals as read so they survive garbage collection.
// Mark externally visible globals as read so they survive garbage collection, and in a hot-reload build every
// global of the source.
for (ImVar global : imProg.getGlobals()) {
if (NamePreservation.isPreserved(global)) readVariables.add(global);
if (NamePreservation.isPreserved(global) || isHotReloadSourceGlobal(global)) readVariables.add(global);
}

// The game initialises common.j and blizzard.j globals itself, so their initialisers are in no
Expand Down Expand Up @@ -2452,7 +2524,7 @@ public void forgetFunctionFacts() {
}
List<ImVar> unread = new ArrayList<>();
for (ImVar v : candidates) {
if (isGlobalOf(v) && NamePreservation.isPreserved(v)) {
if ((isGlobalOf(v) && NamePreservation.isPreserved(v)) || isHotReloadSourceGlobal(v)) {
continue;
}
if (v.getIsBJ()) {
Expand Down Expand Up @@ -2979,27 +3051,68 @@ public List<ImVar> getTupleScalarVars(ImVar v) {
return getVarsForTuple(v).allValuesStream().toList();
}

/** The retained storage of a source global, using recorded specialization and tuple-lowering relations. */
public List<ImVar> loweredGlobalStorage(ImVar source) {
Set<ImVar> roots = Collections.newSetFromMap(new IdentityHashMap<>());
roots.add(source);
ImVar original = canonical(source);
for (Element copy : specialisations.keySet()) {
if (copy instanceof ImVar variable && canonical(variable) == original) {
roots.add(variable);
/**
* The retained storage of globals, using recorded specialization and tuple-lowering relations, indexed once for a
* pass which asks for the storage of many: looking each one up through every specialisation and every global made
* the hot-reload manifest of a large map quadratic.
*/
public GlobalStorage globalStorage() {
return new GlobalStorage();
}

/** A snapshot of the program's globals and specialisations: valid while neither changes. */
public final class GlobalStorage {
private final Map<ImVar, List<ImVar>> copies = new IdentityHashMap<>();
private final Map<ImVar, Integer> positions = new IdentityHashMap<>();

private GlobalStorage() {
for (Element copy : specialisations.keySet()) {
if (copy instanceof ImVar variable) {
ImVar original = canonical(variable);
if (original != variable) {
copies.computeIfAbsent(original, k -> new ArrayList<>()).add(variable);
}
}
}
List<ImVar> globals = imProg.getGlobals();
for (int i = 0; i < globals.size(); i++) {
positions.putIfAbsent(globals.get(i), i);
}
}
Set<ImVar> storage = Collections.newSetFromMap(new IdentityHashMap<>());
for (ImVar root : roots) {
VarsForTupleResult tuple = varsForTupleVar.get(root);
if (tuple == null) {
storage.add(root);
} else {
tuple.allValuesStream().forEach(storage::add);

/**
* The storage of {@code source}, in the program's declaration order: with the specialisations of a source global
* which have no initializer unit of their own.
*/
public List<ImVar> of(ImVar source) {
List<ImVar> roots = new ArrayList<>();
roots.add(source);
if (canonical(source) == source) {
for (ImVar variable : copies.getOrDefault(source, List.of())) {
if (!specializationsWithOwnUnit.contains(variable)) {
roots.add(variable);
}
}
}
Set<ImVar> storage = Collections.newSetFromMap(new IdentityHashMap<>());
for (ImVar root : roots) {
VarsForTupleResult tuple = varsForTupleVar.get(root);
if (tuple == null) {
storage.add(root);
} else {
tuple.allValuesStream().forEach(storage::add);
}
}
// The identity sets are membership only; the order is the program's declaration order.
List<ImVar> result = new ArrayList<>();
for (ImVar v : storage) {
if (positions.containsKey(v)) {
result.add(v);
}
}
result.sort(Comparator.comparingInt(positions::get));
return result;
}
// Identity maps above are membership sets only; output follows the program's deterministic declaration order.
return imProg.getGlobals().stream().filter(storage::contains).toList();
}

VarsForTupleResult getVarsForTuple(ImVar v, ImType concreteStorageType) {
Expand Down
Loading
Loading