Skip to content

Lua: allocate an instantiation whose members need its type argument from its specialised class - #1512

Merged
Frotty merged 6 commits into
masterfrom
lua-generic-erased-dispatch
Oct 20, 2026
Merged

Frotty merged 6 commits into
masterfrom
lua-generic-erased-dispatch

Conversation

@Frotty

@Frotty Frotty commented Oct 20, 2026

Copy link
Copy Markdown
Member

On Lua a new-generic class stays erased unless code needs its concrete type, and that decision was made per call site: a concrete call into T-dependent code was redirected to a specialised copy, but objects were allocated from the erased class. Any dispatch that does not name the instantiation (a non-generic interface or base class, destroy/ondestroy, a closure, a super call, an erased generic function) then ran the erased body, giving wrong values, nil, null or compile rejections. This fixes the defect classes the bounded-exhaustive matrix of #1505 found for that shape.

Root causes and commits

  • b1b27da - objects of an instantiation whose class needs its type argument are allocated from the specialised class. EliminateGenerics.allocatesFromSpecialisedClass is now the one place that decides: true for a tuple instantiation, one an instanceof observes (Lua: tell the instantiations of a generic class apart in instanceof #1507's rule), or one whose class or a superclass has a member needing T (classNeedsIdentity: per-instantiation statics, wurstNewInstance<T>, type-class bound dispatch, T-typed tuple storage). The same answer drives the allocation redirect, attaching every specialised method to the dispatch roots (AGENTS.md §8), and pointing class Sub extends G<X> at the specialised class. Classes with only parametric members stay erased; no runtime guard, tag or lookup is added. A specialised field shares Lua storage with its original, so the garbage removal treats them as one field. Fixes lua-bound-unresolved, lua-closure-receiver, lua-field-split, lua-new-instance-erased, lua-tuple-subclass and lua-static-erased outside closures.
  • 9ce6085 - eliminateRemainingGenericNewCalls and assertNoReachableGenericNewMarkers visited functions left in the erased generic class and rejected them; wurstNewInstance<T>() is lowered only in the specialised copies. Fixes lua-new-instance-unresolved.
  • cbf5ecc - a closure's captured type parameter was not linked to the one it captures (ClosureTranslator.rewriteTypeVars), so a specialised closure wrote the erased static. Fixes the lua-static-erased closure cases and the matrix's lua-tuple-elimination-crash closure case.
  • f54002e - widens Check in unit tests that live Lua code uses no erased generic static #1500's unit-test assertion: live code must also not touch an erased generic static while two or more instantiations of its class are allocated, even if none has a specialised copy (the sharing lua-static-erased showed). It fired on the factory repro before the fix.
  • fb2dd6a - merge of master (Lower a direct wurstKeyOf call on Lua #1506-Type a method call on an inherited generic method with the superclass's type arguments #1510), with the further adjustments the change exposed in adaptToSuperclass, classOwning, adaptSubmethods, specializeFunction and ImOptimizer.garbageRound, and genericSpecialisationMatrix-knownFailures.txt updated to match.

Evidence

  • Matrix, PR tier on the merged tree: 375 pass, 9 listed, 0 unlisted (was 233 / 151). The 9 left are lua-instanceof-erased cases with the instanceof inside a closure, which Lua: tell the instantiations of a generic class apart in instanceof #1507 deliberately keeps erased.
  • Matrix, full product (36,863 cases, pre-merge branch): every master failure in lua-static-erased (2,457), lua-bound-unresolved (1,556), lua-closure-receiver (820), lua-field-split (789), lua-tuple-subclass (634), lua-new-instance-unresolved (592), lua-new-instance-erased (374) and lua-tuple-elimination-crash (174) passes, and nothing newly fails.
  • New LuaBackendAuditTests regressions for each backlog repro (Jass runs as the oracle), plus identityBaseStateKeepsRootSlotBindingsInLua for §8: it checks the dispatched slot at the FSM call site and each sibling's binding, and compiles twice for determinism.
  • Output on the merged tree against master, five test classes: all Jass identical; 16 of 323 Lua scripts differ, each with generic statics, an observed instanceof, or the standard library's ArrayList, whose per-instantiation statics now specialise it.
  • A large real map compiles on Lua plain and with -inline -localOptimizations, both pass luac -p, no new errors or warnings. Its optimised script grows 1.4 %: 116 more class tables, nearly all ArrayList/IntMap instantiations, mostly constructors which differ only in the class table they write. Allocations (686), constructor call sites and __wurst_objectClass dispatches (231) are unchanged; no ordinary path gains a call, allocation or dispatch. On master that map's tuple-typed ArrayList allocator compacted its free list through the erased statics shared by every ArrayList instantiation (once its storage passes the Jass array limit); it now uses its own.
  • Passing locally on the merged tree: GenericsWithTypeclassesTests 119, TypeClassTests 72, FieldIterationTests 43, GenericStoreGeneratedTests 48, GenericStoreSpecializationTests 21, LuaBackendAuditTests 270, LuaTranslationTests 154, ClosureTests 65, DeterministicChecks 29, FastHashMapTests 15 (its shape check updated: those objects now come from the specialised class), plus OptimizerTests, BugTests and ClassesTests.

Follow-ups

  • Specialised classes whose identity is never read could share one constructor body; output size only.
  • AGENTS.md §9 still says not to call wurstNewInstance<T>() from a generic constructor; that now works on Lua.

Tested on Windows with the bundled Lua 5.3; Linux runs in PR CI, macOS only on master. No host-dependent code.

…rom its specialised class

On Lua a new generic stays erased except where code needs its type argument, and specialisation is
decided per call site. Objects were allocated from the erased class, so a call reaching such code
through dispatch which does not name the instantiation (a non-generic interface or base class,
destroy, a closure, a super call, an erased generic function) ran the erased body: shared statics,
unresolved bound dispatch, wurstNewInstance left unlowered, fields read as null.

EliminateGenerics.allocatesFromSpecialisedClass now decides in one place whether the objects of an
instantiation come from its specialised class: a tuple instantiation, one an instanceof observes,
or one whose class (or a superclass) has a method which needs the type argument
(classNeedsIdentity). specializeClass asks the same question to attach every method of such a
class to the dispatch roots, and a class extending such an instantiation extends the specialised
class. Instantiations of classes with no such member stay erased.

Neighbouring defects the change exposed are fixed where they arise:
- ImOptimizer's garbage round dropped a store to a field of a specialised class whose original is
  read; on Lua both share one storage (LuaTranslator.fieldStorage).
- adaptToSuperclass did not know a specialised class is the instantiation it was made for.
- classOwning could map a source class to one of its specialised copies.
- adaptSubmethods iterated a submethod list which specialising a subclass extends.
- specializeFunction left the class's type variables in the copy of a class function which writes
  a static.

Fixes the GenericSpecialisationMatrixTests tags lua-bound-unresolved, lua-closure-receiver,
lua-field-split, lua-new-instance-erased and lua-tuple-subclass, and lua-static-erased outside
closures.
…ic class

On Lua a function of a generic class keeps the class's type variables (they are not lifted onto
it), so its erased original is not a generic function to the passes which lower and check
wurstNewInstance. They visited a constructor or a method left in the erased class, found the
marker with the type parameter as its argument and rejected the program ("requires its type
argument to resolve to a concrete class"), although every concrete use reached a specialised copy:
a super call, or a constructor called from a method for its own instantiation.

eliminateRemainingGenericNewCalls and assertNoReachableGenericNewMarkers now skip the classes which
still have type variables, as they skip generic functions. An erased original which stays live
reaches the backend's check for an unlowered marker.

Fixes the GenericSpecialisationMatrixTests tag lua-new-instance-unresolved.
…lass it captured

A closure written in a method of G<T> becomes a class of its own whose type variable T_captured
stands for G's T, but nothing recorded that. When the closure was specialised for G<int>, the
statics of G its body reads or writes could not be mapped to G<int>, so the specialised closure
kept the erased store, which every instantiation shared (or which nothing initialised).

ClosureTranslator records each captured type variable as a copy of the one it captures, and
EliminateGenerics maps an owner's type parameters through them (capturedOwnerGenerics) when the
class is not a subclass of the static's owner; specializeClass rewrites the statics of a class
whose functions use generic statics it does not own.

Fixes the closure cases of the GenericSpecialisationMatrixTests tag lua-static-erased and the one
lua-tuple-elimination-crash case of the pull-request tier.
…n instantiations

assertNoLiveErasedGenericStatic failed only when a static had specialised copies and live code
still used the erased original. Instantiations which only erased dispatch allocates make no copy
at all, and then the erased static is one store for all of them, where Jass has one each: the
lua-static-erased program in which a generic factory reached through a non-generic interface
allocates Slot<int> and Slot<string> passed it.

The check now also fails when live code uses the erased original of a static while live code
allocates two or more instantiations of the class which declares it, counting the superclasses
of what is allocated, an allocation from a specialised class as its instantiation, and an
allocation whose type arguments are still type variables (outside its own constructor) as
instantiations not known here. EliminateGenerics records the owner of every generic static
for it. Unit-test mode only, as before.
Folds the allocation rule into what #1507 established: an instantiation an instanceof observes is one allocatesFromSpecialisedClass answers for, and a closure is not given an identity for an instanceof alone (classNeedsIdentity). A static inner class's captured owner (#1509) and a closure's captured type parameter both map to the owner of a static (adaptGenericsToOwner). The list of known failures is the one the merged tree leaves.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T20:09:23.095350Z 6961810 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fb2dd6acc0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…r call as supported

Lua now reaches a specialised copy for each of these shapes, as Jass always did. AGENTS.md section 9 says so and names the coverage: a new Jass and Lua case in FieldIterationTests, and the NEW_INSTANCE cases of GenericSpecialisationMatrixTests. The bullet on targeted Lua specialisation names the instantiations whose members need their type argument.
@Frotty

Frotty commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 696181029c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Frotty
Frotty merged commit 695e459 into master Oct 20, 2026
2 checks passed
Frotty added a commit that referenced this pull request Oct 21, 2026
…wn on Lua

#1512 made TypeClassTests.classBoundWithIndependentMethodTypeParam pass on Lua, and the test now runs
there, so section 9 says the shape is supported instead of not promised. Generic construction inside
such a method stays uncovered, so the advice for serialization loaders remains.

LuaExemption.CLASS_AND_METHOD_TYPE_PARAMS had no use left; it goes, with its TRANSLATION_ERROR kind.
Frotty added a commit that referenced this pull request Oct 21, 2026
Frotty added a commit that referenced this pull request Oct 21, 2026
…ure (#1515)

* Lua: tell the instantiations apart in an instanceof written in a closure

An instanceof Box<T> in a closure written in a method of a generic class
accepted every Box on Lua. #1507 kept closures erased for an instanceof,
because specialising one left its captured receiver typed by the erased
class; #1512 fixed that receiver, so the exclusion is lifted: an instanceof
of the type parameter now counts towards a closure's identity like any
other member which needs its type argument.

A closure which constructs the Box<T> another closure checks still stayed
erased. Box<int> is observed only once the checking closure is
specialised, in the second round, but classNeedsIdentity keeps its first
answer, given in the first. Whether an instanceof observes a class is now
collected once, before the specialisation, from every parameterised
instanceof, including one still written with a type variable.

The IM interpreter compared only the class in an instanceof, so it took a
Box<string> for a Box<int> in compile-time code and @test functions. It
now compares the type arguments of the instantiation too. The audit tests
for instanceof identity run the interpreter on the generic program again.

Removes the nine INSTANCEOF_CLOSURE cases from the matrix's known failures
and the lua-instanceof-erased backlog entry. Records a crash found on the
way: a closure inside another closure which uses its owner's T fails in
EliminateGenerics on Jass and Lua.

* Compare instantiations in the interpreter's instanceof as the specialisation does

Type-class bindings are dispatch metadata, which GenericTypes ignores at every
nesting level when it tells specialisations apart; the interpreter now compares
an object's instantiation with the checked one the same way, instead of through
equalsType, which compares nested bindings. Adds a check of a type argument with
a bound inside it, built directly and through generic functions.

* Check every path to a generic supertype in the interpreter's instanceof

A class which reaches one generic interface through two others, as G<int> and
as G<string>, is an instance of both, as on Jass and Lua. The interpreter
compared the checked instantiation with the first path to the interface only,
so one of the two checks was false. It now collects the instantiations of
every path.
@Frotty
Frotty deleted the lua-generic-erased-dispatch branch November 25, 2026 08:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant