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
13 changes: 2 additions & 11 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ Notes; finished-work narrative does not.
- **Run every executing test on Lua on master CI (`-PallBackends`).** Forcing `translateAndTestLua`
after the Jass runs of every `executeProg` test that does not opt into Lua (686 tests, October 2026)
passed 645 on plain Lua and 644 with `-inline -localOptimizations`; the failures found the
generic-static, `wurstKeyOf` and type-id items below, two defects with their own fixes (compile-time
object ids, old-generic tuple arguments) and 24 tests stopped by natives missing from `wc3shim.lua`. The two Lua variants
generic-static and type-id items below, three defects with their own fixes (compile-time object ids,
old-generic tuple arguments, a direct `wurstKeyOf` call) and 24 tests stopped by natives missing from `wc3shim.lua`. The two Lua variants
cost about 300 s of test time each over the suite. Proposal: `-PallBackends` (master CI only, PR CI
unchanged) runs Lua after Jass for every executing test, `-PallBackends=full` adds the inlined
variant. A test that cannot hold on Lua says why with `.luaExempt(LuaExemption.X)` instead of
Expand All @@ -42,15 +42,6 @@ Notes; finished-work narrative does not.
`ExprTranslation.translateEquals` typing `a.iterator().next()`. Fix in `EliminateGenerics`, where the
store is split, and turn on `testLua(true).luaOnly(false)` for both tests.

- **A direct `wurstKeyOf` call answers its placeholder on Lua.** `KeyedTableTests.intKeyIsIdentity`
(`wurstKeyOf(7)` is 0) and `classInstanceKeyIsStable` (two instances share key 0) pass on the
interpreter and Jass and fail on Lua: the emitted `wurstKeyOf` is its source body, `return 0`. On Lua
the keyed-table operations are replaced as a whole (`LuaNativeLowering.lowerKeyedTables`), and the
tests' class calls itself "the Jass side", but nothing stops a program from calling the intrinsic
directly, and that placeholder answer is the failure `lowerKeyedTables` was moved to avoid. Either
lower it on Lua (the value itself for `int` and class instances, the handle id for handles) or reject
a direct call there with a diagnostic (AGENTS.md §3: no silent fallback).

- **`typeIdToTypeName`, `maxTypeId`, `instanceCount` and `maxInstanceCount` answer defaults on Lua.**
Only `EliminateClasses` implements them, on the Jass path. On Lua they compile to the generic native
fallback, which returns `""` or 0 without a diagnostic, so `NewFeatureTests.typeName`, `typeName2`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -979,19 +979,20 @@ public LuaCompilationUnit transformProgToLua() {
RemoveGarbage.removePhantomGenericStaticInitializers(getImProg(), getImTranslator());
timeTaker.endPhase();
}
// Before stack traces: that pass appends a parameter to every affected function, and on
// Lua every non-native function is affected, so the exact signatures the keyed-table
// operations are recognised by would stop matching and leave their Jass bodies on Lua, which
// key through wurstKeyOf. Before the tree shake, which then drops those replaced bodies: the
// native lowering lowers each call of wurstKeyOf it finds, and rejects one from generic code.
beginPhase(2, "lower keyed tables");
LuaNativeLowering.lowerKeyedTables(imProg, getImTranslator());
timeTaker.endPhase();
// What nothing calls (most of the imported libraries) would go through every pass below, and the garbage
// removal after the tuples is the first thing to drop it. The helpers the passes below call are pinned.
beginPhase(2, "remove unreachable functions");
TreeShaker.removeUnreachableFunctions(getImTranslator());
timeTaker.endPhase();
imTranslator.assertNoLiveErasedGenericStatic();
// Before stack traces: that pass appends a parameter to every affected function, and on
// Lua every non-native function is affected, so the exact signatures the keyed-table
// operations are recognised by would stop matching - silently leaving their Jass bodies on
// Lua, where wurstKeyOf answers with its placeholder and every element shares one key.
beginPhase(4, "lower keyed tables");
LuaNativeLowering.lowerKeyedTables(imProg, getImTranslator());
timeTaker.endPhase();

if (!runArgs.isNoDebugMessages() && runArgs.isIncludeStacktraces()) {
beginPhase(4, "add stack traces");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,17 @@ private ImVar prepareTrigger() {
return converter == null ? null : getFuncFor(converter);
}

/**
* The common.j native {@code GetHandleId}, or null when the program has no such native. The Lua lowering of a
* handle key calls it. Nothing else need have called it, so it may never have been translated (it is then appended
* to the program's functions here, as {@link #enumConverter} does) or may have been shaken out of the program (its
* parent is then null, and the caller adds it).
*/
public @Nullable ImFunction handleIdNative() {
ImFunction f = getNativeFunc("GetHandleId");
return f != null && f.isBj() && f.isNative() ? f : null;
}

private ImFunction getNativeFunc(String funcName) {
ImmutableCollection<FuncLink> wurstFunc = wurstProg.lookupFuncs(funcName);
if (wurstFunc.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@
* emitted by the normal path - so this pass only has to pick one.
*
* <p>On Lua this never runs: {@link LuaKeyedTable} replaces the keyed-table operations wholesale
* before the inliner, and the element is its own key there, so no projection exists to make.
* before the inliner, and the element is its own key there, so no projection exists to make. A
* direct call is lowered at its call site there instead ({@link LuaNativeLowering}).
*/
public final class JassKeyOfLowering {

/** The intrinsic being given a body. */
private static final String KEY_OF = "wurstKeyOf";
static final String KEY_OF = "wurstKeyOf";

/** Projections it can be rewritten to, each an ordinary function in the same package. */
private static final String KEY_OF_INT = "keyOfInt";
Expand All @@ -41,15 +42,9 @@ private JassKeyOfLowering() {

public static void transform(ImProg prog) {
for (ImFunction f : prog.getFunctions()) {
if (!isNamedKeyOf(f)) {
if (!isCheckedKeyOf(f)) {
continue;
}
if (!isKeyOf(f)) {
// The rewrite below returns an integer projection, so a declaration of another
// shape would leave the return type disagreeing with the body it now has.
throw new CompileError(f.attrTrace().attrErrorPos(),
KEY_OF + " must take exactly one parameter and return int.");
}
ImVar value = f.getParameters().get(0);
ImFunction projection =
findProjection(prog, packageOf(f), projectionFor(value.getType(), f), f);
Expand Down Expand Up @@ -79,6 +74,22 @@ public static boolean isUnloweredKeyOf(ImFunction f) {
return !f.getTypeVariables().isEmpty() && isKeyOf(f);
}

/**
* Whether {@code f} is the key projection intrinsic, which both backends rewrite to an integer
* projection. A declaration of that name with another shape is rejected: the rewrite would
* leave its return type disagreeing with the projection it now answers.
*/
static boolean isCheckedKeyOf(ImFunction f) {
if (!isNamedKeyOf(f)) {
return false;
}
if (!isKeyOf(f)) {
throw new CompileError(f.attrTrace().attrErrorPos(),
KEY_OF + " must take exactly one parameter and return int.");
}
return true;
}

private static boolean isKeyOf(ImFunction f) {
return isNamedKeyOf(f)
&& f.getParameters().size() == 1
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package de.peeeq.wurstscript.translation.imtranslation;

import de.peeeq.wurstscript.WurstOperator;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.types.TypesHelper;

Expand Down Expand Up @@ -79,10 +80,10 @@ private LuaNativeLowering() {}
* <p>Separate from {@link #transform} so it can run <b>before</b> stack-trace injection. That
* pass appends a parameter to every affected function, and on Lua every non-native function is
* affected, so the exact signatures these operations are recognised by stop matching. Nothing
* reported that: the Jass bodies simply survived onto Lua, where {@code wurstKeyOf} is never
* lowered and answers with its placeholder, so every element shared one key and a set claimed
* to hold everything. Stack traces are on by default in a release build, so that was the
* common case rather than an exotic one.
* reported that: the Jass bodies simply survived onto Lua, where {@code wurstKeyOf} then
* answered with its placeholder, so every element shared one key and a set claimed to hold
* everything. Stack traces are on by default in a release build, so that was the common case
* rather than an exotic one. Runs before the tree shake, which drops the bodies it replaced.
*
* <p>Membership becomes a table keyed directly by the element. Done before optimization rather
* than at emission because the inliner runs in between: a call inlined before an emission-time
Expand Down Expand Up @@ -206,6 +207,12 @@ public static void transform(ImProg prog, ImTranslator translator) {
public void visit(ImFunctionCall call) {
super.visit(call);
ImFunction f = call.getFunc();
// Here, before the call it is an argument of is visited: a replacement below is built
// from a copy of the arguments, which would leave a call lowered later unlowered.
if (JassKeyOfLowering.isCheckedKeyOf(f)) {
lowerKeyOf(call, translator, specialNativeStubs, deferredAdditions);
return;
}
if (isCompatGetHandleIdFunction(f)) {
if (shouldRewriteGetHandleId(call)) {
ImFunction replacement = specialNativeStubs.computeIfAbsent("__wurst_GetHandleId",
Expand Down Expand Up @@ -282,6 +289,80 @@ private ImFunction computeReplacement(ImFunction bj) {
prog.getFunctions().addAll(deferredAdditions);
}

/**
* Lowers a direct call of {@code wurstKeyOf} to the key Jass computes for it.
*
* <p>Jass gives the intrinsic a body once generic elimination has made its parameter type
* concrete ({@link JassKeyOfLowering}). Lua keeps generics erased, so the intrinsic kept its
* placeholder body there and a direct call answered 0 for every element. The call is lowered
* where it is made instead, from the type it is made with, and costs nothing: an int and a
* class instance (an integer id on both targets) are their own key, and a handle's key is its
* id, so the call becomes the {@code GetHandleId} call Lua makes of a handle of its type. The
* keyed-table operations, whose Jass bodies key through the intrinsic, are replaced as a whole
* before the tree shake, which takes those bodies away.
*
* <p>A type with no stable integer key is rejected, as on Jass, and so is a call from generic
* code: Lua erases its element type, so there is nothing to choose the key by.
*/
private static void lowerKeyOf(ImFunctionCall call, ImTranslator translator,
Map<String, ImFunction> specialNativeStubs, List<ImFunction> deferredAdditions) {
ImExpr value = call.getArguments().get(0);
ImType type = call.getTypeArguments().size() == 1
? call.getTypeArguments().get(0).getType()
: value.attrTyp();
if (TypesHelper.isIntType(type) || type instanceof ImClassType) {
value.setParent(null);
call.replaceBy(value);
return;
}
if (type instanceof ImTypeVarRef || type instanceof ImAnyType) {
throw new CompileError(call.attrTrace().attrErrorPos(),
JassKeyOfLowering.KEY_OF + " needs a concrete element type on Lua, but this call is made with "
+ typeName(type) + ": generic code is erased on Lua, so no key can be chosen for it. Call "
+ JassKeyOfLowering.KEY_OF + " where the element type is known.");
}
if (!isHandleType(type) || isSimpleType(type, "code")) {
throw new CompileError(call.attrTrace().attrErrorPos(),
JassKeyOfLowering.KEY_OF + " cannot key " + typeName(type) + " on Lua: only int, class "
+ "instances and handles have a stable integer key.");
}
ImFunction getHandleId = translator.handleIdNative();
if (getHandleId == null) {
throw new CompileError(call.attrTrace().attrErrorPos(),
JassKeyOfLowering.KEY_OF + " keys a handle by its id, but the program declares no native GetHandleId.");
}
// The same choice as for a call of GetHandleId itself, so both give a handle the same id.
ImFunction target;
if (usesLuaObjectIdentityHandleId(value.attrTyp())) {
target = specialNativeStubs.computeIfAbsent("__wurst_GetHandleId",
name -> createNativeStub(name, getHandleId));
} else {
target = getHandleId;
}
// A function nothing called before may have been shaken out of the program (a native which was never
// translated is added by the translator, behind the traversal's end).
if (target.getParent() == null && !deferredAdditions.contains(target)) {
deferredAdditions.add(target);
}
value.setParent(null);
call.replaceBy(JassIm.ImFunctionCall(call.attrTrace(), target, JassIm.ImTypeArguments(),
JassIm.ImExprs(value), false, CallType.NORMAL));
}

private static boolean isSimpleType(ImType t, String name) {
return t instanceof ImSimpleType st && name.equals(st.getTypename());
}

private static String typeName(ImType t) {
if (t instanceof ImSimpleType st) {
return st.getTypename();
}
if (t instanceof ImTypeVarRef ref) {
return ref.getTypeVariable().getName();
}
return t.toString();
}

/**
* An erased generic value is normalised with {@code __wurst_ensureInt} and friends when it
* reaches a concrete primitive context, because erased storage can hold nil for a primitive.
Expand Down
Loading
Loading