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
9 changes: 9 additions & 0 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ Notes; finished-work narrative does not.

## Open

- **Broaden modeled backend source generation and add shrinking.** The erased generic-store
dispatch regression passed interpreter-only tests; executing generated Lua exposed the split
backing stores. `GenericStoreGeneratedTests` now checks fixed seeds against a Java model through
Jass and Lua, varying generic owners, tuple storage, inheritance, dispatch, closures and destruction.
Extend generation to nested containers, old/new-generic boundaries and bounded dispatch. Run larger
seed campaigns separately from PR checks, preserve the failing seed/source/options, and minimize
failures into ordinary regressions. Add metamorphic checks that replace interface calls with
concrete calls while keeping observable behavior unchanged.

- **Represent raw Lua helper bindings structurally.** Lua name compression now runs after backend
lowering so it includes descriptors, field storage and resolved dispatch slots. `LuaLiteral` still
embeds helper bindings and references as text (for example the object/string index helpers), so
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imtojass.ImAttrType;
import de.peeeq.wurstscript.translation.imtojass.TypeRewriteMatcher;
import de.peeeq.wurstscript.translation.lua.translation.RemoveGarbage;
import de.peeeq.wurstscript.types.TypesHelper;
import io.vavr.control.Either;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -41,6 +42,9 @@ public class EliminateGenerics {
Collections.newSetFromMap(new IdentityHashMap<>());
private final Set<ImFunction> scannedFixedStaticCallees =
Collections.newSetFromMap(new IdentityHashMap<>());
private final Set<ImMethod> scannedFixedStaticMethods =
Collections.newSetFromMap(new IdentityHashMap<>());
private @Nullable Set<ImMethod> dispatchReachableMethods;
private final Table<ImFunction, GenericTypes, ImFunction> specializedFunctions = HashBasedTable.create();
/** The class each function was moved out of, for calls which name their target without a receiver. */
private final Map<ImFunction, ImClass> functionOwners = new IdentityHashMap<>();
Expand Down Expand Up @@ -252,6 +256,8 @@ private static ImExpr defaultValueFor(ImType type) {


private void collectGenericNewRoots() {
scannedFixedStaticMethods.clear();
dispatchReachableMethods = null;
classByFunction = null;
specializationRelevantNodes = new IdentityHashMap<>();
methodAnswers = new IdentityHashMap<>();
Expand Down Expand Up @@ -765,11 +771,7 @@ private void collectGenericNewUse(ImMethodCall call) {
forgetAnswersIfCallChanged(call, dependedOnCaller);
boolean needsSpecialization = methodNeedsSpecializationAnswer(method);
if (!shouldSpecializeTupleArguments(call.getTypeArguments()) && !needsSpecialization) {
if (!call.getTypeArguments().isEmpty()
&& !typeArgumentsContainTypeVariable(call.getTypeArguments())
&& method.getImplementation() != null) {
recordFixedErasedStaticAllocations(method.getImplementation());
}
recordFixedErasedStaticAllocations(method);
return;
}
if (!call.getTypeArguments().isEmpty()
Expand All @@ -778,6 +780,29 @@ private void collectGenericNewUse(ImMethodCall call) {
}
}

/**
* Erased dispatch still reaches concrete operations inside every possible implementation.
* A nongeneric interface carries no class arguments, even when its implementation belongs to
* a generic class. Skipping that implementation can make one method write an erased static
* while another method on the same object reads its specialised counterpart.
*/
private void recordFixedErasedStaticAllocations(ImMethod method) {
if (dispatchReachableMethods == null) {
dispatchReachableMethods = RemoveGarbage.reachableMethods(prog, translator);
}
Deque<ImMethod> remaining = new ArrayDeque<>();
remaining.add(method);
while (!remaining.isEmpty()) {
ImMethod current = remaining.removeFirst();
if (!scannedFixedStaticMethods.add(current)) continue;
if (!dispatchReachableMethods.contains(current)) continue;
if (current.getImplementation() != null) {
recordFixedErasedStaticAllocations(current.getImplementation());
}
remaining.addAll(current.getSubMethods());
Comment thread
Frotty marked this conversation as resolved.
Resolved
}
}

/**
* Whether a call is short of the type arguments belonging to the receiver's class.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
import de.peeeq.wurstscript.validation.NamePreservation;


import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
Expand Down Expand Up @@ -149,6 +150,15 @@ public static void removeGarbage(ImProg prog, ImTranslator translator) {

}

/**
* Read-only dispatch reachability for targeted Lua specialization. Query again after the
* specialization graph changes: scanning an uninstantiated override can activate a static
* initializer which would otherwise never run.
*/
public static Set<ImMethod> reachableMethods(ImProg prog, ImTranslator translator) {
return collectUsed(prog, translator).getMethods();
}

private static Used collectUsed(ImProg prog, ImTranslator translator) {
return collectUsed(prog, translator, Collections.emptySet());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@
*/
public class DeterministicChecks extends WurstScriptTest {

@Test
public void erasedDispatchConcreteStoresAreDeterministic() throws IOException {
CU program = compilationUnit("Stores.wurst", GenericStoreGeneratedTests.program(7));
CU extra = compilationUnit("Extra.wurst", "package Extra", "native consume(int value)",
"init", " consume(7)");
String name = "erasedDispatchStores";
testNamed(name).testLua(true).inline().localOptimizations().compilationUnits(program, extra);
String forward = compiledLua(name);
testNamed(name).testLua(true).inline().localOptimizations().compilationUnits(extra, program);
assertEquals(compiledLua(name), forward);
}

@Test
public void compressedLuaDescriptorsAreIdenticalAcrossCompilations() throws IOException {
String name = "compressedLuaDescriptors";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
package tests.wurstscript.tests;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Random;

/** Seeded source programs checked against a Java model, through the emitted backends. */
public class GenericStoreGeneratedTests extends WurstScriptTest {
@DataProvider
public Object[][] seeds() {
var cases = new ArrayList<Object[]>();
for (int seed = 0; seed < 12; seed++) {
for (boolean optimized : new boolean[]{false, true}) cases.add(new Object[]{seed, optimized});
}
return cases.toArray(Object[][]::new);
}

@Test(dataProvider = "seeds")
public void modeledStoreOperations(int seed, boolean optimized) {
var config = testNamed("storeSeed" + seed + "Optimized" + optimized)
.testLua(true).luaOnly(false).executeProg();
if (optimized) config.optimize().inline().localOptimizations();
config.lines(program(seed).split("\n"));
}

@Test(dataProvider = "seeds")
public void deadDispatchDoesNotAddStaticInitializerEffects(int seed, boolean optimized) {
int liveCount = 1 + new Random(seed).nextInt(3);
StringBuilder allocations = new StringBuilder();
String[] types = {"int", "string", "bool"};
for (int i = 0; i < liveCount; i++) {
allocations.append(" let store").append(i).append(" = new Store<").append(types[i]).append(">()\n");
}
// The generic erased initializer is specific to Lua; the operation model above checks Jass too.
String source = """
package Test
native testSuccess()
native testFail(string message)
int initialized = 0
function initialize<T:>() returns T
initialized++
return null
class Store<T:>
static T value = initialize<T>()
interface Runner
function run()
class Live implements Runner
override function run()
class Dead<T:> implements Runner
override function run()
let store = new Store<real>()
class DeadChild<U:> extends Dead<U>
init
%s
Runner runner = new Live()
runner.run()
if initialized == %d
testSuccess()
else
testFail("dead dispatch changed static initializer effects")
""".formatted(allocations, liveCount);
var config = testNamed("staticSeed" + seed + "Optimized" + optimized).testLua(true).executeProg();
if (optimized) config.optimize().inline().localOptimizations();
config.lines(source.split("\n"));
}

static String program(int seed) {
StringBuilder source = new StringBuilder("""
package Test
native testSuccess()
native testFail(string message)
int total = 0
tuple Pair(int x, int y)
interface Action
function run()
function invoke(Action action)
action.run()
destroy action
class Store<T:>
static T array values
static int next = 0
int slot
construct()
slot = next
next++
function put(T value)
values[slot] = value
function read() returns T
return values[slot]
function pop() returns T
let value = values[slot]
values[slot] = null
return value
interface Source
function put(Observer value)
function changed()
function pop() returns Observer
class Observer
function put(Observer value)
function changed()
function pop() returns Observer
return null
class Subscriber extends Observer
int weight
construct(int weight)
this.weight = weight
override function changed()
total += weight
class Box<T:> extends Observer implements Source
T value
Store<Observer> entries = new Store<Observer>()
construct(T initial)
value = initial
override function put(Observer value)
entries.put(value)
override function changed()
let value = entries.read()
if value != null
value.changed()
override function pop() returns Observer
return entries.pop()
ondestroy
let value = entries.pop()
if value != null
value.changed()
destroy entries
class Child<T:> extends Box<T>
construct(T value)
super(value)
init
let box0 = new Box<int>(7)
let box1 = new Box<string>("one")
let box2 = new Child<int>(9)
let box3 = new Box<Pair>(Pair(1, 2))
Source source0 = box0
Source source1 = box1
Source source2 = box2
Source source3 = box3
Observer observer0 = box0
Observer observer1 = box1
Observer observer2 = box2
Observer observer3 = box3
""");
Random random = new Random(0x53544f5245L + seed);
int[] contents = new int[4];
int expected = 0;
for (int operation = 0; operation < 32; operation++) {
int box = random.nextInt(contents.length);
String receiver = new String[]{"box", "source", "observer"}[random.nextInt(3)] + box;
switch (random.nextInt(4)) {
case 0 -> {
int weight = random.nextInt(99) + 1;
source.append(" ").append(receiver).append(".put(new Subscriber(").append(weight).append("))\n");
contents[box] = weight;
}
case 1 -> {
source.append(" ").append(receiver).append(".changed()\n");
expected += contents[box];
}
case 2 -> {
source.append(" let removed").append(operation).append(" = ").append(receiver).append(".pop()\n")
.append(" if removed").append(operation).append(" != null\n")
.append(" removed").append(operation).append(".changed()\n");
expected += contents[box];
contents[box] = 0;
}
default -> {
source.append(" invoke(() -> ").append(receiver).append(".changed())\n");
expected += contents[box];
}
}
source.append(" if total != ").append(expected).append("\n")
.append(" testFail(\"seed ").append(seed).append(" operation ").append(operation).append("\")\n");
}
for (int box = 0; box < contents.length; box++) {
source.append(" destroy box").append(box).append('\n');
expected += contents[box];
}
source.append(" if total == ").append(expected).append("\n testSuccess()\n")
.append(" else\n testFail(\"destruction total\")\n");
return source.toString();
}
}
Loading
Loading