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
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,7 @@ public static LuaExpr translate(ImAlloc e, LuaTranslator tr) {
return LuaAst.LuaExprFunctionCall(tr.objectAlloc(),
LuaAst.LuaExprlist(LuaAst.LuaExprVarAccess(classVar)));
}
LuaMethod m = tr.luaClassInitMethod.getFor(c);
return LuaAst.LuaExprMethodCall(
LuaAst.LuaExprVarAccess(classVar),
m,
LuaAst.LuaExprlist()
);
return LuaAst.LuaExprFunctionCall(tr.luaClassAllocator.getFor(c), LuaAst.LuaExprlist());
}

public static LuaExpr translate(ImBoolVal e, LuaTranslator tr) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,11 +326,15 @@ descriptor, isDestroyDispatchMethod(method)
return LuaAst.LuaExprFunctionCallE(target, args);
}

GetAForB<ImClass, LuaMethod> luaClassInitMethod = new GetAForB<ImClass, LuaMethod>() {
/**
* The allocator of a class with one of its own ({@link #allocatesOnly}): a plain function, not a method of the
* class table. An allocation then calls it directly, while a method would cost each allocation a lookup in the
* class table and pass the table as an argument nothing reads.
*/
GetAForB<ImClass, LuaFunction> luaClassAllocator = new GetAForB<ImClass, LuaFunction>() {
@Override
public LuaMethod initFor(ImClass a) {
LuaExprVarAccess receiver = LuaAst.LuaExprVarAccess(luaClassVar.getFor(a));
return LuaAst.LuaMethod(receiver, uniqueName("create"), LuaAst.LuaParams(), LuaAst.LuaStatements());
public LuaFunction initFor(ImClass a) {
return LuaAst.LuaFunction(uniqueName(a.getName() + "_create"), LuaAst.LuaParams(), LuaAst.LuaStatements());
}
};

Expand Down Expand Up @@ -1528,9 +1532,9 @@ private void translateClass(ImClass c) {
// following the code at http://lua-users.org/wiki/InheritanceTutorial
LuaVariable classVar = luaClassVar.getFor(c);
// a class which only allocates has no allocator of its own (allocatesOnly)
LuaMethod initMethod = allocatesOnly(c) ? null : luaClassInitMethod.getFor(c);
if (initMethod != null) {
luaModel.add(initMethod);
LuaFunction allocator = allocatesOnly(c) ? null : luaClassAllocator.getFor(c);
if (allocator != null) {
luaModel.add(allocator);
}

// translate functions
Expand All @@ -1539,8 +1543,8 @@ private void translateClass(ImClass c) {
luaFunc.getFor(f).setName(uniqueName(c.getName() + "_" + classFunctionName(f)));
}

if (initMethod != null) {
createClassInitFunction(c, classVar, initMethod);
if (allocator != null) {
createClassInitFunction(c, classVar, allocator);
}
}

Expand Down Expand Up @@ -1593,9 +1597,8 @@ private String classFunctionName(ImFunction f) {
return f.getName();
}

private void createClassInitFunction(ImClass c, LuaVariable classVar, LuaMethod initMethod) {
// create init function:
LuaStatements body = initMethod.getBody();
private void createClassInitFunction(ImClass c, LuaVariable classVar, LuaFunction allocator) {
LuaStatements body = allocator.getBody();
LuaVariable newInst = addAllocation(body, LuaAst.LuaExprVarAccess(classVar));
// The defaults the optimiser did not remove at some allocation of this class (LuaFieldDefaults), and the
// table an array field needs per object, which only the backend can make.
Expand Down Expand Up @@ -1763,17 +1766,6 @@ private void createMethods(ImClass c, LuaVariable classVar) {
slotToImpl.put("__wurst_destroy", destroyImplementation);
}

// Constructor helpers (create, create1, ...) live in the same class-table
// key namespace as dispatch slots. If a slot would overwrite this class's
// constructor at main() time, rename the constructor instead (allocation
// sites reference the shared LuaMethod object, so a rename is safe here).
if (!allocatesOnly(c)) {
LuaMethod initMethod = luaClassInitMethod.getFor(c);
while (slotToImpl.containsKey(initMethod.getName())) {
initMethod.setName(uniqueName(c.getName() + "_create"));
}
}

for (Map.Entry<String, ImMethod> e : slotToImpl.entrySet()) {
ImMethod impl = e.getValue();
if (impl == null || impl.getImplementation() == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,7 @@ public void testCompiletimeObjectKeepsIdAfterDroppedObject() throws IOException
// id the kept object stored at compile time is the one it gets.
String lua = compiledLua("testCompiletimeObjectKeepsIdAfterDroppedObject");
java.util.regex.Matcher replay = java.util.regex.Pattern.compile(
"__wurst_objectFreeCount = 0\\s+__wurst_objectMax = (\\d+)\\s+(\\w+) = A:create\\(\\)\\s+"
"__wurst_objectFreeCount = 0\\s+__wurst_objectMax = (\\d+)\\s+(\\w+) = A_create\\d*\\(\\)\\s+"
+ "A_storedId_storage\\[\\2\\] = (\\d+)").matcher(lua);
assertTrue(replay.find(), lua);
assertEquals(Integer.parseInt(replay.group(3)), Integer.parseInt(replay.group(1)) + 1, lua);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ private static String allocatedFields(String compiled, String classPattern) {
}

private static @Nullable String allocatedFieldsOrNull(String compiled, String classPattern) {
Matcher allocation = Pattern.compile("function " + classPattern + ":create\\d*\\(\\)\\s*\\R"
Matcher allocation = Pattern.compile("function " + classPattern + "_create\\d*\\(\\)\\s*\\R"
+ "(.*?)\\R\\s*return new_inst\\s*\\Rend", Pattern.DOTALL).matcher(compiled);
if (!allocation.find()) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7137,16 +7137,55 @@ public void classesWhichOnlyAllocateShareOneAllocator() throws IOException {
" testSuccess()");
String compiled = compiledLua("classesWhichOnlyAllocateShareOneAllocator");
assertEquals("the shared allocator and one for each class which keeps its own:\n" + compiled,
1 + java.util.regex.Pattern.compile("(?m)^function \\w+:create\\d*\\(").matcher(compiled).results().count(),
1 + java.util.regex.Pattern.compile("(?m)^function \\w+_create\\d*\\(\\) ").matcher(compiled).results().count(),
countOccurrences(compiled, "if (__wurst_objectFreeCount == 0) then"));
assertTrue(compiled, compiled.contains("local function __wurst_allocObject(class) \n"));
assertFalse(compiled, compiled.contains("Circle:create"));
assertFalse(compiled, compiled.contains("Circle_create"));
assertTrue(compiled, compiled.contains("__wurst_allocObject(Circle)"));
String grid = topLevelFunctionBodyWithPrefix(compiled, "Grid:create");
String grid = topLevelFunctionBodyWithPrefix(compiled, "Grid_create");
assertTrue("the array field's table is made on allocation:\n" + grid, grid.contains("Grid_cells_storage[new_inst]"));
assertFalse("which allocates in place:\n" + grid, grid.contains("__wurst_allocObject"));
}

/**
* A class with an allocator of its own gets it as a plain function, which an allocation calls directly. As a
* method of the class table, {@code Grid:create()}, each allocation looked the allocator up in the table and
* passed the table, which the allocator never read.
*/
@Test
public void ownAllocatorIsAPlainFunction() throws IOException {
test().testLua(true).luaOnly(false).executeProg().lines(
"package Test",
"native testSuccess()",
"class Grid",
" int array[4] cells",
" function update() returns int",
" return 7",
"class Wide extends Grid",
" int array[2] more",
" override function update() returns int",
" return 8",
"init",
" let g = new Grid()",
" g.cells[1] = 5",
" destroy g",
" Grid w = new Wide()",
" let h = new Grid()",
" w.cells[2] = 3",
" h.cells[2] = 4",
" if w castTo int != h castTo int and w.cells[2] == 3 and h.cells[2] == 4 and w.update() == 8",
" and h.update() == 7 and w instanceof Wide and not (h instanceof Wide)",
" testSuccess()");
String compiled = compiledLua("ownAllocatorIsAPlainFunction");
assertFalse("no allocator is a method of its class table:\n" + compiled, compiled.contains(":create"));
String grid = topLevelFunctionBodyWithPrefix(compiled, "Grid_create");
assertTrue("the allocator records its class:\n" + grid, grid.contains("__wurst_objectClass[new_inst] = Grid\n"));
assertTrue("an allocation calls it directly:\n" + compiled,
java.util.regex.Pattern.compile("= Grid_create\\d*\\(\\)").matcher(compiled).find());
assertTrue("an allocation calls it directly:\n" + compiled,
java.util.regex.Pattern.compile("= Wide_create\\d*\\(\\)").matcher(compiled).find());
}

/**
* A global is given its default by the bootstrap which main runs first, and a global Lua has not seen reads as
* nil, so the script declares none of them as nil at its top: each declaration was a table write at load which
Expand Down Expand Up @@ -8531,9 +8570,12 @@ public void closureMethodsWithUnderscoresKeepTheirSemanticNames() throws IOExcep
luaTablesWithPrefix(lua, "Under_pass"));
assertEquals(java.util.Arrays.asList("Hidden_passHidden_Test", "Hidden_passHidden_Test1"),
luaTablesWithPrefix(lua, "Hidden_pass"));
assertEquals(java.util.Arrays.asList("Hidden_passHidden_Test__hidden", "Hidden_passHidden_Test__hidden1"),
// the closure which captures a variable has an allocator of its own, named after its class
assertEquals(java.util.Arrays.asList("Hidden_passHidden_Test__hidden", "Hidden_passHidden_Test__hidden1",
"Hidden_passHidden_Test_create"),
luaFunctionsWithPrefix(lua, "Hidden_pass"));
assertEquals(java.util.Arrays.asList("Under_passUnder_Test_do_it", "Under_passUnder_Test_do_it1"),
assertEquals(java.util.Arrays.asList("Under_passUnder_Test_create", "Under_passUnder_Test_do_it",
"Under_passUnder_Test_do_it1"),
luaFunctionsWithPrefix(lua, "Under_pass"));
assertFalse(lua, lua.contains("passUnder_passUnder"));
}
Expand Down Expand Up @@ -8568,7 +8610,7 @@ public void aConstructedFieldIsWrittenOnceNotFirstWithItsDefault() throws IOExce
" testSuccess()");
String compiled = compiledLua("aConstructedFieldIsWrittenOnceNotFirstWithItsDefault");
// an allocation which writes no field is the shared allocator's (classesWhichOnlyAllocateShareOneAllocator)
assertFalse("the allocation writes no field:\n" + compiled, compiled.contains("Hit:create"));
assertFalse("the allocation writes no field:\n" + compiled, compiled.contains("Hit_create"));
assertTrue("the allocation:\n" + compiled, compiled.contains("__wurst_allocObject(Hit)"));
for (String field : new String[] {"amount", "factor", "crit", "label", "next"}) {
int writes = compiled.split("Hit_" + field + "_storage(_local\\d*)?\\[[^\\]]+\\] = ", -1).length - 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ public void optCompressesLuaDescriptorsFieldsAndDispatchSlots() {
private void assertSiblingBindings(String lua, String slot) {
String identifier = "[A-Za-z_][A-Za-z_0-9]*";
// Each sibling's unique field initializer identifies its allocated descriptor and field
// table even after all names are compressed. Both a shared allocator(descriptor) and
// descriptor:create() identify the descriptor used by the allocation.
// table even after all names are compressed. A shared allocator(descriptor) names the
// descriptor at the allocation, a class's own allocator() in its body.
var allocations = Pattern.compile("(?m)^\\s*(" + identifier + ") = (" + identifier
+ ")(?::" + identifier + ")?\\((" + identifier + ")?\\)\\s*\\R\\s*(" + identifier
+ ")\\((" + identifier + ")?\\)\\s*\\R\\s*(" + identifier
+ ")\\[\\1\\] = ([1-4])\\b").matcher(lua);
Map<Integer, String> descriptors = new HashMap<>();
Set<String> implementations = new HashSet<>();
Expand All @@ -107,7 +107,15 @@ private void assertSiblingBindings(String lua, String slot) {
while (noOpFunctions.find()) noOps.add(noOpFunctions.group(1));
while (allocations.find()) {
int sibling = Integer.parseInt(allocations.group(5));
String descriptor = allocations.group(3) == null ? allocations.group(2) : allocations.group(3);
String descriptor = allocations.group(3);
if (descriptor == null) {
// the allocator records the object's descriptor before any field default
var recorded = Pattern.compile("(?m)^function " + Pattern.quote(allocations.group(2))
+ "\\(\\)(?:(?!\\nend)[\\s\\S])*?^\\s*" + identifier + "\\[" + identifier + "\\] = ("
+ identifier + ")\\s*$").matcher(lua);
assertTrue("Find the descriptor sibling " + sibling + "'s allocator records", recorded.find());
descriptor = recorded.group(1);
}
assertNull("One allocation anchor per sibling " + sibling, descriptors.put(sibling, descriptor));
String storage = allocations.group(4);
var override = Pattern.compile("(?m)^function (" + identifier + ")\\((" + identifier
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ private List<String> nonBaseSubclassBindings(String output, String baseName, Str
private List<String> subclassCreateClasses(String output, String baseName) {
// a class with its own allocator, or one which allocates with the shared one
String ownerPattern = "(" + Pattern.quote(baseName) + "_[A-Za-z0-9_]+)";
Matcher matcher = Pattern.compile("function\\s+" + ownerPattern + ":create\\d*\\s*\\(|__wurst_allocObject\\(" + ownerPattern + "\\)")
Matcher matcher = Pattern.compile("function\\s+" + ownerPattern + "_create\\d*\\s*\\(|__wurst_allocObject\\(" + ownerPattern + "\\)")
.matcher(output);
List<String> result = new ArrayList<>();
while (matcher.find()) {
Expand Down Expand Up @@ -1923,7 +1923,7 @@ public void luaClassTablesExistBeforeCreateMethodDefinitions() throws IOExceptio
" skip"
);
String compiled = Files.toString(new File("test-output/lua/LuaTranslationTests_luaClassTablesExistBeforeCreateMethodDefinitions.lua"), Charsets.UTF_8);
assertOccursBefore(compiled, "A = ({})", "function A:create(");
assertOccursBefore(compiled, "A = ({})", "function A_create(");
}


Expand Down Expand Up @@ -4551,9 +4551,9 @@ public void subclassAllocationIncludesInheritedFieldsInLua() throws IOException

// Within Child's own allocation function (Window is never allocated, so its allocation writes nothing).
assertContainsRegex(compiled,
"function\\s+Child:create\\d*\\s*\\(\\)(?:(?!\\nend)[\\s\\S])*?Window_anchorTop_storage\\[new_inst\\] = 0");
"function\\s+Child_create\\d*\\s*\\(\\)(?:(?!\\nend)[\\s\\S])*?Window_anchorTop_storage\\[new_inst\\] = 0");
assertContainsRegex(compiled,
"function\\s+Child:create\\d*\\s*\\(\\)(?:(?!\\nend)[\\s\\S])*?Window_anchorBottom_storage\\[new_inst\\] = 0");
"function\\s+Child_create\\d*\\s*\\(\\)(?:(?!\\nend)[\\s\\S])*?Window_anchorBottom_storage\\[new_inst\\] = 0");
}

// ----- GetHandleId remapping -----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public void dispatchInsideClosureLua() throws IOException {
String compiled = Files.toString(
new File("test-output/lua/TypeClassTests_dispatchInsideClosureLua.lua"), Charsets.UTF_8);

Matcher allocation = Pattern.compile("(\\w+_specialized\\w*):create\\d*\\(").matcher(compiled);
Matcher allocation = Pattern.compile("(\\w+_specialized\\w*?)_create\\d*\\(").matcher(compiled);
assertTrue(allocation.find(),
"the closure should be allocated from its specialised class:\n" + compiled);
String specialised = allocation.group(1);
Expand Down
Loading