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
5 changes: 3 additions & 2 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,9 @@ Notes; finished-work narrative does not.
Multiplayer only through a synchronised channel is a later stage in the design note.
- **Lua hot reload: remaining daily-use work.** Each correctness change needs a failing test first.
- Callback bodies now use source-callable ownership for native `code` callbacks as well as class closures. Stable
event arguments anchor distinct registrations. Independent, unique direct registrations added to existing package
init blocks run as complete source-owned units, once, without repeating previous setup. Computed/local operands,
event arguments anchor distinct registrations, including qualified static calls such as `EventListener.add` and
`DamageEvent.addListener`. Independent, unique direct registrations added to existing package
init blocks run as complete source-owned units, once, without repeating previous setup. Instance receivers, computed/local operands,
generic/duplicate registrations and existing live capture/state migration remain separate work. Test behavioral
effects of CF/ZD edits; payload acceptance and warning counts alone do not establish whole-commit coverage.
- An anonymous order group
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,15 +351,25 @@ private String hotReloadCallSites() {
StringBuilder sites = new StringBuilder();
Element argument = e;
for (Element parent = e.getParent(); parent != null; argument = parent, parent = parent.getParent()) {
if (!(parent instanceof Arguments args) || !(parent.getParent() instanceof ExprFunctionCall call)) continue;
if (!(parent instanceof Arguments args) || !(parent.getParent() instanceof FunctionCall call)) continue;
if (!(argument instanceof ExprClosure) || args.stream().allMatch(value -> value instanceof ExprClosure)) continue;
String key = registrationIdentity(call, tr);
if (key != null) sites.append("_site").append(key).append("_argument").append(args.indexOf(argument));
}
return sites.toString();
}

static String registrationIdentity(ExprFunctionCall call, ImTranslator tr) {
static String registrationIdentity(FunctionCall call, ImTranslator tr) {
if (call instanceof ExprMemberMethod member) {
// A static qualifier names the resolved declaration, not a runtime receiver. Dynamic receivers and
// generic bindings need their own identities; do not guess those from the spelling of the qualifier.
if (!(member instanceof ExprMemberMethodDot)
|| !(member.getLeft().attrTyp() instanceof WurstTypeNamedScope qualifier)
|| !qualifier.isStaticRef() || !qualifier.getTypeParameters().isEmpty()
|| call.attrImplicitParameter() instanceof Expr
|| (call.attrFuncDef() instanceof AstElementWithTypeParameters generic
&& !generic.getTypeParameters().isEmpty())) return null;
}
if (!call.getTypeArgs().isEmpty() || !tr.getFuncFor(call.attrFuncDef()).getTypeVariables().isEmpty()) return null;
StringBuilder key = new StringBuilder(hotReloadOwnerIdentity(call.attrFuncDef(), tr));
boolean callback = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@ private HotReloadInitActions() { }

static void translate(InitBlock block, ImTranslator translator, ImFunction init) {
Map<String, Integer> occurrences = new LinkedHashMap<>();
Map<ExprFunctionCall, String> identities = new IdentityHashMap<>();
Map<FunctionCall, String> identities = new IdentityHashMap<>();
// Equal registrations in separate init blocks are ambiguous too. Keep such groups in the ordinary init.
((WPackage) block.attrNearestPackage()).accept(new de.peeeq.wurstscript.ast.Element.DefaultVisitor() {
@Override public void visit(InitBlock candidate) {
for (WStatement statement : candidate.getBody()) {
if (!(statement instanceof ExprFunctionCall call) || readsOutsideLocal(call)) continue;
if (!(statement instanceof FunctionCall call) || readsOutsideLocal(call)) continue;
String key = ClosureTranslator.registrationIdentity(call, translator);
if (key != null) { identities.put(call, key); occurrences.merge(key, 1, Integer::sum); }
}
}
});
for (WStatement statement : block.getBody()) {
String key = statement instanceof ExprFunctionCall call ? identities.get(call) : null;
String key = statement instanceof FunctionCall call ? identities.get(call) : null;
if (key == null || occurrences.get(key) != 1) {
init.getBody().addAll(translator.translateStatements(init, List.of(statement)));
continue;
Expand All @@ -36,7 +36,7 @@ static void translate(InitBlock block, ImTranslator translator, ImFunction init)
}
}

private static boolean readsOutsideLocal(ExprFunctionCall call) {
private static boolean readsOutsideLocal(FunctionCall call) {
boolean[] outside = {false};
call.accept(new de.peeeq.wurstscript.ast.Element.DefaultVisitor() {
private void check(NameDef declaration) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,8 +333,8 @@ public List<String> getReasons() {
*/
static Manifest install(LuaTranslator tr, Map<LuaFunction, ImFunction> reloadable, List<ImFunction> packageInits,
Set<ImFunction> entries, String compilerVersion) {
// Older scripts did not record completed action units; applying these units to one would repeat setup.
compilerVersion += "+hotreload-init-actions-v1";
// Older scripts did not record every supported action kind; applying an unmarked unit would repeat setup.
compilerVersion += "+hotreload-init-actions-v2";
Set<ImFunction> inits = Collections.newSetFromMap(new IdentityHashMap<>());
inits.addAll(packageInits);
Map<ImFunction, String> initNames = new IdentityHashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ public void hotReloadRegistrationUnitsAndCallbackSitesAreDeterministic() {
assertEquals(compileLuaHotReloadManifest(false, args, registrations, main), first);
}

@Test
public void hotReloadQualifiedStaticRegistrationsAreDeterministic() {
CU registrations = compilationUnit("Events.wurst", "package Events", "public interface Callback",
" function run() returns int", "Callback array saved", "public class Registry",
" static function add(int event, Callback cb)", " saved[event] = cb");
CU main = compilationUnit("Main.wurst", "package Main", "import Events", "init",
" Registry.add(2, () -> 20)", " Registry.add(3, () -> 30)");
RunArgs args = new RunArgs().with("-lua", "-luaHotReload", "-stacktraces");
var first = compileLuaHotReloadManifest(false, args, registrations, main);
assertEquals(2L, first.statements().stream().filter(statement -> statement.kind().equals("action")).count());
assertEquals(compileLuaHotReloadManifest(false, args, main, registrations), first);
assertEquals(compileLuaHotReloadManifest(false, args, registrations, main), first);
}

@Test
public void hotReloadUnreadSnapshotRootsAreDeterministic() {
CU values = compilationUnit("Values.wurst", "package Values", "public class Node", " public int value",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1237,6 +1237,104 @@ public void eventArgumentsAnchorExistingCapturedCallbacksAcrossInsertionsAndBody
test().testLua(true).executeProg().luaHotReload(eventCallbacks(true)).lines(eventCallbacks(false));
}

@Test
public void qualifiedStaticCallbackSitesKeepCapturedValuesAcrossInsertions() {
test().testLua(true).executeProg().luaHotReload(qualifiedRegistrations(eventCallbacks(true)))
.lines(qualifiedRegistrations(eventCallbacks(false)));
}

@Test
public void qualifiedStaticRegistrationsRunOnceWithoutRepeatingOldSetup() {
test().testLua(true).executeProg().luaHotReload(qualifiedRegistrations(initEventCallbacks(true)))
.lines(qualifiedRegistrations(initEventCallbacks(false)));
}

@Test
public void qualifiedStaticNativeRegistrationsKeepEditedBodies() {
test().testLua(true).executeProg().luaHotReload(qualifiedRegistrations(nativeEventCallbacks(true)))
.lines(qualifiedRegistrations(nativeEventCallbacks(false)));
}

@Test
public void qualifiedStaticNamedCallbacksRegisterOnce() {
test().testLua(true).executeProg().luaHotReload(qualifiedRegistrations(namedNativeEventCallbacks(true)))
.lines(qualifiedRegistrations(namedNativeEventCallbacks(false)));
}

@Test
public void qualifiedStaticRegistrationsPreserveNormalBackendSemantics() {
String[] source = java.util.Arrays.stream(qualifiedRegistrations(initEventCallbacks(true)))
.filter(line -> !line.equals(" hotReload()")).toArray(String[]::new);
test().testLua(true).luaOnly(false).executeProg().lines(source);
}

@DataProvider
public Object[][] instanceRegistrationCases() {
return new Object[][] {{false}, {true}};
}

@Test(dataProvider = "instanceRegistrationCases")
public void instanceRegistrationReceiversRemainOrdinaryInit(boolean constant) throws Exception {
String[] before = {"package Main", "interface Callback", " function run() returns int",
"Callback array saved", "class Events", " function register(int event, Callback cb)",
" saved[event] = cb", (constant ? "constant " : "") + "Events events = new Events",
"init", " events.register(2, () -> 2)"};
var after = manifest(concat(before, new String[] {" events.register(1, () -> 1)"}));
assertFalse(after.statements().stream().anyMatch(statement -> statement.kind().equals("action")));
var payload = LuaHotReload.payload(manifest(before), after, LuaHotReload.History.NONE, 1);
assertTrue(payload.warnings().toString(), payload.warnings().stream().anyMatch(w -> w.contains("Changed package init")));
}

@DataProvider
public Object[][] genericStaticRegistrationCases() {
return new Object[][] {{"class Events<T>", "Events<int>", ""}, {"class Events<T:>", "Events<int>", ""},
{"class Events", "Events", "<T>"}, {"class Events", "Events", "<T:>"}};
}

@Test
public void qualifiedAndUnqualifiedStaticCallsKeepTheSameCallbackIdentity() {
test().testLua(true).executeProg().luaHotReload(staticCallSpelling(true)).lines(staticCallSpelling(false));
}

private static String[] staticCallSpelling(boolean edited) {
String call = edited ? "register" : "Events.register";
return new String[] {"package Main", "native testSuccess()", "native testFail(string msg)", "native hotReload()",
"interface Callback", " function run() returns int", "Callback array saved", "class Events",
" static function register(int event, Callback cb)", " saved[event] = cb",
" static function setup(int seed)", edited ? " register(1, () -> seed + 1)" : " skip",
" " + call + "(2, () -> seed + " + (edited ? "20" : "2") + ")",
" " + call + "(3, () -> seed + 3)", "init", " Events.setup(7)", " let kept = saved[2]",
" hotReload()", " if kept.run() != 27 or saved[3].run() != 10",
" testFail(\"static qualification changed callback identity or captured state\")", " testSuccess()"};
}

@Test(dataProvider = "genericStaticRegistrationCases")
public void genericStaticRegistrationsRemainOrdinaryInit(String owner, String qualifier, String parameters) {
String[] source = {"package Main", "interface Callback", " function run() returns int", "Callback saved",
owner, " static function register" + parameters + "(int event, Callback cb)", " saved = cb",
"init", " " + qualifier + ".register" + (parameters.isEmpty() ? "" : "<int>") + "(1, () -> 1)"};
assertFalse(manifest(source).statements().stream().anyMatch(statement -> statement.kind().equals("action")));
}

/** The same behavioral fixtures through EventListener.add-style static methods. */
private static String[] qualifiedRegistrations(String[] source) {
var result = new java.util.ArrayList<String>();
boolean registrationBody = false;
for (String line : source) {
if (line.startsWith("function register(")) {
result.add("class Events");
result.add(" static " + line);
registrationBody = true;
} else if (registrationBody && line.startsWith(" ")) {
result.add(" " + line);
} else {
registrationBody = false;
result.add(line.replace("register(", "Events.register("));
}
}
return result.toArray(String[]::new);
}

private static String[] eventCallbacks(boolean edited) {
return new String[] {"package Test", "native testSuccess()", "native testFail(string msg)", "native hotReload()",
"interface Callback", " function run() returns int", "Callback array saved",
Expand Down Expand Up @@ -1379,11 +1477,22 @@ public void removedActionsFromEarlierPayloadsWarnOnlyIfTheyRan(boolean newPackag
assertEquals(output, skipFirst ? 2 : 3, occurrences(output, "true " + (skipFirst ? 1 : 2) + " nil"));
}

@Test
public void scriptsWithoutQualifiedStaticActionMarkersRequireANewSession() {
var current = manifest(qualifiedRegistrations(initEventCallbacks(false)));
var legacy = new LuaHotReload.Manifest(current.abi(),
current.compilerVersion().replace("+hotreload-init-actions-v2", "+hotreload-init-actions-v1"),
current.functions(), current.statements(), current.bindings(), current.initOrder());
var rejected = expectThrows(LuaHotReload.Rejected.class,
() -> LuaHotReload.payload(legacy, current, LuaHotReload.History.NONE, 1));
assertTrue(rejected.getMessage(), rejected.getMessage().contains("another compiler"));
}

@Test
public void scriptsWithoutInitializationActionMarkersRequireANewSession() {
var current = manifest(initEventCallbacks(false));
var legacy = new LuaHotReload.Manifest(current.abi(),
current.compilerVersion().replace("+hotreload-init-actions-v1", ""), current.functions(), current.statements(),
current.compilerVersion().replace("+hotreload-init-actions-v2", ""), current.functions(), current.statements(),
current.bindings(), current.initOrder());
var rejected = expectThrows(LuaHotReload.Rejected.class,
() -> LuaHotReload.payload(legacy, current, LuaHotReload.History.NONE, 1));
Expand Down
10 changes: 6 additions & 4 deletions docs/LUA_HOT_RELOAD.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,19 +100,20 @@ this is not completion of the fully incremental design. Real-map probes and timi
### Adding and editing event registrations

Hot-reload callback identities include their source callable and named bindings for both class closures and native
`code` callbacks. Direct non-generic calls with stable non-callback arguments also use the resolved target and those
`code` callbacks. Direct free-function calls and qualified static method calls with stable non-callback arguments use the resolved target and those
arguments as anchors. Handlers registered for distinct event constants are separate identities, so inserting one
and editing another need not shift existing callbacks. Repeated calls with indistinguishable operands still use the
conservative order-group checks below.

Void interface/class callbacks retain the declared void ABI even when their expression body computes a value;
changing such an expression into a guarded block preserves the callback identity and discards only the unused result.

Unique, independent direct callback calls (inline closures or named function references) at the top level of package `init` blocks become source-owned initialization
Unique, independent direct callback calls (inline closures or named function references), including qualified static calls such as
`EventListener.add(EVENT_PLAYER_UNIT_CONSTRUCT_START, ...)` and `DamageEvent.addListener(102, ...)`, at the top level of package `init` blocks become source-owned initialization
actions in hot-reload builds. A new action runs once in the live map, in package dependency order, without repeating
existing setup. Each complete statement owns its closure construction and temporaries; the backend does not extract
registration calls from flattened code. Calls that depend on locals outside the statement, computed/mutable arguments,
generic calls and duplicate action identities remain ordinary init code and retain restart warnings. Actions run
instance receivers (even constant instances), generic qualifiers/callees and duplicate action identities remain ordinary init code and retain restart warnings. Actions run
against current live state, not a reconstruction of startup state.

Completed actions are recorded by the running script. Repeated/cumulative payloads do not repeat them; a failed action
Expand All @@ -124,7 +125,8 @@ these changes do not relax that guard.
Package dispatch emitted by the compiler is tracked by its producer, so a new package whose initialization the payload
already applies no longer produces a misleading changed-`main` warning. Actual entry-point edits and changes to the
relative initialization order of existing packages still warn. The action-completion protocol requires a **new game
session after upgrading from an older compiler**, even if the compiler's version label is unchanged.
session after upgrading from an older compiler**, even if the compiler's version label is unchanged. Earlier action-aware compilers
that tracked only free-function calls also require a new session before using qualified static registrations.

### Names from identities

Expand Down
Loading