Skip to content

feat: PHP# generics, checked and carried at runtime (spec section 11, R1 to R5) - #102

Merged
heyJordanParker merged 258 commits into
masterfrom
feat/slice-generics
Oct 14, 2026
Merged

heyJordanParker merged 258 commits into
masterfrom
feat/slice-generics

Conversation

@heyJordanParker

@heyJordanParker heyJordanParker commented Oct 11, 2026 •

Copy link
Copy Markdown
Owner

Problem

A PHP# developer writes class Counter<T>, T first<T>(List<T> items), List<Order> orders = cache.get("orders"); and new PaginatedList<Order>(rows). Spec section 11 makes all of them valid, and says the running program knows Order in each. Decisions 7 and 29 rest on that: plain PHP calling in is checked against the type arguments, and reflection can read them.

On master each generic declaration is a parse error, and the engine has nowhere to keep a type argument. A List<int> that plain PHP fills with a string passes, is can't test a List<int> or a type parameter, and Counter<Order> and Counter<Customer> would share one static field. Generics appear in nearly every service, repository and cache signature, and they are the second-ranked gap to v1.

Solution

PHP# generics land whole, R1 to R5 of the reified-generics plan, as decision 072 records. The checker in sharp/mago/ parses, binds, checks and lowers them, and the engine carries every type argument and checks every PHP# value against its type. This PR used to be the engine half of heyJordanParker/mago-sharp#152. Since #120, Mago lives in sharp/mago/, so #152's checker half is merged into this branch and #152 is closed.

The checker

  • Parse and bind. The parser reads type parameters with inline bounds (<TItem : DatabaseEntity & Shareable>), in and out markers, and type arguments on types, headers, new, calls, typeof and a class read as an expression, as in Counter<Order>.count. Each type parameter binds to its declaration.
  • Check. Generics are typed with Mago's templates:
    • bounds, with Any? as the bound of an unbounded parameter
    • opaque type parameters
    • out and in as spec 11.1 rules them, and invariance for a parameter with neither
    • Self on a receiver typed by a type parameter
    • erased-signature soundness against plain PHP parents and children
    • Serializable refused on a generic class
    • a type, or a new, written without its type arguments is refused
    • a type written as a type argument is checked as any written type, so new Box<Pair<int>>() is refused
  • Infer. A generic call takes its type arguments from its arguments or from the declared type its result goes into, also through ?? and ?:. One that neither fixes is refused, as C#'s CS0411 is: "Nothing fixes the type argument T of the call to Store.get." A generic method value takes its type arguments from the function type it goes into.
  • Test types (R3). is, as, a match arm and a catch test a List, a Map, a Set, a union, a nullable type, a type parameter and a class with type arguments. A function type and Class<T> have no test, and the checker says why. new TItem(…), typeof(TItem) and TItem.LIMIT read the type argument while the code runs.
  • Per-type-argument statics (R4). Counter<Order>.count, Counter<Order>.reset() and Counter<Order>.LIMIT read and write the statics of that type argument. A static method of a generic class takes its class's type arguments.
  • Class values (R5, spec 25). typeof(Box<Order>) is a Class<Box<Order>>. new (type)() creates the class with the type arguments the value carries, and a static member read or written through the value takes them. == and != compare two class values by their whole type, type arguments included, as C# compares two Types. A class value keys no Map.
  • Lower. new, a generic call, a type test, a static of a generic class and a class value carry their type arguments to the engine. Each PHP# class-like carries its type metadata. A lambda captures its method's type arguments.
  • Check values from plain PHP. Every function plain PHP can call ends its parameter list with the type texts the engine checks each argument against: a method, an event's constructor, a named constructor, an operator and a lambda. A plain PHP call's result is wrapped in SHARP_AST_VERIFY_TYPE_ARGS wherever PHP# takes it. A property carries its PHP# type text, which the engine checks on every write from plain PHP on PHP's own typed property path.
  • Unions. A union is refused only where the engine can't tell two members apart. Two of List, Map and Set are refused, for example.

The engine

  • On the object. A generic class declares one hidden slot, ZEND_ACC_SHARP_HIDDEN, that holds its object's type arguments. new fills it through ZEND_SHARP_TYPE_ARGS. clone, serialize and unserialize keep it, and == compares it. No view of the object shows it.
  • On the call. A generic method's own type arguments ride on its call, and the method reads them with ZEND_SHARP_RECV_TYPE_ARGS. A lambda captures them. A plain PHP call pays nothing.
  • One interned type per type text. App.PaginatedList<Set<int>> is one descriptor, so equal types are one pointer.
  • One check of a value against a type (R3). sharp_type_accepts walks a List, a Map, a Set, a union and an object with type arguments, and turns an int a float takes into a float. Each place plain PHP hands PHP# a value runs it and throws TypeError on a mismatch:
    • a parameter of every function plain PHP calls: a method, an event's constructor, a named constructor, an operator and a lambda
    • a plain PHP call's result wherever PHP# takes it, through ZEND_SHARP_VERIFY_TYPE_ARGS
    • every write to a PHP# property, instance or static, on PHP's own typed property path behind ZEND_ACC_SHARP_TYPED, so a subclass, a reference and reflection are checked too
    • unserialize
  • Type tests (R3). SHARP_IS_TYPE tests a value for is, as, a match arm and a generic catch. out and in keep their variance in the class's sharp_variance, and the entry checks honor it.
  • Each type argument's own statics (R4). A generic class has one hidden static store, keyed by the type argument text, with its defaults under "". \Sharp\Internal\statics returns an entry by reference and copies the defaults on first use. Plain PHP and reflection neither name nor list the store.
  • Class values (R5). typeof(Box<Order>) returns the descriptor's own interned class name, which sharp_class_values maps back to the type. new (value)(…) creates the class with the type arguments the value carries. \Sharp\Internal\equals, which PHP#'s ==, != and a search of class values call, compares two class values through their type descriptors. Plain PHP's === on the class name keeps PHP's answer. A Class<Box<Order>> parameter, result or property takes only a class value of that type from plain PHP.
  • Readable from plain PHP. ReflectionObject::getTypeArguments() returns ["App.Order"]. ReflectionType::getName() and __toString() stay PHP's, because Laravel's container and the proxy generators read them.
  • Through every engine path. The opcache file cache, preloading, every optimizer pass alone, and the tracing and function JITs keep the type-argument operands. sharp/bin/census checks every write of a marked op1 or op2.

Test any PHP# type (R3)

type_test_of is the one decision of which types is and as test. A type with no PHP instanceof lowers to SHARP_IS_TYPE, which carries the type text the engine walks:

value is List<int>                 // every element is an int
value as Map<string, float>?       // null, or a Map whose keys and values pass
value is TItem                     // the type argument the call or object carries
match (value) { PaginatedList<Order> page => … }
catch (Failure<Order> failure)     // a generic catch
value is Function<int(int)>        // refused: a function value carries no signature to test

An as or is that always holds says so in the code's words. out and in are @template-covariant and @template-contravariant, each checked in the positions spec 11.1 allows. When exactly one type argument differs and a marker would allow it, the help names the marker.

Per-type-argument statics (R4)

A static field of a generic class lowers to its entry in \Sharp\Internal\statics, one per type argument. Counter<Order>.count++ and Counter<Customer>.count++ change two numbers. A method call on a static collection field binds the field by reference, so Log<Order>.events.add(e) keeps the element. Orders : Counter<Order> passes its header's type arguments to the statics it inherits.

Class values (R5)

typeof(Box<Order>) is a Class<Box<Order>>, and it reaches plain PHP as the class name. new (type)() gives a Box<Order>. type.count = 1 writes the static of Box<Order>, as type.count reads it. == and != between class values, and a search of a collection of them, lower to a call of \Sharp\Internal\equals. Every other == lowers as before:

typeof(Box<Order>) == typeof(Box<Invoice>)    // false: the type arguments differ
typeof(Box<Order>) == typeof(Box<Order>)      // true
typeof(Order) == typeof(Order)                // true: no type arguments
typeof(Box<Order>) != typeof(Box<Invoice>)    // true
[typeof(Box<Order>)].contains(type)           // compares each element the same way

type_arguments_call_class_value.phpt prints false, true, true, true, false for these. Without the lowering it prints true, true, true, false, true.

One check, is_map_key, refuses a class value as a Map key in all three places one can appear:

  • the type Map<Class<Order>, int>
  • the literal [typeof(Order): 1]
  • the Map that groupBy or associateBy infers from a key function that returns a class value

Each is "A Map's keys are int, string or a type with an int or string backing value, and Class<Order> has none.", with master's code for that position.

The entry checks from plain PHP

One helper, Lowering::parameter_metadata, ends the parameter list of every lowering that emits parameters: method, event, named_constructor, operator and lambda_parameters, which an arrow function and a closure share. A static method's texts also name its class's bounds, since it takes its class's type arguments. every_function_plain_php_calls_checks_its_parameters_type_arguments pins all five.

The bridge wraps a value in SHARP_AST_VERIFY_TYPE_ARGS when it is a call the analyzer resolved to plain PHP and the type the call returns passes the same test a parameter's check does:

Box<Order> box = Pager.orders();     // checked, named Lib\Pager::orders()
box = Pager.orders();                // checked
let untyped = Pager.orders();        // checked
this.keep(Pager.orders());           // checked
return Pager.orders();               // checked
this.auto = Pager.orders();          // checked
Box<Order> made = Shelf.make();      // PHP# call: not checked
Box<Order> held = this.maker();      // a function value a property holds: not checked
int count = Pager.count();           // nothing to check

Plain PHP passes a PaginatedList<Customer> where PHP# expects a PaginatedList<Order>. The type_arguments_entry_*.phpt tests show each TypeError, one rule per test:

PaginatedList<Order> page = Pager.orders();   // Pager is plain PHP, its docblock promises orders
  TypeError: Lib\Pager::orders(): Return value must be of type App.PaginatedList<App.Order>, App.PaginatedList<Checks.Customer> returned

List<int> sizes = Pager.sizes();              // a plain PHP array with a wrong element where PHP# takes a List
  TypeError: Lib\Pager::sizes(): Return value must be of type List<int>, array returned: [1] expected int, got string 'seven'

new Paged($customers);                           // an event's constructor
Purse::of($customers);                           // a named constructor
Purse::op_Addition(new Purse(1), $customers);    // an operator, Argument #2
Pages::taker()($customers);                      // a lambda
  TypeError: Checks\Paged::__construct(): Argument #1 ($page) must be of type App.PaginatedList<App.Order>, App.PaginatedList<Checks.Customer> given, called in … on line …

Every TypeError names an object's class with dots, as the expected type is written: Checks.Customer, never Checks\Customer beside App.PaginatedList<App.Order>. A class value with type arguments is named by its Class type. An array with a wrong element names the first one, its path and the type found, at a parameter, a return and a property write alike.

The rulings on R3 to R5

  • R4 is accepted. The cast handler's new branch runs only under IS_OBJECT | ZEND_SHARP_OPERATOR, so plain PHP takes none of it. receiver#N follows compound_assignment's temporaries.
  • R5 is accepted as built. TypeOf.type_arguments follows Instantiation's precedent. A static write through a class value and the one Map-key check are part of R5, because R5 owns class values.
  • A type written as a type argument is checked as a type. This fixes a regression and a gap that master also has.
  • ReflectionNamedType::getTypeArguments() is withdrawn: it would add a field to every function, bump the module API and change what opcache persists, for a method no consumer needs in v1. Spec 11's "Reflection shows PaginatedList<Order>" is met by ReflectionObject::getTypeArguments() on the object.
  • The spec harness files can't ride this PR, because sharp/harness/ is guarded. PaginatedList.sharp and the Element.sharp change go in a harness-only PR after this one merges, so typeof-type-parameters and generic-class-values stay listed in sharp/baseline/spec/.
  • A static whose initial value isn't constant, such as = typeof(Box<Order>), is the general section 6 gap, task A module can't bind every implementation of an interface without a hand-written list #517. It stays "A static member's initial value that is not constant is not supported yet in PHP#."
  • Three findings are their own tasks and stay out of this PR: the false unused-template-parameter when only a method body uses the type parameter (A law can't compare a nullable value of a class with == #513), "Invalid property assignment value" on a wrong generic static write, and the bare Counter.track message that omits the missing type argument (Reflection throws on a method with a plain PHP callable parameter #514).
  • Jordan ruled == between class values: it compares the whole type, type arguments included, as C# does. This PR builds it.
  • Jordan ruled a non-nullable static field with no initial value a compile error. It ships with task PHP#'s own tooling still holds plain PHP: the extension SDK and the Composer plugin #531, outside this PR.
  • Jordan ruled that a function type is tested like any other type, and a test whose type the value's source never declares is a compile error. It ships with task vendor/bin/mago runs out of memory unpacking the 0.6.40 binary under PHP's default memory_limit #535, outside this PR. Until then value is Function<int(int)> stays refused.

Plain PHP stays the same

mago analyze over a plain PHP corpus, built from master 5d5724a95a and from this head, differs by exactly one line. The corpus is the analyzer's case files, phpunit with its vendor tree, and a file of @template, @template-covariant, @implements and class-string<T> uses, an untyped private method and a private callable(int) property. Master gives 17,812 lines and this head 17,813, with no panic:

> vendor/phpunit/phpunit/src/Logging/TestDox/NamePrettifier.php:290:49:error - less-specific-argument: … `ReflectionClass::__construct`: expected `BackedEnum|UnitEnum|class-string<BackedEnum>|class-string<UnitEnum>`, but provided type `object` is less specific.

It comes from the ReflectionEnum fix that 4c501c237 keeps, the line the review found too.

Section 11 rules and their state

Rule State
The running program knows every type argument Done: new, calls, headers, statics and class values carry them, and the engine keeps them on the object
Reflection shows PaginatedList<Order> Done: ReflectionObject::getTypeArguments() returns ["App.Order"]. ReflectionType stays PHP's
Plain PHP reads type arguments with ReflectionObject::getTypeArguments() Done
A class value reaches plain PHP as a plain class-name string Done (R5)
page is PaginatedList<Order> is checked while the code runs Done (R3), with as, a match arm and a catch
A plain PHP class's objects carry no type arguments, so value is Collection<Order> on a plain PHP @template class is a compile error Done, at any depth, in is, as, a match arm and a catch: "Collection<Order> can't be tested: Collection is a plain PHP class, so its objects carry no type arguments while the code runs."
A wrong value entering from plain PHP throws TypeError Done at every parameter plain PHP calls, at a plain PHP call's result wherever PHP# takes it, at every property write and at unserialize, a collection's elements included
An int where PHP# expects a float becomes a float Done at a float parameter, a T = float parameter, and the typed local and property checks, inside collections too
Each type argument has its own static members Done (R4)
new always names its type arguments Done: new Box(1) is refused, "Box needs its type argument"
new Self(…) names none Done
A type names its type arguments, except Class<PaginatedList> Done
A generic call fixes them from its arguments or the declared type its result goes into, and refuses one neither fixes (CS0411) Done
Plain PHP @template generics keep their fallback Done
A raw object plain PHP creates has its bounds as its type arguments, checked where it enters Done
PHP# code never creates a raw object Done: CS0411 and the new rule
Every type argument is carried at runtime, written or inferred, as in value is TItem Done (R3)
Type parameter names start with T Done
The bound is written inline, and several bounds use & Done
A type parameter with no bound is bounded by Any? Done
A generic class can't implement Serializable Done
A class value with type arguments can't be a Map key Done (R5), in a type, a literal and an inferred Map
== compares two class values by their whole type Done, with != and a collection search, through \Sharp\Internal\equals
Self on a receiver typed by a type parameter is that type parameter Done
11.1 Variance: out, in, invariant Done (R3), in the checker and the engine's entry check alike
11.1 The checker enforces the marker on every member Done
11.1 The error names the marker to add Done (R4), when exactly one type argument differs
11.1 No variance at the point of use Done: there is no syntax for it
Generic catch Done (R3)

What stays refused

Refused Message Why
A named constructor called through a type parameter, new TItem.of(1) "A named constructor through a type parameter, as in new TItem.of(…), is not supported yet in PHP#." R3 to R5 did not build it. new TItem(value) compiles
A generic event, event Moved<TItem>(TItem item); "A generic event is not supported yet in PHP#." R3 to R5 did not build it
A static whose initial value isn't constant "A static member's initial value that is not constant is not supported yet in PHP#." Task #517, the section 6 gap
A wrong count of type arguments "Map takes 2 type arguments: the key and the value." A wrong program, refused for good
Type parameters on a named constructor "A named constructor takes its class's type arguments and declares none of its own." In a generic class the help quotes public static Pair<T> of(T value), which compiles there A wrong program, refused for good
A class that reaches a generic class-like twice with other type arguments "Strings implements Feeder twice: Feeder<int> through Ints, and Feeder<string>." A wrong program, refused for good, as a header that names Feeder twice is

The review of 66c6b8d44e

Each change the review asked for, at head ea2ea81e9b:

  • f4ae6879bc merges php-sharp master 5d5724a95a (Run section 9's constructors and init on the engine #110, §28: the engine refuses a file whose law or structure rule the checker refuses #113), tests and docs only, with no conflict.
  • bb1a691414 merges php-sharp master e19d4c27c8 (feat: run extension members and give string its trim(), spec section 26 #115, extensions). Eight files conflicted, and each keeps both sides. An extension method's parts carry its type parameters, as a method's do, and the bridge keeps this PR's parameter metadata with master's new set_parameters argument.
  • a6cd08c91e fixes the checker:
    • Plain PHP that calls an untyped private method, or reads a private property whose docblock callable has no return type, no longer panics. The private-reach checks run only for a PHP# class, and two .php rows pin it.
    • A type test that gives a plain PHP class type arguments is a compile error, at any depth, in is, as, a match arm and a catch. Analyzer and bridge rows pin it.
    • The named-constructor help in a generic class quotes a static method that compiles there. A test compiles the quoted method in a plain class, a class of one type parameter and a class of two.
    • new TItem.of(…) names the form refused.
    • A class that reaches a generic interface twice through a parent gets one error naming each way, in place of a false never return type and "Diamond inheritance … template parameter". Upstream's diamond check stays for plain PHP.
    • The staleness test gains a variance row and an arity row. Each fails when its part of the type parameter list fingerprint is removed.
  • 7b4ac21a28 splits type_arguments_entry_check.phpt into 16 tests and type_arguments_call.phpt into 8, one per rule over the same fixtures, with every expected line unchanged.
  • d5be88d8d4 makes a wrong element from plain PHP name its path and the type found: "…, array given: [1] expected Probe.Order, got object Probe.Invoice".
  • b48d4e71cf adds the two rows patch-coverage asked for: the same type arguments reached through two header entries are named once, and a subclass of a class refused for reaching Feeder twice is not refused again.
  • c340ebdff4 merges php-sharp master f208b11e74 (feat: modules, with services checked at compile time and resolved by the engine #121, modules). Six files conflicted, and each keeps both sides. Where the two features meet:
    • Both sides registered the Sharp\Internal functions in the engine's startup, which warned "duplicate name". Master's one registration stays.
    • A binding declares no type parameters, so its scan resolves none and its lambda captures none.
    • A constructor parameter whose type names a type parameter, as List<TItem> does, is no service the container gives. Before this, it got a Sharp\Internal\Service attribute naming a template id.
  • 45cab9a4fd makes as T?, as in as Map<string, float>?, say what to write: "Write as Map<string, float>." as already gives null when the value doesn't fit. 32ba9db945 adds the as void row patch-coverage asked for: it keeps the refusal, with no help.
  • 7c01edba21 joins extensions and generics:
    • Plain PHP that calls an extension member checks a generic parameter's elements, as it does for a method. extension_entry_check.phpt passes [3, 4] to counted(List<int> amounts) and gets 7, and passes [3, "x"] and gets "…, array given: [1] expected int, got string 'x'". Both rows pass in each of the 22 opcache modes.
    • A receiver typed by a type parameter, as TRush : RushOrder, runs the member its bound declares, not an extension of the same name. A bound that declares no such member still runs the extension. A bridge test pins both.
  • e30c8462fa merges php-sharp master c6a673cdde (feat: declare effects as foreign classes, and ship Environment as one #118, foreign and effect classes; fix: a compile after a warm pass types every class the pass skipped #126, the warm compile panic). Nine files conflicted, and each keeps both sides. Where the two features meet:
    • Sharp\Environment is now master's library class, so the engine keeps this PR's type texts and master's native commandLine, and sharp_arginfo.h is regenerated from the merged stub.
    • Master's uses and this PR's type parameters together took Method past clippy's large_enum_variant limit again. A method's on clause now lives in the arena too.
    • A method value of a plain PHP @template method, as List.wrap passed where a Function<List<Any?>(Any?)> goes, takes its type arguments from that function type, as a PHP# method's does. Before, its unfixed T was refused. It records none, so the engine still runs PHP's first-class callable.
    • No static holds a foreign object behind a type parameter's bound or a generic class's type argument. A new analyzer test pins both, and a bound that is no foreign class.
    • Two fixtures implemented a pure interface method with sprintf, which master's effects check refuses. They use template strings, and opcodes.phpt pins three .php lines the old body hid.
  • bc49d3928a steadies type_arguments_requests.phpt. Its random type texts spelled each bit as string or int, so one request read some 1.8 MB more than another, and Linux CI saw the peak grow by exactly the 4 MiB limit with nothing kept. Each bit is now string or float?, both six bytes, and the heap peak is the same in every request. A worker that kept the texts would still grow some 10 MB a request.
  • ea2ea81e9b merges php-sharp master 660ad5a094 (feat: call plain PHP through its namespace, and refuse bare calls and statements that never run #124, plain PHP calls through their namespace, and statements that never run). Seven files conflicted, and each keeps both sides. Where the two features meet:
    • A property read takes master's arms for a namespace constant and an unknown class first, then this PR's class constant arm, which reads a generic class too.
    • Three engine fixtures and three bridge tests call global.sprintf, global.max and the rest in place of bare calls.
    • This PR analyzed a .sharp file's code after throw. Master refuses that code and stops the block there, so Context::analyze_dead_code and its test are deleted.
    • Through global.array_key_exists a call reaches no assertion, so the Set row moves to plain PHP, which still calls it bare on the Set a PHP# method returns.

The move into sharp/mago/

14cfa4bad4 merges php-sharp master f670be8f1e (#120). Two files conflicted:

  • ext/sharp/sharp_unit.h took master's side, which names no Mago commit.
  • The one-file list sharp/baseline/spec was removed for master's folder.

cf3e3c4256 merges mago-sharp feat/slice-generics at cb9e2842f into sharp/mago/, as docs/architecture/mago.md says under "Moving an open mago-sharp branch":

  • sharp/mago/.github/actions/setup-lean/action.yml and sharp/mago/.github/workflows/ci.yml are removed. The branch changed neither, and .github/ carries mago-sharp master's versions.
  • ext/sharp/sharp_unit.h is the header the merged bridge's build.rs writes. Only its ABI differs from master's.
  • 24 examples leave sharp/baseline/spec/ because they pass. Six are generics: §7 method-declarations, §11 generic-statics, inferred-type-arguments and self-on-type-parameters, and §25 class-values and class-value-equality. The other 18 passed because the branch carries mago-sharp master up to 164ef442d, which php-sharp's sharp/mago/ held only after feat: the engine runs section 12's collection methods and index places, with sharp/mago at mago-sharp 3cc39cc8c #114.

The merge of #114

At cf3e3c4256, mago compile refused five of master's engine fixtures, which still used the collection methods and keywords from before mago-sharp 164ef442d. The self-test's refusal example also failed, because #173's braces rule refuses if (true) return; as a real error. #114 fixes both, and 66c6b8d44e merges it, master b8907a9c1e. That also brings sharp/mago/ to mago-sharp 3cc39cc8c, so mago-sharp #175 and #177 merge into the generics checker, without a conflict.

Six files conflicted, and each keeps both sides:

  • ext/sharp/sharp_arginfo.h is regenerated from the merged sharp.stub.php, which holds master's insert, removeAt, put and clear and this PR's \Sharp\Internal functions.
  • index_read.inc keeps master's two count calls and this PR's three standing calls.
  • enum_keys.phpt and its two JIT twins keep this PR's TypeError: the Map's check refuses the key "missing" where plain PHP hands the Map in, before master's loop would convert it. enum_keys.inc's comment that plain PHP collections are not checked now says where the key fails.
  • opcodes.phpt keeps master's 16 op arrays for EnumKeys and this PR's check lines, with one for each of master's grouped and groupNames.

The nightly stack overflow

The nightly Linux job aborted in a_property_default_of_100_000_terms_is_inferred_on_a_small_stack. The parser's path from the parse_statement guard into a class property reaches the lexer with no guard between them, and the stack guard allows that path only its 100 KiB red zone. In an x86_64 debug build the path took 102,032 bytes on master and 103,360 on this branch. parse_statement_inner was 43,720 of them, because each arm unwrapped its node with ? and wrapped it again. cb9e2842f returns each arm's Result as it is: parse_statement_inner takes 17,144 bytes and the path 76,832. On x86_64, a thread whose first guard has 102,560 bytes left overflowed before the change and passes after it.

What the earlier merges changed

On the checker side, mago-sharp 7931eb3ad merged Mago master 164ef442d (#166, #170, #171, #173 and #176) and resolved 21 files, keeping both sides of each:

  • The .sharp lexer keeps a keyword only in exact lowercase (feat: a constant's value is any expression built from constants #173), so List, Class and Function lex as names. The slice's keyword arms for them are deleted, and a name followed by < or ( starts a generic or function hint.
  • A typed local checks its type arguments, then reports master's miscased keyword, then an unknown type.
  • A Map key is checked by the slice's is_map_key, inside master's fix: a PHP form PHP# never has is refused for good, with what PHP# writes instead #166 paths for groupBy and associateBy.
  • Master's on clause and the slice's type parameters together took Method past clippy's large_enum_variant limit in ClassLikeMember. A method's type parameters now live in the arena, as a local's hint does.

On the engine side, 1a0320ac17 brought R3 to R5 over round 2's call checks. R3 removed ZEND_SHARP_VERIFY_SET_HOOK, since every property now checks on PHP's typed property path, so ZEND_SHARP_VERIFY_TYPE_ARGS checks only a plain PHP call's result. 1fa9c8ccb3 merged master b1fa0fdb0d (#111, #112). Each earlier merge commit's body lists its resolutions.

patch-coverage

Every line this PR adds to Mago runs in a test. The only lines patch-coverage leaves out are unreachable! arms, which mago-sharp #164 excludes. Each states what an earlier step guarantees:

Function Why no accepted program reaches it
sharp-bridge erase, three arms The binder binds a type parameter's name only to a type parameter the file declares. check_slice joins only classes with & and refuses every other type.
Types::type_arguments The analysis records the type arguments of every generic new.
Types::member_declaration The checker refuses a member read that names no member, unless the class has __get.
Types::atomic_text, three arms A class and a method declare each of their type parameters. The analyzer refuses a type argument PHP# can't write.
static_type_text The bridge writes an index after every $ and # in a static's type text.
GenericClass::analyze A name the binder binds as a class resolves to that one class.
TypeOf::analyze A type parameter's class values are those of its bound, which takes any type.
resolve_static_properties A static property's resolution names the class that declares it.
try statement, a generic catch A type parameter's hint reads as the type parameter.
find_template_uses A class lists only the methods it declares.
find_method_positions A PHP# method other than a constructor declares its return type.
find_atomic_template_positions, two arms A PHP# function type writes the type of each parameter and its return type.
explain_blocked_substitution A blocked substitution differs in a type argument.

Mutants

The mutants job at mago-sharp 6b923c21d left 36 survivors in the R1 and R2 code, and review round 2's CI run found three more. Each one fails a row, is deleted as dead code, or is equivalent with the reason. The full table is in mago-sharp 0a3ba8119's body and in #152's review round 2 comment.

Verification

At ea2ea81e9b, the merge of #124, with the engine built here and mago built from sharp/mago/ by sharp/bin/test's own cargo build:

mago compile                                    Compiled 117 PHP# files into .sharp/.
sharp/bin/test Zend/tests/sharp, no opcache     237 of 237 passed
the generics, extension and Environment tests, --opcache --repeat --passes   54 of 54 in each of the 22 modes
sharp/bin/native                                writes the committed sharp_native.h and native.php
mago-analyzer tests, 1.97.0                     390, 2569 and 789 passed
mago-codex, mago-names, mago-syntax, mago-semantics, mago-fingerprint   every test passed
mago-sharp-bridge, mago-orchestrator, mago-server   every test passed
mago tests/compile.rs and tests/sharp.rs        75 and 68 passed
cargo fmt --check                               clean
clippy --workspace --all-targets -D warnings    no warnings

At e30c8462fa, the merge of #118 and #126, the spec run gave "Checked 180 examples, ignored 1, and 71 fail, all of them listed", and --self-test 17 of 17.

At mago-sharp cb9e2842f, before the move:

mago-syntax tests, 1.97.0                       874 passed
mago-codex lib tests, 1.97.0                    227 passed
clippy -p mago-syntax --all-targets             no warnings
the 100,000-term test, x86_64 nightly           overflowed before cb9e2842f at 102,560 bytes left, passes after

At cf3e3c4256, CI's build-and-test (ubuntu-latest, nightly), the job that overflowed, passed in 11m23s. CI runs every mode, the census and Mago's full suites.

Files

Zend/
├── zend.h, zend_compile.h            the hidden slot, ZEND_ACC_SHARP_TYPED, sharp_type and sharp_variance
├── zend_ast.h, zend_ast.c            SHARP_TYPE_ARGS, VERIFY_TYPE_ARGS, SHARP_TYPE_OF, SHARP_IS_TYPE, SHARP_CLASS_METADATA
├── zend_compile.c                    type arguments on new and calls; property type texts; the statics store; type tests
├── zend_execute.c, zend_execute.h    zend_verify_object_property_type and the reference refusal
├── zend_API.c, zend_object_handlers.c, zend_property_hooks.c   writes check through the object; the store stays hidden
├── zend_vm_def.h (+ generated)       SHARP_TYPE_ARGS, RECV_TYPE_ARGS, VERIFY_TYPE_ARGS, the type test, NEW through a class value
├── Optimizer/                        every pass keeps the type-argument operands
└── tests/sharp/                      type_arguments_*.phpt and their fixtures
ext/
├── sharp/sharp.c, php_sharp.h        interned types, sharp_type_accepts, the statics store, class values
├── sharp/sharp.stub.php              \Sharp\Internal\accepts, statics and equals
├── sharp/sharp_unit.h                the header the merged bridge generates
├── reflection/                       getTypeArguments(); the store stays hidden
├── standard/, spl/                   serialize keeps type arguments; unserialize checks; untypable references refused
└── opcache/                          the file cache, persistence and both JITs
docs/
├── decisions/072-reified-generics.md NEW
├── architecture/slices/11-generics.md NEW: the R3 to R5 design other Slices build against
└── spec.md                           the section 11 rules the checker enforces
sharp/
├── baseline/spec/                    24 examples that pass leave the list
└── mago/
    ├── crates/syntax/
    │   ├── src/cst/cst/instantiation.rs    GenericClass, a class with type arguments read as an expression
    │   ├── src/cst/cst/type_of.rs          typeof keeps its type arguments
    │   ├── src/cst/cst/class_like/method.rs  a method's type parameters, in the arena
    │   ├── src/utils/pattern.rs            type_test_of, the one decision of what a type test runs
    │   ├── src/parser/                     type parameters and arguments, GenericClass, new (value)(…); each statement arm returns its Result
    │   ├── src/error.rs                    NamedConstructorTypeParametersInSharp
    │   └── tests/sharp.rs
    ├── crates/names/                       a type parameter binds to its declaration; a GenericClass binds as a class
    ├── crates/codex/                       PHP# generics as templates; out and in as variance; a static method's class type parameters
    ├── crates/fingerprint/                 a class's, an interface's and a method's type parameters
    ├── crates/orchestrator/                a warm compile after a bound edit matches a clean one
    ├── crates/analyzer/
    │   ├── src/artifacts.rs                inferred type arguments, tested types, statics' type arguments
    │   ├── src/invocation/                 inference, CS0411, a written type argument checked as a type
    │   ├── src/expression/                 is, as, match over every type; typeof; new through a class value
    │   ├── src/resolver/                   statics and class values with type arguments
    │   ├── src/statement/                  variance, erased signatures, Serializable, generic catch, is_map_key
    │   ├── src/utils/template.rs           variance checks and spec 11.1's wording
    │   └── tests/sharp.rs
    ├── crates/semantics/                   the generics slice of check_slice
    ├── crates/sharp-bridge/
    │   ├── src/kind.rs                     SHARP_AST_VERIFY_TYPE_ARGS, SHARP_TYPE_OF, SHARP_IS_TYPE, SHARP_CLASS_METADATA
    │   ├── src/lower.rs                    type arguments on new and calls; type tests, statics, class values; the entry checks
    │   ├── src/lower/types.rs              class-like metadata and the check texts
    │   └── tests/lower.rs
    └── composer/src/Sdk/Syntax/NodeKind.php  GenericClass in the extension SDK's node kinds

The analyzer ignored the type arguments of `new C<A>(…)` and `x.m<A>(…)`,
let `new` of a PHP# generic class omit them, checked `in` and `out` only
on bare parameter and return types with `@template-covariant` messages,
reported a substitution a missing marker blocks as a plain mismatch, and
added its own errors on lines `check_slice` refuses.

Written type arguments are converted in the caller's scope, checked for
count and bounds as a written generic type is, and seeded as the
shallowest bounds of their templates before the arguments, as a
receiver's type arguments are. In a PHP# file the templates bound before
the arguments are fixed, so an argument infers only the others; this
generalizes the rule PHP# collections already followed. `new` of a PHP#
generic class without type arguments names the ones to write.

PHP# classes check spec section 11.1 on every member another class
reaches, nesting positions through type arguments, lists, maps and
function types, and one helper rewrites an argument, return, typed-local
or property mismatch that only a missing marker blocks into the spec's
message with the marker to add. A member read or call on a type
parameter, `typeof` and `new` of one are refused without a second error,
and a typed local's generic type is checked for its bounds.
The bridge lowered a type parameter such as `TItem` as a class named
`TItem`, every type with type arguments as `array`, so `PaginatedList<Order>`
and `Class<Model>` became `array`, and a loop key written as a type
parameter read back through `\TItem::from`. PHP refuses or misruns each.

Generics are erased as the PHP twin written with `@template` declares
them. One walk over the file records each type parameter's PHP type: its
bound's class, its bound's classes as one `TYPE_INTERSECTION`, or `mixed`
without a bound. Every type then lowers through that erasure: a generic
class type is its class, `Class<T>` is `string`, `List` and `Map` stay
`array`. A union leaves out a member another member holds, so it never
names a type twice or an intersection beside one of its classes, and a
union that holds `mixed` is `mixed`. `?` adds `ZEND_TYPE_NULLABLE` to one
type, PHP's `(A&B)|null` to an intersection, and nothing to `mixed`. A
loop key whose type erases to one class reads back through that class.

Type parameter lists, the type arguments of `new` and of calls, and a
header entry's type arguments lower to nothing. The tests pin each
against its PHP twin's tree.
A generic `.sharp` file failed to parse at its first type parameter,
while spec section 11 writes generics throughout. With the bridge from
a Mago commit that lowers them erased, every section 11 example that
G1 compiles now runs and compiles to the opcodes of its PHP twin.

Run generic classes, interfaces and methods:
- A type parameter is its bound's PHP type, or `mixed` without one,
  and `DatabaseEntity & Shareable` is their intersection
- `new PaginatedList<Order>(…)`, `Store.pick<Order>(…)` and the same
  call with its type argument inferred run as the call without them
- `OrderPage : PaginatedList<Order>` extends `PaginatedList`
- An `out TItem` class passes where its supertype is expected, and a
  `Validator<DatabaseEntity>` passes as a `Validator<Order>`
- `Class<T>` is `string`, so a `Map<string, Class<DatabaseEntity>>`
  holds class names

Compare generics with their twin:
- The twin writes `@template`, `@template-covariant`,
  `@template-contravariant`, `@extends` and `@implements`, and its
  docblocks are pinned as the only signature difference, because doc
  comments do not reach the engine
- `$_main` declares `Order` and `OrderPage` at run time, as a header
  that names a parent class does in Site

The tests need the bridge from a Mago commit with generics, so the pin
in ext/sharp/Cargo.toml moves before this merges.

Zend/tests/sharp/
├── Generics.sharp    <- added, every section 11 example G1 compiles, each run
├── Generics.inc      <- added, the PHP twin of Generics.sharp
├── generics.phpt     <- added, runs each example and reflects the erased types
└── opcodes.phpt      <- compares Generics with its twin
PHP# generics (G1) branched from master at 705925d. Master has since
merged ten PRs, ending with typed compilation's Slice D (#34), which
lowers through the typed entry point (`check`/`lower` with `Types`) and
analyzes every file before it lowers. G1 has to sit on that master, and
its erasure has to run inside D's typed lowering.

Six files conflicted. Each keeps both sides:
- sharp-bridge/src/lower.rs: D's `Unit`, `inlined` forms and typed
  `class_header` stay. G1's `type_parameters` table, `erase`, `php_type`
  and `PhpType` run inside them. `class_header` and `name_list` read a
  header entry through `header_name`, so `PaginatedList<Order>` is its
  class in both. D's `key_read_back` replaces G1's hint-based
  `read_back`: a loop key reads back by the Map's analyzed key type.
- names/src/internal/walker.rs: master's `resolve_class` (standard
  library names in the `Sharp` namespace) resolves every class name G1's
  binder does not bind to a type parameter first: hints, header entries,
  `new`, `typeof` and a bare name before `.`. G1 had removed
  `walk_in_inheritance`, since `walk_in_hint` resolves header entries.
- semantics/src/internal/checker/sharp.rs: G1's `check_generic` keeps
  master's Map key rule: a key outside the slice is refused once, as
  that type, and a Map key refusal still checks the type arguments
  (`report_refusal`). The `void` type argument arm keeps its
  `return None`, which git had dropped. The docs and the method body
  "supported" text carry both sides' additions (type arguments and
  `exit(code)`).
- analyzer/src/expression/mod.rs: `is_refused` keeps G1's type parameter
  refusals and drops the `typeof(X)` member refusal, as master's class
  value reads require. A chain rooted at `typeof(T)` of a type parameter
  stays refused.
- analyzer/src/utils/names.rs: master's `display_sharp_type(union,
  codebase)` is the one renderer. G1's atomic version goes, and
  `explain_blocked_substitution` calls master's.
- analyzer/tests/sharp.rs: both sides appended tests at the same place.
  Both sets stay.

Auto-merged files that needed follow-through:
- analyzer/src/expression/call/mod.rs: master's class value static calls
  pass the call's type arguments, as G1's `Class.m<T>()` path does.
- sharp-bridge/tests/lower.rs: G1's tests use D's harness. They read the
  root through `Lowered::root()` and declare the library classes they
  name, because D analyzes each file before it lowers.
- semantics/tests/fixtures/slice.sharp: D analyzes the fixture, so G1's
  generic section is analyzer-clean: `Page` implements `Listing`, `out`
  moves to `Source`, type arguments satisfy their bounds, and `TKey`'s
  bound is `Comparable<Version>`, because the analyzer cannot resolve a
  type parameter inside its own bound.
- G1 files formatted with rustfmt 1.9.0 of the 1.97.0 toolchain.

Extension protocol minors stay at G1's analyzer 1.8 and linter 1.2.
Master bumped neither.

One test stays red until the next commit:
`a_loop_key_written_as_a_type_parameter_reads_back_as_its_bound`. D
analyzes before it lowers, and the analyzer does not yet read a type
parameter's bound as a Map key, so `Map<TKey, int>` with
`TKey : Status` is refused. The next commit teaches the analyzer and the
bridge that bound, with the multi-bound key.

crates/
├── analyzer/src/expression/call/mod.rs     <- class value calls take type arguments
├── analyzer/src/expression/mod.rs          <- is_refused: type parameters, no typeof(X) member
├── analyzer/src/utils/names.rs             <- one display_sharp_type
├── analyzer/src/utils/template.rs          <- calls master's display_sharp_type
├── analyzer/tests/sharp.rs                 <- both sides' tests
├── names/src/internal/walker.rs            <- type parameters, then resolve_class
├── semantics/src/internal/checker/sharp.rs <- check_generic with master's Map key rule
├── semantics/tests/fixtures/slice.sharp    <- generic section analyzer-clean
├── sharp-bridge/src/lower.rs               <- G1 erasure inside D's typed lowering
└── sharp-bridge/tests/lower.rs             <- G1 tests on D's harness
…atures sound

Problem

A `Map<TKey, int>` with `TKey : Status` was refused, because the analyzer
and the bridge looked for a backed enum only in an enum key, never in a
type parameter's bound. A bound of several members lost the enum when the
interface came first: `HasLabel & Status` reads as `HasLabel` with `Status`
joined to it.

A method that implements a generic parent with a narrower parameter, as
`OrderValidator : Validator<Order>` with `validate(Order item)`, passed the
checker, which compares the substituted types. PHP compares the erased
types: `Validator<in TItem>` takes `mixed`, so the engine failed with a
fatal error when it linked the class. A field over a generic parent's field
had the same gap, and the checker compared it against the parent's
unsubstituted `TItem`.

`value is TItem`, `value as TItem` and a `match` arm of `TItem` added a
`non-existent-class-like` issue beside the slice's own refusal.

Solution

`get_backing_key_type` reads a type parameter's bound and each member of an
intersection, so the key reads back as the backed enum in either member
order. The bridge's `backed_enum` reads the same bound through
`Types::class_declaration` and emits one direct `\Status::from($key)`. A
key without a backed enum stays refused: a PHP array cannot hold an object
key.

In a `.sharp` file, the analyzer erases both signatures as the bridge's
`erase` does and refuses a parameter narrower than the parent's erased
type, naming that type and the bound that makes both sides erase alike. A
field must erase to the parent field's erased type, and is first checked
against the parent's type with the header's type arguments. A wider return
needs no new check: the substituted check and the bound check of the
header already refuse it.

`is_refused` covers `is`, `as` and `match` of a type parameter, in an
expression and in a statement.

crates/
├── analyzer/
│   ├── src/expression/mod.rs                      is_refused covers is, as and match of a type parameter
│   ├── src/statement/mod.rs                       a refused match statement adds no issue; a bounded key reads back as one enum
│   ├── src/statement/class_like/method_signature.rs  erase, erased parameter check, bound example
│   ├── src/statement/class_like/mod.rs            call the erased check; erased field check; report the new issue
│   └── tests/sharp.rs                             bounded Map keys, erased signatures, is/as/match of a type parameter
├── codex/src/ttype/mod.rs                         get_backing_key_type reads a type parameter's bound
├── semantics/tests/fixtures/slice.sharp           two generic implementations that PHP refused now link
└── sharp-bridge/
    ├── src/lower.rs                               backed_enum reads a type parameter's bound
    └── tests/lower.rs                             bounded loop keys and erased signatures, lowered
Problem

A `Map` key holds a backed enum when it names the enum, or when it is a
type parameter whose bound has the enum among its members. Three copies
of that walk decided it, and they disagreed on what counts as the enum.
`get_backing_key_type` took only an enum object and read its backing
type. The analyzer's loop-key check took any enum object, backed or not.
The bridge also took a named class, through `Types::class_declaration`.

Solution

`get_backed_enum` in codex walks the bound once: a type parameter is its
one-member bound, and the bound and each of its intersection members are
tried in written order. A member is the enum when it names an enum, as
an enum or a named object, that has a backing type. It returns the
enum's metadata, so `get_backing_key_type` reads its backing type, the
analyzer its name, and the bridge, through `Types::backed_enum`, its
declared name. `DeclarationKind::Enum` drops `backed`, which only the
bridge's copy read.

crates/
├── codex/src/ttype/mod.rs                 get_backed_enum; get_backing_key_type reads it
├── analyzer/
│   ├── src/statement/mod.rs               report_key_mixing_a_backed_enum reads get_backed_enum
│   └── tests/sharp.rs                     a key's backed enum: the enum, each bound order, none
└── sharp-bridge/src/
    ├── lower.rs                           backed_enum reads Types::backed_enum
    └── lower/types.rs                     Types::backed_enum; DeclarationKind::Enum without backed
Problem

The checker refused correct PHP# generics and accepted wrong ones.

- A bound could not name a type parameter of its own list. The scanner
  read each bound before it added that parameter to the type context, so
  `TItem` in `Sorted<TItem : Comparable<TItem>>` became a class named
  `TItem`, and `Sorted<Version>` was refused. The bound check then
  skipped every bound that names a template, so once the bound was read
  right, `Sorted<Line>` would pass.
- Spec section 11.1 did not check a header. `Sink<in TItem> :
  Source<TItem>` with `Source<out TItem>` hands `TItem` out and passed,
  where C# (CS1961) and Kotlin refuse it. `Class<TItem>` did not count as
  a use of `TItem` either.
- A header with the wrong number of type arguments in a `.sharp` file
  told the user to fix an `@extends` tag, which PHP# has no form for.
- The erased-signature check ran only when no other issue was found, so
  a renamed parameter hid an erased one. It also ran only in `.sharp`
  files, so a PHP class whose `@extends Box<Order>` narrows `put` of a
  PHP# `Box<TItem>` passed and failed when the engine linked it. A PHP
  class over a PHP# field compared its type with the raw type
  parameter, and its help named `('TItem.demo\slot extends mixed)|null`.

The generics changeset also held copies: three short-name helpers, two
English-list builders, two erased-type helps, two angle-bracket list
loops, the built-in generic names twice, a walker fixture constant
beside the slice fixture, and a test the Capability tests already cover.

Solution

`scan_type_parameters` reads a type parameter list for a class and a
method: every name of the list enters the type context first, with a
`mixed` bound, then each bound is read and each template recorded with
its real bound. `check_template_arguments` puts the written arguments
into a PHP# bound that names the owner's type parameters before it
checks the bound. In PHP it skips that bound, as Mago did.

`find_template_uses` counts each header entry as an output position,
wrapped in the parent's variance, and `Class<T>` as a use that keeps its
position. The header is reported on its entry, in spec 11.1's message.
`check_template_parameters` no longer reports a PHP# header's variance,
which the header check reports, and speaks of type arguments and the
header form in a `.sharp` file. A `.php` file keeps its text.

The erased-signature and erased-property checks run when the only
issues so far are renamed parameters, and when either the parent or the
overriding class is PHP#. A field's parent type is filled with the
child's type arguments under the same condition, so a PHP class over a
PHP# field gets the erased-type report. A PHP class over a PHP class is
unchanged.

One `short_name` and one `and_list` live in `utils/names`, one
`erased_type_help` builds both erased-type helps, `built_in_generic_arity`
holds the built-in generic names, and `parse_angle_bracket_list` parses
both angle-bracket lists. The walker test reads the slice fixture.

crates/
├── codex/src/scanner/
│   ├── ttype.rs                           scan_type_parameters: names first, then bounds
│   ├── class_like.rs                      class list through scan_type_parameters, keeps variance
│   └── function_like.rs                   method list through scan_type_parameters
├── analyzer/
│   ├── src/statement/function_like/mod.rs check_template_arguments fills a PHP# bound with its arguments
│   ├── src/statement/class_like/
│   │   ├── mod.rs                         header spans; header arity in PHP#; erased checks and field parent type when either class is PHP#
│   │   └── method_signature.rs            erased_type_help; short_name from utils/names
│   ├── src/utils/
│   │   ├── template.rs                    header entries and Class<T> in find_template_uses
│   │   └── names.rs                       short_name, and_list
│   ├── src/expression/
│   │   ├── instantiation.rs               report_missing_type_arguments reads short_name, and_list
│   │   └── access/mod.rs                  and_list and short_name moved to utils/names
│   └── tests/sharp.rs                     bounds, header variance, Class<T>, header arity, renames, PHP over PHP# method and field
├── semantics/src/internal/checker/sharp.rs built_in_generic_arity read by is_slice_type and is_built_in_generic
└── syntax/
    ├── src/parser/internal/type_hint.rs   parse_angle_bracket_list
    └── tests/walker.rs                    reads slice.sharp; GENERICS deleted; 468 sources
…ew Self keeps its type parameters

Problem

`new Self(…)` in a generic PHP# class was refused for naming no type
arguments, though `Self` is the class with its own type parameters, as
in a return type. `new Self<…>(…)` passed the checker.

The checker refused `value is PaginatedList<Order>` and
`value as PaginatedList<Order>`, and the analyzer still reported them,
because the two kept separate walks of an erased type and disagreed on a
generic class type. Four places copied the match that reads a header
entry's name, and the scanner and a test read `in` and `out` through two
methods on `TypeParameter` instead of `Variance`.

Solution

`new Self(…)` takes the class's own type parameters, from
`get_this_type`, as written ones: they bound the constructor and type
the value, so it passes where `Repo<TItem>` is expected and not where
`Box<int>` is. `check_slice` refuses `new Self<…>(…)` with "`Self`
already carries its class's type parameters."

`ResolvedNames::erased_type` is the one walk of the part of a type that
needs a type argument while the code runs. `check_slice` refuses with it
and `is_refused` skips with it, so the analyzer adds nothing on a line
the checker refused. `Inheritance::names` yields each header entry's
name for the scanner, the analyzer, `check_header` and the bridge.
`Variance` converts from a `TypeParameter`, beside its two `From` impls,
and `TypeParameter::is_covariant` and `is_contravariant` are deleted.

crates/
├── syntax/
│   ├── src/cst/cst/class_like/inheritance.rs   + Inheritance::names
│   ├── src/cst/cst/type_hint.rs                - TypeParameter::is_covariant, is_contravariant
│   └── tests/sharp.rs                          header_names reads names(); a non-class entry names nothing; variance read directly
├── names/
│   ├── src/lib.rs                              + ResolvedNames::erased_type
│   └── tests/binder.rs                         the erased part of each kind of type
├── semantics/
│   ├── src/internal/checker/sharp.rs           new Self<…> refused; erased_type and check_header read names; - erased_type, type_parameter_in
│   └── tests/sharp.rs                          new Self names no type arguments
├── codex/src/
│   ├── ttype/template/variance.rs              + From<&TypeParameter> for Variance
│   └── scanner/class_like.rs                   header through names(), variance through Variance::from
├── analyzer/
│   ├── src/expression/instantiation.rs         new Self takes the class's own type parameters
│   ├── src/expression/mod.rs                   is_refused reads erased_type; - names_type_parameter; tests_erased_type
│   ├── src/statement/class_like/mod.rs         header through names(); the variance check reads the header's generic spans
│   └── tests/sharp.rs                          new Self carries its type parameters; is/as of a generic class type adds nothing
└── sharp-bridge/src/lower.rs                   header through names(); - header_name
Problem

Section 11 says `new` always names its type arguments, as in
`new PaginatedList<Order>(…)`. `new Self(…)` in a generic class names
none, and the checker accepts it, so the spec and the checker disagree.

Solution

Section 11 names `new Self(…)` as the one exception: `Self` is the class
with its own type parameters, so it names no type arguments.

docs/
└── spec.md    section 11: new Self(…) names no type arguments
Problem

A PHP# type parameter is meant to be opaque, as C#'s `T` is. Mago treated it
as a PHP template bounded by `mixed`. So `1` passed where `TItem` was
required in `new Box<TItem>(1)`, `this.take<TItem>(1)`, `TItem x = 1`,
`return 1` and `new Self(1)`. A call also inferred bounds for the caller's
own type parameters. A self-referential bound such as
`TItem : Comparable<TItem>` refused correct programs. Two flags covered PHP#
comparison rules, and several type-argument messages printed Mago's internal
ids and PHP wording.

Solution

`ComparisonResult` now carries one flag, `sharp_rules`, which
`ComparisonResult::for_dialect` sets for a `.sharp` file.
`with_strict_nonnull` is deleted. Under that flag, a type parameter takes
only itself, a type parameter whose bound reaches it, or `never`. Template
inference in PHP# binds only the call target's own templates. A bound that
names its own list is checked against the written type arguments.

`check_template_arguments` now speaks of type arguments and short class
names in `.sharp`. The Map-key error and `display_sharp_type` now print a
type parameter by its name and an intersection as `A & B`. A call's type
arguments may name `From` or `Enum`. `missing_cases` uses `short_name`.

The erased-signature guard folds into
`validate_erased_signature_compatibility`. `Types::backed_enum` takes the
union, and `Lowering::backed_enum` is deleted. `is_built_in_generic` and an
always-true `is_sharp` check are deleted, along with four redundant tests.

crates/
├── codex/src/ttype/comparator/
│   ├── mod.rs                 sharp_rules, for_dialect; with_strict_nonnull deleted
│   ├── atomic_comparator.rs   opaque type parameters, is_same_type_parameter
│   ├── generic_comparator.rs  a type parameter passes as its bound
│   └── union_comparator.rs    carries sharp_rules
├── analyzer/
│   ├── src/invocation/
│   │   ├── arguments.rs           invalid-argument, not possibly-invalid
│   │   └── template_inference.rs  is_inferable: only the target's templates
│   ├── src/statement/
│   │   ├── mod.rs                 always-true is_sharp check deleted
│   │   ├── return.rs              sharp_rules
│   │   ├── function_like/mod.rs   PHP# type-argument wording, bounds over arguments
│   │   └── class_like/
│   │       ├── mod.rs                 erased guard moved out
│   │       ├── method_signature.rs    guard folded into the erased check
│   │       ├── constant.rs, property.rs  for_dialect
│   ├── src/expression/
│   │   ├── mod.rs                 missing_cases uses short_name
│   │   └── assignment/{mod,property_assignment,static_property_assignment}.rs  for_dialect
│   ├── src/utils/
│   │   ├── names.rs               type parameter and intersection display
│   │   └── template.rs            one find_map
│   └── tests/sharp.rs             new tests with PHP twins
├── syntax/
│   ├── src/parser/stream.rs   `from` and `enum` in call type arguments
│   └── tests/sharp.rs         From/Enum call test
├── semantics/src/internal/checker/sharp.rs  is_built_in_generic inlined
├── sharp-bridge/
│   ├── src/lower.rs           Lowering::backed_enum deleted
│   ├── src/lower/types.rs     Types::backed_enum takes the union
│   └── tests/lower.rs         two redundant tests deleted
└── linter/src/external/mod.rs redundant node-kind test deleted
…rameters

Problem

A PHP# type parameter is opaque under spec section 11, but three paths still
let it through. A function type compared its parameters and its return with a
fresh comparison that dropped the PHP# rules, and a `mixed`-templated return
passed anything, so `Function<TItem()> maker() => () => 1;` reported nothing.
Defaults were skipped wherever the declared type held a type parameter, so
`TItem item = 1` passed. A `TItem` value passed where an `int` was required as
a too-general value, not as an invalid one.

The messages generics make reachable in a `.sharp` file printed Mago's ids:
`('TItem.demo\box extends mixed)`, `Demo\PaginatedList<Demo\Order>`,
`string('text')`, `int|null`, and erased parent types as
`array<array-key, mixed>`.

Solution

`ComparisonResult::nested` gives every nested comparison the rules of its outer
one, and replaces each hand-built `ComparisonResult { sharp_rules, .. }`. The
callable comparator keeps the templated-return shortcut for PHP only. A PHP#
type parameter input is contained only by the same type parameter, or through
a class bound by a class type, and the special case in the generic comparator
goes away. Defaults are checked in `.sharp` whatever their type parameters.

`display_type` prints a type as the analyzed file writes it: as PHP# writes it
in `.sharp`, by its Mago id in PHP. Every argument, return, assignment,
default, missing-return, bound, override and member-access message uses it,
and `display_sharp_type` now writes function types, `Class<T>` and literals.
An erased parent type prints as PHP declares it: `array`, `mixed`, a class.
PHP messages and PHP issues are unchanged.

`InvocationTarget::get_sharp_collection_receiver` folds into `guess_name`, its
only caller. Formatting the workspace also reflowed three files the formatter
had flagged at the parent commit.

crates/
├── codex/src/ttype/comparator/
│   ├── mod.rs                  ComparisonResult::nested, sharp_rules doc
│   ├── atomic_comparator.rs    opaque type parameter input, nested()
│   ├── generic_comparator.rs   special case deleted, nested()
│   ├── callable_comparator.rs  nested(), PHP-only templated-return shortcut
│   ├── union_comparator.rs     nested(), no bound expansion in PHP#
│   ├── iterable_comparator.rs  nested()
│   └── array_comparator.rs     nested()
├── analyzer/src/
│   ├── utils/names.rs          display_type, function types, Class<T>, literals
│   ├── utils/mod.rs            get_type_diff in PHP# types
│   ├── utils/template.rs       formatting only
│   ├── invocation/arguments.rs argument messages, opaque overlap check
│   ├── invocation/mod.rs       guess_name absorbs the collection receiver
│   ├── invocation/template_inference.rs  bound violation message
│   ├── expression/assignment/mod.rs                typed local message
│   ├── expression/assignment/property_assignment.rs property write message
│   ├── statement/return.rs     return, mixed, nullable and hook messages
│   ├── statement/function_like/mod.rs  defaults checked, missing return, type arguments
│   ├── statement/class_like/property.rs  defaults checked, default message
│   ├── statement/class_like/mod.rs  header bound, override and property messages
│   ├── statement/class_like/method_signature.rs  types kept as TUnion, display_erased
│   ├── resolver/method.rs      method call on a type parameter names it
│   └── resolver/property.rs    property read on a type parameter names it
├── analyzer/tests/sharp.rs     eight new tests with PHP twins, updated messages
├── names/tests/binder.rs       formatting only
└── sharp-bridge/
    ├── src/lower.rs            formatting only
    ├── src/lower/types.rs      formatting only
    └── tests/lower.rs          hook message says `Any?`
…s as PHP# does

Problem

A PHP# type parameter with no bound may hold `null`, yet the checker let
it pass where `Any`, the non-null `mixed`, is required. The comparator's
`mixed` container arm returned true for any input before PHP#'s opaque
type-parameter rule ran, so `Any give(TItem item) => item;`,
`Sink.take(item)` into `Any value` and `Any held = item;` reported nothing.

Four messages still spoke PHP in a `.sharp` file. A property accessor read
`Demo\Box::$total::get` in every message that names a hook: a refused,
nullable, falsable or `mixed` `get` return, a `get` block that can end
without returning, a missed abstract hook, an overridden final hook and a
by-reference hook. `unused-template-parameter` read "Template parameter
`TItem` is never used in class `Demo\Page`" with a `@template` docblock
help. The override parameter message named the parameter `$item`.

Solution

Under `ComparisonResult.sharp_rules`, a non-null `mixed` container refuses
a `TGenericParameter` input whose bound accepts `null`, as Kotlin bounds an
unbounded `T` by `Any?`. `Any?` still takes it, and a bounded
`TItem : DatabaseEntity` still passes as `Any`.

`display_sharp_accessor` in `utils/names.rs` names an accessor as C# does,
`Box.total.get`, and every site that formats a hook name uses it in
`.sharp`. `unused-template-parameter` follows the header-bound message's
`.sharp` branch: "Type parameter `TItem` is never used in class `Page`."
with the help "Remove `TItem` from `Page<…>`.", using the declaring kind's
own word for a class, an interface or a method. The override parameter
message names the parameter without `$`, as the erased-parameter message
beside it does. Every `.php` message and issue is unchanged, and each new
`.sharp` test has a `.php` twin pinned to what Mago reported before.

crates/
├── codex/src/ttype/comparator/
│   └── atomic_comparator.rs    non-null mixed refuses a type parameter whose bound takes null
├── analyzer/src/
│   ├── utils/names.rs          display_sharp_accessor
│   ├── statement/return.rs     get-return messages name the accessor
│   ├── statement/class_like/property.rs  missing-return names the accessor
│   ├── statement/class_like/mod.rs  abstract, final and by-reference hook names, unused type parameter, override parameter
│   └── statement/function_like/mod.rs  unused method type parameter
├── analyzer/tests/sharp.rs     five new tests with PHP twins, three updated messages
└── sharp-bridge/tests/lower.rs  mixed-return message names `Report.b.get`
Problem

Spec section 11 lists how a type parameter's bound is written, but not
what a type parameter without one may hold. The checker now refuses an
unbounded `TItem` where `Any` is required, and the spec did not say why.

Solution

Section 11's list of type-parameter rules says that a type parameter with
no bound may hold `null`, so it is bounded by `Any?`.

docs/
└── spec.md    section 11: an unbounded type parameter is bounded by Any?
Problem

PHP# treats a type parameter as opaque, as C# treats `T`, but review round 4
found seven places where the checker still broke that rule, and one family of
messages that still printed Mago ids:

- An override's return and parameter types were compared with PHP's rules, so
  `int pick<T>(T item)` overrode `T pick<T>(T item)`, and `int next()`
  overrode `TItem next()`, with no error.
- A collection method on a property read the declaring class's raw property
  type, so `other.items.add(item)` put a `TItem` into a `Shelf<Order>`.
- Function types skipped `Any`/`Any?` parameters, treated an `Any` return as
  unchecked, and let a lambda that returns nothing stand for
  `Function<TItem()>`.
- `Class<TItem>` was compared through its bound, so it took
  `typeof(Order)` and any `Class<TOther>`.
- A written `Any?` or `Any` type argument skipped the bound check.
- A pattern variable over a type parameter kept the type parameter, so
  `item is int n ? n : 0` was refused.
- A null guard on an unbounded `TItem` parameter was reported as a nullable
  parameter the method rejects, though no `?` can be dropped.
- `.sharp` messages printed `('TItem.demo\box extends ...)`, `positive-int`,
  `class-string`, `object`, `null|string`, `list<int>`, `mixed` and
  "template" wording.

Solution

- The comparators follow PHP#'s rules wherever `sharp_rules` is set: a
  function type checks every parameter and an `Any` return, `void` no longer
  fits a type parameter, `Class<TItem>` is the type parameter's own class
  type, and a type parameter passes as any type that holds its whole bound.
- An override is compared with the file's dialect, after mapping the child
  method's type parameters onto the parent's by position when their bounds
  match.
- A property read through a receiver is localized to the receiver's type
  arguments with the new `get_localized_property_type`, for collection
  method calls and for lambdas assigned to a `this` property.
- A written `Any`/`Any?` type argument is checked against the bound in PHP#.
- A nullable-parameter rejection counts only null the parameter's type writes.
- Every listed message names its types through `display_type`, and the
  template wording says "type parameter" and "bound" in `.sharp`.
- Every PHP behavior is unchanged, pinned by a `.php` twin in each test.

crates/
├── analyzer/
│   ├── src/
│   │   ├── expression/
│   │   │   ├── assignment/mod.rs                 declared_target_type localizes `this.prop`
│   │   │   └── binary/
│   │   │       ├── comparison.rs                 null and false operand messages use display_type
│   │   │       └── null_coalesce.rs              redundant `??` message uses display_type
│   │   ├── invocation/
│   │   │   ├── arguments.rs                      nested Any?, spread messages; Class<TItem> is opaque
│   │   │   └── template_inference.rs             "type parameter ... bounded by" in .sharp
│   │   ├── resolver/
│   │   │   ├── method.rs                         get_declared_collection localizes the property
│   │   │   └── property.rs                       get_localized_property_type; nullsafe message
│   │   ├── statement/
│   │   │   ├── class_like/
│   │   │   │   ├── method_signature.rs           dialect comparison, method type parameter mapping
│   │   │   │   └── mod.rs                        @var override message uses display_type
│   │   │   ├── function_like/
│   │   │   │   ├── mod.rs                        written Any checks the bound; overly-wide message
│   │   │   │   └── rejected_nullable_parameter.rs  null from a type parameter's bound is skipped
│   │   │   └── return.rs                         mixed and nested-mixed notes say Any? in .sharp
│   │   └── utils/names.rs                        int, string, Class<Object>, Object
│   └── tests/sharp.rs                            10 new tests, 7 updated, .php pins
└── codex/src/ttype/comparator/
    ├── atomic_comparator.rs                      type parameter passes as a type holding its bound
    ├── callable_comparator.rs                    Any parameters and an Any return are checked
    ├── class_string_comparator.rs                Class<TItem> takes only Class<TItem>
    ├── mod.rs                                    sharp_rules doc
    └── union_comparator.rs                       void fits no opaque type parameter
…and refuse erased type tests

Problem

G1 erases type parameters while the code runs, and the checker treats them
as opaque. Review round 4 left five places where PHP# let a wrong value
through or gave the user a wrong or unclear error:

- A private member was exempt from `in`/`out`, and any instance of the class
  could reach it, so `Cell<out TItem>.poison(Cell<Any?> target)` wrote `1`
  into `target.value`.
- A static member could name its class's type parameters, though every
  `Box<…>` shares one static.
- `is`, `as` and a `match` arm with written type arguments, as in
  `item is List<int> numbers`, compiled to a test of the erased type.
  `as List<int>` passed silently. The `is` form reported `invalid-operand`,
  `undefined-variable` and `mixed-argument` instead of one clear error.
- An override that changed a method type parameter's bound printed
  "expects type `T` but parent … expects type `T`".
- A generic type written without type arguments, as in
  `void f(PaginatedList page)`, reported nothing. Only `new` was checked.

Solution

- A private member, or a property whose `set` is private, that breaks its
  class's `out`/`in` stays allowed. Reaching it through any receiver but
  `this` is `invalid-template-parameter`: "`value` breaks `out TItem`, so it
  is reachable only through `this`." The check runs on reads, writes, calls
  and method values. `find_broken_marker` is the one rule shared with the
  member variance check.
- `check_slice` refuses a class type parameter anywhere in a static field,
  property or method: "A static member can't use `TItem`, because every
  `Box<…>` shares it." A static method's own type parameters stay legal.
- `ResolvedNames::erased_type` returns every type with type arguments, `List`
  and `Map` included, so `check_slice` refuses it in a pattern, `as` and a
  `match` arm with "This type is not supported yet in PHP#." The analyzer
  gives a refused `is`'s pattern variable its written type and adds no issue.
- An override that changes a bound keeps `incompatible-parameter-type` and
  names the bound: "`AnyPicker.pick<T>` must keep the bound `DatabaseEntity`
  of `Picker.pick<T>`." An added bound reads "must keep `T` of
  `Taker.take<T>` without a bound."
- `report_missing_type_arguments` checks a type as well as `new`, for a
  property, a parameter, a return type and a local, with one message:
  "`PaginatedList` needs its type argument, as in `PaginatedList<TItem>`."
  `Self` is exempt. A local is checked as written, before expansion fills
  the type arguments it leaves out.
- Every PHP behavior is unchanged, pinned by a `.php` twin in each test.

crates/
├── analyzer/
│   ├── src/
│   │   ├── expression/
│   │   │   ├── instantiation.rs          report_missing_type_arguments owns the rule, one message
│   │   │   └── mod.rs                    a refused `is` declares its pattern variables
│   │   ├── resolver/
│   │   │   ├── method.rs                 a call checks the private member's reach
│   │   │   └── property.rs               reads, writes and method values check the reach
│   │   ├── statement/
│   │   │   ├── class_like/
│   │   │   │   ├── method_signature.rs   ChangedTemplateBound when a bound differs
│   │   │   │   └── mod.rs                renders the bound message, shares find_broken_marker
│   │   │   ├── function_like/mod.rs      a type without type arguments is reported
│   │   │   └── mod.rs                    a typed local is checked before expansion
│   │   └── utils/template.rs             find_broken_marker, check_private_*_reach
│   └── tests/sharp.rs                    4 new tests, 1 updated, .php pins
├── names/
│   ├── src/lib.rs                        erased_type returns every type with type arguments
│   └── tests/binder.rs                   List and Map expectations
└── semantics/
    ├── src/internal/checker/sharp.rs     static members refuse the class's type parameters
    └── tests/sharp.rs                    3 new tests, 2 updated, .php pins
… under generics

Problem

Section 11 did not say three rules the checker now enforces. A private
member may break its class's `in`/`out`. A static member can't use its
class's type parameters. A type, not only `new`, names a generic class's
type arguments.

Solution

Three sentences in section 11:

- "Writing type arguments" adds "A type names them too:
  `PaginatedList<Order> page`."
- "Declaring type parameters" adds "A static member can't use its class's
  type parameters, because every `Box<…>` shares one."
- 11.1 adds "A private member may break the marker, and is then reachable
  only through `this`."

docs/
└── spec.md    section 11: written type arguments, static members, 11.1 private members
… rules

Problem

PHP# treats a type parameter as opaque, as C# does, but review round 5
found eight places where the checker or the analyzer still let a value
through, refused a correct override, or worded an issue wrongly:

- null passed as an argument where an unbounded type parameter is the
  parameter type.
- An override was refused when the parent method's bound named the
  parent class's type parameter, as `count<TQuery : Query<TEntity>>`
  overridden in a `Repository<Order>`.
- The help of a blocked substitution named `out` or `in` even when that
  marker allows only the opposite substitution.
- A bound that named a sibling type parameter saw it unbounded, as
  `<TKey : DatabaseEntity, TItem : Holder<TKey>>`.
- Type arguments written on a method call checked their bound without
  the receiver's type arguments.
- A class constant could use its class's type parameters.
- `is`, `as` and `match` of a function type were accepted or refused
  with the generic message, although a function type runs as a
  `Closure` of any signature.
- A property whose read is public and whose `set` is private was
  reported as "reachable only through `this`".

The same rules also lived in several copies: four nullable type
displays, two arity reports, two receiver loops around
`get_localized_property_type`, an index round trip for a changed
override bound, and a second null guard in the atomic comparator.

Solution

- `verify_argument_type` asks `writes_null` in a `.sharp` file, the
  helper the rejected-nullable-parameter rule already uses, now
  `has_null() || has_nullable_mixed() || is_void()`.
- `apply_template_substitution_to_method` substitutes the method's own
  template bounds too. Only PHP#-gated code reads them.
- `explain_blocked_substitution` names `out` only when the substitution
  widens and `in` only when it narrows, and keeps the issue's help
  otherwise.
- `scan_type_parameters` reads the bounds once per type parameter, each
  time with the templates of the read before.
- `check_template_arguments` takes the call's template result, so a
  written type argument's bound sees the receiver's type arguments.
- `static_member_class` counts a constant as a static member.
- `ResolvedNames::erased_type` names a function type, so the checker
  refuses it with "This type is not supported yet in PHP#." and the
  type-argument note.
- The private-reach message says "written only through `this`" for a
  property whose `get` is public.
- `display_nullable_type` replaces the four nullable display copies,
  `check_template_parameters` builds one arity report,
  `get_localized_property_type` takes the receiver union,
  `with_parent_type_parameters` returns the `ChangedTemplateBound`
  issue, and the comparator folds its type-parameter null guard into
  the upstream non-null check.
- Three tests whose cases other tests cover lose those cases.

Files

crates/
├── analyzer/
│   ├── src/
│   │   ├── expression/assignment/mod.rs        receiver union to get_localized_property_type
│   │   ├── invocation/
│   │   │   ├── arguments.rs                    writes_null in .sharp, display_nullable_type
│   │   │   └── template_result.rs              passes the call's template result
│   │   ├── resolver/
│   │   │   ├── method.rs                       receiver union to get_localized_property_type
│   │   │   └── property.rs                     get_localized_property_type runs the find_map
│   │   ├── statement/
│   │   │   ├── class_like/
│   │   │   │   ├── method_signature.rs         with_parent_type_parameters returns the issue
│   │   │   │   └── mod.rs                      one arity report, substituted method bounds
│   │   │   ├── function_like/
│   │   │   │   ├── mod.rs                      check_template_arguments takes bounds
│   │   │   │   └── rejected_nullable_parameter.rs  writes_null shared
│   │   │   └── return.rs                       display_nullable_type
│   │   └── utils/
│   │       ├── names.rs                        display_nullable_type
│   │       └── template.rs                     marker help, "written only through `this`"
│   └── tests/sharp.rs                          5 new tests, 2 deleted, 1 trimmed, 1 reworded
├── codex/src/
│   ├── scanner/ttype.rs                        bounds read once per type parameter
│   └── ttype/comparator/atomic_comparator.rs   one non-null check
├── names/
│   ├── src/lib.rs                              erased_type names a function type
│   └── tests/binder.rs                         function type case
└── semantics/
    ├── src/internal/checker/sharp.rs           static_member_class counts constants
    └── tests/sharp.rs                          2 new tests, 1 trimmed
…cs, type-parameter and backed-enum rules

Problem

G1 erases type arguments when the program runs, so the checker refuses
every type test it cannot run: `is List<int>`, `as PaginatedList<Order>`,
a `match` arm with type arguments, `is TItem`, `is Function<int(int)>`,
`catch (TItem)`, `typeof(TItem)`, `new TItem` and a static member of a
type parameter. Each refusal read "This type is not supported yet in
PHP#." with a shared note, which sounds as if PHP# lacks `List<int>`.
The `List.wrap` refusal told users to write `x is List<int> one ? [one]
: x`, which the checker now refuses.

Three rules were each written in two to four places that must agree:
the built-in generic names `List`, `Map` and `Class`, the check "is this
name a type parameter", and "the one backed enum every key member is a
case of".

Solution

Each erased-type refusal names the test or expression as the code
writes it, and why it can't run, in one sentence:
"`is List<int>` can't be tested yet, because type arguments don't reach
the running program." A function type gives "because a function's
parameter and return types don't reach the running program." The
`ERASED_TYPE_ARGUMENTS` note is gone. `List.wrap` keeps its "T is …"
refusal without the `write …` suggestion. `.php` results do not change.

`built_in_generic_arity` moves into mago-syntax beside `GenericHint`,
and the checker, the binder's `walk_in_hint` and the bridge's
`Lowering::erase` read it. `ResolvedNames::is_type_parameter` replaces
the checker's function, the analyzer's closure in `is_refused` and the
codex scanner's copy. `get_sole_backed_enum` in mago-codex replaces the
analyzer's `enum_of` and `is_one_enum` closures and the bridge's loop in
`Types::backed_enum`.

crates/
├── syntax/src/cst/cst/
│   ├── type_hint.rs          + built_in_generic_arity
│   └── mod.rs                re-exports it
├── names/src/
│   ├── lib.rs                + ResolvedNames::is_type_parameter; erased_type uses it
│   └── internal/walker.rs    walk_in_hint reads built_in_generic_arity
├── semantics/
│   ├── src/internal/checker/sharp.rs   erased refusals name the test; local
│   │                                   copies of both rules and the note deleted
│   └── tests/sharp.rs        full-text message tests with .php pins
├── codex/src/
│   ├── ttype/mod.rs          + get_sole_backed_enum
│   └── scanner/ttype.rs      reads is_type_parameter
├── analyzer/
│   ├── src/expression/mod.rs                   is_refused reads is_type_parameter
│   ├── src/statement/mod.rs                    reads get_sole_backed_enum
│   ├── src/invocation/return_type_fetcher.rs   List.wrap drops `write …`
│   └── tests/sharp.rs        List.wrap message tests
└── sharp-bridge/src/
    ├── lower.rs              erase reads built_in_generic_arity
    └── lower/types.rs        backed_enum reads get_sole_backed_enum
… keep PHP's enum-bound keys

Problem

PHP#'s `Self` read as its class with no type arguments, so a method of
`Box<TItem>` that returns `Self` could return a `Box<Order>`, and a
static member of a generic class could return `Self` although every
`Box<…>` shares it.

`is Box`, `as Box`, a `match` arm `Box` and `catch (Box)` passed when
`Box<TItem>` is generic, although the running program can't test type
arguments. `Class<Box>` was refused with "`Box` needs its type
argument", although a class type names the class itself.

In `.php` files, a key type `T` with `@template T of Status`, a backed
enum, passed as its backing type. Upstream Mago reports it, and the
PHP# rule that reads through a bound leaked into PHP.

Messages in `.sharp` files named classes by their full names, methods as
`Store::count`, types PHP# doesn't write (`array-key`,
`iterable<mixed, int>`) and erased types without saying they are PHP's.
"1 type parameters" lacked number agreement, and the type-parameter name
rule said "starts with `T`" for a rule that also needs a capital letter.

Solution

`union_from_hint` gives a PHP# method's `Self` its class's type
parameters, as `this` has them. The checker refuses `Self` in a static
member of a generic class with "A static member can't use `TItem`,
because every `Box<…>` shares it."

The analyzer refuses a type test of a generic class written without its
type arguments: "`is Box` can't be tested yet, because type arguments
don't reach the running program." `Class<Box>` passes, and
`Class<Box<Order>>` stays refused.

`get_backed_enum`, `get_backing_key_type` and `get_sole_backed_enum`
take a `Dialect` and read through a type parameter's bound only in
PHP#. The comparators pass their `sharp_rules`, the analyzer its file's
dialect and the bridge `Dialect::Sharp`.

`.sharp` messages use short class names, `Store.count` and
`Repository.count<TQuery>`, "PHP's `mixed`" for erased types,
`int|string` and `Iterable<int>`, and "1 type parameter". The name rule
reads "A type parameter's name is `T`, or `T` and a capital letter, as
in `TItem`." `.php` results do not change.

`ResolvedNames::erased_type` returns the erased hint, so the checker's
`is_function_type_at` is deleted. The scanner reads `List`, `Map` and
`Class` arities from `built_in_generic_arity`.

crates/
├── names/
│   ├── src/lib.rs            erased_type returns the hint
│   └── tests/binder.rs       reads the hint's span
├── semantics/
│   ├── src/internal/checker/sharp.rs   static Self refused; name rule
│   │                                   wording; is_function_type_at deleted
│   └── tests/sharp.rs        Self, Class<Box> and wording tests; erased
│                             test trimmed to type parameters
├── codex/src/
│   ├── scanner/ttype.rs      Self carries class_templates; arities from
│   │                         built_in_generic_arity; read_bounds inlined
│   ├── scanner/function_like.rs        scan_method passes its templates
│   ├── scanner/{class_like,class_like_constant,parameter,property}.rs
│   │                         pass no templates
│   ├── ttype/mod.rs          backed-enum readers take a Dialect
│   └── ttype/comparator/{array,iterable}_comparator.rs   pass sharp_rules
├── analyzer/
│   ├── src/expression/mod.rs           refuses is/as/match of a bare
│   │                                   generic class
│   ├── src/statement/{mod,try,return}.rs   match arms, catch, is_refused
│   ├── src/statement/class_like/{mod,method_signature}.rs
│   │                         short names, Box.put, PHP's `mixed`, plurals
│   ├── src/statement/function_like/mod.rs  Class<Box> passes; plurals;
│   │                         Repository.count<TQuery>; dialect for keys
│   ├── src/invocation/template_result.rs   Store.count
│   ├── src/invocation/{arguments,template_inference}.rs   dialect for keys
│   ├── src/expression/array.rs, src/utils/expression/array.rs
│   │                         dialect for keys
│   ├── src/utils/names.rs    int|string and Iterable<T>
│   └── tests/sharp.rs        tests with .php pins
└── sharp-bridge/src/lower/types.rs     backed_enum passes Dialect::Sharp
Problem

Spec section 11 says a type names a generic class's type arguments, as
in `PaginatedList<Order> page`. `Class<PaginatedList>`, the type of
`typeof(PaginatedList)`, names the class itself and takes no type
arguments, and the spec did not say so.

Solution

Section 11's rule for types names `Class<PaginatedList>` as the one
exception: a class type names the class itself.

docs/
└── spec.md    section 11: Class<PaginatedList> names the class itself
…'s holes

Problem

Round 6 gave the scanned `Self` type its class's own type parameters, so
every call bound them from the declaring class: `tagged.same().tag(1)` on a
`Tagged<string> : Box<int>` passed, and `OrderBox : Box<Order>` got a stray
`OrderBox<Order>` from `same()`. An override of a method returning `Self`
also failed its return check. A call's resolver filled the declaring
class's omitted type arguments into an unbound `Self` before binding it to
the receiver, which left `OrderBox<Any?>`.

Inference read a generic method's `Map<TKey, int>` key in the caller's
dialect: a PHP# caller's `Map<Status, int>` was converted to backing
values, and a plain PHP caller's backing values bound `TKey` to a string,
both refused against `TKey : Status`. The argument check read the key in
the caller's dialect too. Function-like metadata never carried the SHARP
flag, so nothing could tell a PHP# target from a PHP one.

`new` on a class value of a generic PHP# class asked for type arguments
G1 can't keep. A type test of a PHP class with docblock templates, such as
`Traversable`, was refused as a generic class. In plain PHP,
`get_backed_enum` read a backed enum out of an intersection, so a
`.php` key of `HasLabel&Status` lost upstream's issue. Erased types in
PHP# messages were all written as PHP's. The static `Self` refusal named
`TItem` instead of `Self`, and `new Self(…)` in a static method of a
generic class went unrefused.

Solution

- `Self` stays a bare static type in the scanner. In `.sharp` the body
  checks expand it against `this`'s type, `Box<TItem>`, through
  `get_scope_static_class_type`, and a call binds it to the receiver
  before filling omitted type arguments.
- `InvocationTarget::get_dialect` names the target's dialect from the
  SHARP flag, which the scanner now sets on functions, methods, closures
  and arrow functions. Inference and the plain PHP argument check read a
  parameter's `Map` key in it, and `comparable_key_types` compares two
  keys that hold an enum's cases as written, and a key of cases against
  one of backing values as its backing type.
- `new` on a class value of a generic PHP# class reports that it can't run
  yet, with the expression as the code writes it, in place of the missing
  type argument.
- Only a PHP# class counts as untestable generic class.
- In plain PHP `get_backed_enum` returns only an enum type's enum.
- `display_erased` writes PHP# names, and PHP's only for a type with
  `mixed` or `array` in it.
- The checker names `Self` and every type parameter it carries, and
  refuses `new Self(…)` in a static member of a generic class.

crates/
├── analyzer/
│   ├── src/
│   │   ├── expression/
│   │   │   ├── instantiation.rs        new on a generic class value refused
│   │   │   └── mod.rs                  untested generic class is a PHP# class
│   │   ├── invocation/
│   │   │   ├── analyzer.rs             passes the target's dialect to inference
│   │   │   ├── arguments.rs            backing key read in the target's dialect
│   │   │   ├── mod.rs                  InvocationTarget::get_dialect
│   │   │   ├── resolver.rs             Self bound to the receiver before the fill
│   │   │   └── template_inference.rs   comparable_key_types, InferenceOptions.dialect
│   │   └── statement/
│   │       ├── class_like/
│   │       │   ├── method_signature.rs display_erased writes PHP# names
│   │       │   └── mod.rs              passes the codebase to display_erased
│   │       ├── function_like/mod.rs    get_scope_static_class_type
│   │       └── return.rs               return checks expand Self against this
│   └── tests/sharp.rs                  red-first cases with .php twin pins
├── codex/src/
│   ├── scanner/
│   │   ├── class_like.rs               class_templates argument removed
│   │   ├── class_like_constant.rs      class_templates argument removed
│   │   ├── function_like.rs            SHARP flag on function-likes
│   │   ├── parameter.rs                class_templates argument removed
│   │   ├── property.rs                 class_templates argument removed
│   │   └── ttype.rs                    Self is a bare static type again
│   └── ttype/mod.rs                    get_backed_enum in plain PHP
└── semantics/
    ├── src/internal/checker/sharp.rs   Self refusal, new Self in a static member
    └── tests/sharp.rs                  Self and new Self refusals
Spec section 25 lets `new type(…)` create an object from a class value.
G1 erases type arguments, so an object created from a class value of a
generic class could not get its own. The checker refuses it, and the spec
now says so beside the `new type(…)` bullet.

docs/
└── spec.md   section 25: new on a generic class value is not supported yet
…receiver, and keep PHP's key inference

Problem

A PHP# method value such as `boxes.first` kept the declaring class's type
parameters and an unbound `Self`, so `Function<TItem?()>` and
`Function<Box<Any?>()>` reached callers in place of `Function<string?()>` and
`Function<Box<string>()>`. A plain PHP caller of a PHP# method returning
`Self` got Mago's `static` reading, not the receiver's type. A plain PHP
container keyed by a template bounded by a backed enum had its key converted
to the enum's backing type, which changed upstream Mago's inference for PHP.
The static `Self` refusal named the shared class after the type parameters,
the erased-signature messages named PHP's `iterable` and `Closure` as PHP#
types, and the class-value `new` refusal printed the whole expression.

Solution

resolve_method_value takes the receiver object, expands the signature with
`Self` bound to it and localizes the declaring class's type parameters as a
property read does, through one localize_member_type helper. The invocation
resolver reads a PHP# callee's `Self` as PHP# does for any caller.
comparable_key_types converts a container key only when the container is
PHP#. display_erased treats `iterable` and `Closure` as PHP-only types. The
static `Self` refusal and the class-value refusal read as C# would.

Cuts: display_sharp_member names `Box.put` at every PHP# member site,
Span::to_range_usize replaces hand-written offset slices, get_backed_enum
reads an object's name once, report_methods_named_as_properties takes the
class, static_member_use reads the type parameter list's span, and two
semantics tests covered elsewhere are deleted.

crates/
├── analyzer/src/
│   ├── expression/access/mod.rs           static method values pass a receiver object
│   ├── expression/instantiation.rs        class-value refusal prints `new …(…)`
│   ├── expression/mod.rs                  Span::to_range_usize
│   ├── invocation/resolver.rs             PHP# callee's Self for any caller
│   ├── invocation/template_inference.rs   PHP container key kept as written
│   ├── invocation/template_result.rs      display_sharp_member
│   ├── resolver/property.rs               receiver-specialized method values
│   ├── statement/class_like/method_signature.rs  iterable and Closure are PHP's
│   ├── statement/class_like/mod.rs        display_sharp_member
│   └── utils/names.rs                     display_sharp_member
├── analyzer/tests/sharp.rs                new and updated cases with PHP twins
├── codex/src/ttype/mod.rs                 get_backed_enum reads get_name
├── names/tests/binder.rs                  Span::to_range_usize
├── semantics/src/internal/checker/sharp.rs  static Self wording, cuts
└── semantics/tests/sharp.rs               new wording, two tests removed
…s callable when erasing

Problem

A PHP# method value expanded `Self` to its receiver first and then replaced
the declaring class's type parameters, so a receiver whose type arguments
name the class's own type parameter had them replaced twice: inside
`Box<TItem>`, `boxes.same` on a `Box<List<TItem>>` was typed
`Function<Box<List<List<TItem>>>()>`. That refused the correct return type
and accepted the wrong one. The erased-signature check erased every callable
to `Closure`, so a PHP# override taking a `Function<int(int)>` where a PHP
parent takes `callable` passed, and PHP refuses that override when it links
the class. Erased messages named an `iterable` as PHP's `iterable`, though
spec section 12 writes it `Iterable<T>`.

Solution

resolve_method_value builds the signature with `self_class` only, runs
localize_member_type, then expands the closure type with `Self` bound to the
receiver, the order resolve_union uses. erase keeps a closure signature, how
PHP# stores `Function<…>`, as `Closure` and erases PHP's `callable` to
`callable`. display_erased names them PHP's `Closure` and PHP's `callable`,
and an erased `iterable` as `Iterable<Any?>`.

Cuts: forwarded_return_type and get_localized_property_type call
localize_member_type in place of their copies of its guard,
display_sharp_accessor builds on display_sharp_member, access/mod.rs uses
TObject::new_named, the erased Closure and iterable cases fold into
an_erased_parameter_type_is_named_as_sharp_writes_it, and the multi-line
`built()` case leaves the class-value `new` test.

crates/analyzer/
├── src/
│   ├── expression/access/mod.rs                  TObject::new_named
│   ├── resolver/method.rs                        forwarded_return_type calls localize_member_type
│   ├── resolver/property.rs                      localize, then expand Self; localize_member_type shared
│   ├── statement/class_like/method_signature.rs  callable stays callable; Iterable<Any?>
│   └── utils/names.rs                            display_sharp_accessor on display_sharp_member
└── tests/sharp.rs                                two new cases with PHP twins, one fold, one cut
…calls and method values

Problem

A PHP# call `pair.same()` and its method value `pair.same` were typed by two
functions with two orders, so they disagreed. resolve_union typed the call,
and resolve_method_value typed the method value. The method value expanded
`Self` before the declaring class's type parameters were bound, so a subclass
that adds a type parameter got `Box`'s omitted arguments filled in: `pair.same`
was `Function<Pair<Any?, Any?>()>` and `orders.same` was
`Function<OrderBox<Any?>()>`. Both paths also expanded `Self` again after the
replacement, so a caller's `Self` inside a receiver's type argument was rebound
to the receiver: `this.children().first()` on a `Tree<Self>` gave
`Tree<Node>?` where it is `Node?`, and the call accepted the wrong return type.

Solution

specialize_member_type computes a member's type for a receiver, and both
resolve_union's PHP# receiver path and resolve_method_value call it. It
expands the member's declared type with `Self` bound to the receiver's class
with its own type parameters, as get_this_type builds it. One replacement then
gives those type parameters, and the declaring class's, the receiver's type
arguments, beside the call's own. The last expansion binds no `Self`, so a
caller's `Self` stays the class that wrote it. resolve_union skips its second
expansion on that path. `.php` callers keep upstream's order.

TypeExpansionOptions gains keep_generic_derived_types. With it set, the
expander keeps a derived type that still holds a type parameter, with only its
target expanded. specialize_member_type sets it in its `Self` pass, so a PHP
docblock's `list<key-of<T>>` called from PHP# reads the call's type argument
in the last expansion: `List<string>` for a `Map<string, int>`, never the
`List<int|string>` of `T`'s bound.

localize_property_type gets its bounds from get_receiver_type_arguments, which
specialize_member_type shares.

crates/
├── codex/src/ttype/expander.rs       keep_generic_derived_types keeps a derived type over a type parameter; unit test
└── analyzer/
    ├── src/invocation/resolver.rs    the PHP# receiver path calls specialize_member_type, no second expansion
    ├── src/resolver/property.rs      specialize_member_type and get_receiver_type_arguments; resolve_method_value calls the first
    └── tests/sharp.rs                four new cases with PHP twins: the subclass, Tree<Self>, every receiver, key-of
…e member-type path

Problem

Review rounds 11 to 13 found seven places where PHP#'s member type for a
receiver, `specialize_member_type`, gave the wrong type, and one where a
plain PHP call lost the type upstream gives it:

- A receiver bounded by an intersection lost every part but its head.
  `box.same()` on a `TBox : Box<int> & Named` was a `Box<int>`, so `name()`
  did not exist on it. `item.copy()` on a `TItem : Order & Copyable` was a
  `Copyable`, and `item.copy` as a method value did not resolve at all. A
  generic part other than the head gave no type arguments, so
  `holder.held()` on an `Order & Holder<int>` was `Any?`.
- A receiver whose generic head does not declare the member lost the head's
  type arguments. `box.copy()` on a `TBox : Box<int> & Copyable`, where
  `Copyable` declares `copy`, was a `Box<TItem> & Copyable`, because only
  the part that inherits the declaring class gave type arguments.
- A PHP `@mixin` method called from PHP# took the PHP# path, which assumes
  the receiver inherits the declaring class. `repository.first()` lost the
  mixin's `Order` and `repository.latest()` returned the `Builder`.
- `resolve_union` recurses for conditional and derived types and ran
  `specialize_member_type` at every level, so a receiver type argument that
  names the class's own type parameter was replaced twice: `pair.get(true)`
  on a `Pair<List<TKey>>` was a `List<List<TKey>>`.
- Calling a stored method value rebound its already specialized `Self` to
  the class that declares the method: `first()` on a local holding
  `this.children().first` was a `Tree<Any?>?` instead of a `Node?`.
- Specializing once, after the recursive `resolve_union`, left a PHP
  conditional return type comparing a subject and target PHP# never
  specialized. A `static` target stayed the class that declares the
  method: `basket.pickSame(picker)` on a `Basket`, whose inherited
  `pickSame` returns `($picker is static ? int : string)`, was an `int`
  where a plain `Picker` gives an `int|string`.
- A PHP trait's `self` named the trait in a method value. `order.me()` on an
  `Order` that uses `Fluent`, whose `me` returns `self`, was an `Order`, but
  `order.me` was a `Function<Fluent()>`, so `label()`, which only `Order`
  declares, did not exist on what calling it gives. Only calls renamed the
  trait.
- Moving the trait rename into `rename_trait_objects` dropped upstream's
  check that a PHP call renames a trait only when the method runs on
  another class. `self::make()` inside the trait `Fluent` printed
  `lib\fluent` where upstream prints `Lib\Fluent`.

Solution

- `specialize_member_type` binds `Self` to the receiver's class plus every
  intersection part it carries. It always gives the receiver's class's type
  parameters the receiver's type arguments, then gives the declaring class's
  the type arguments of the part that inherits it. `resolve_method_value`
  finds the method on the head or on any intersection part, as a call does.
- `specialize_member_type` takes the class the member was found on and runs
  `rename_trait_objects` on what the member gives, and on the return type of
  a method value, so a call and its method value both name the class that
  uses the trait. `resolve_invocation_type` no longer renames on its own.
  PHP calls keep upstream's rename through `get_declaring_class`.
- `resolve_invocation_type` runs `specialize_member_type` once, after the
  recursive `resolve_union` returns. `get_sharp_receiver` decides that path
  in one place and leaves out targets found through a `@mixin`, which keep
  upstream's replacement and `static` rebinding.
- `resolve_conditional` runs a PHP# member's subject and target through
  `specialize_member_type`, the one call `specialize_for_receiver` makes,
  before it compares them. Its `then` and `otherwise` stay raw, so
  `resolve_invocation_type` still specializes the result once.
- A PHP call renames a trait's objects only when the class that declares
  the method is not the class it runs on, as upstream does.
- `calls_sharp_method_value` stops the final expansion from rebinding `Self`
  when PHP# calls a method value. The call still replaces its own type
  arguments, so a stored generic method keeps inferring them.

crates/analyzer/
├── src/
│   ├── invocation/mod.rs        re-exports rename_trait_objects for specialize_member_type
│   ├── invocation/resolver.rs   resolve_invocation_type specializes once; get_sharp_receiver,
│   │                            specialize_for_receiver, calls_sharp_method_value,
│   │                            get_declaring_class; resolve_conditional specializes the
│   │                            operands it compares; rename_trait_objects renames in place
│   │                            for both paths, and a PHP call keeps upstream's guard
│   └── resolver/property.rs     specialize_member_type keeps intersection parts, binds the
│                                receiver's own type parameters, renames a trait's self;
│                                resolve_method_value finds methods on intersection parts
└── tests/sharp.rs               seven tests with .php twin pins; the agreement test covers
                                 intersection receivers, a generic head with a declaring
                                 part, a PHP trait's self, and a called stored method value;
                                 a conditional return compares a class, class-string and
                                 static target; a trait's own self call keeps upstream's text
PHP# generics (G1) last took master at 39a57d0. Master has since merged
#39 to #55, ending at 9c95c77: static classes and extern methods, the
standard library's Int, Float and Bool, Replaces and the refusal of calls
PHP# replaces with syntax, the List index and Map key refusals, recorded
reads, unsuppressible PHP# errors, mago compile inputs and Position's
file. G1 has to sit on that master before its pull request.

Eight files conflicted. Each keeps both sides:
- composer/src/Sdk/Internal/Analyzer/Protocol.php and
  crates/analyzer/src/external/protocol.rs: master moved the analyzer
  protocol from 1.7 to 1.9 for recorded reads and type comparison reads,
  and G1 moved it to 1.8 for the 22-byte node record. The merged wire
  format is neither side's, so the protocol is 1.10 on both sides, and
  VERSION_U32 stays public as master's InvocationTest reads it. The
  linter protocol stays at G1's 1.2, which master did not change.
- crates/syntax/src/parser/internal/type_hint.rs: master's
  is_at_conditional, which reads `value is string ? a : b` as a
  conditional, and G1's is_at_generic_hint with its `Class<` comment.
- crates/syntax/tests/walker.rs: master walks slice.sharp and
  library.sharp, and G1's slice_fixture() still feeds its type parameter
  walk test.
- crates/semantics/tests/fixtures/slice.sharp: G1's generic section
  (Page, Listing, Source, Comparable, Entry, Version), then master's
  static class Slug.
- crates/semantics/src/internal/checker/sharp.rs: ClassLike carries both
  G1's type_parameters and master's is_static, and ClassLike::of_class
  fills both. enter keeps G1's report_methods_named_as_properties(&Class)
  and runs master's check_static_class. check_slice's documentation
  lists master's static class beside G1's type parameters.
- crates/analyzer/src/expression/mod.rs: the imports of both sides,
  master's As and LocalIdentifier for its pattern calls and G1's Access,
  Call, Hint and Identifier for is_refused.
- crates/analyzer/tests/sharp.rs: both sides appended tests at the same
  place. Both sets stay.

Two master tests met G1's rule that a .sharp message names types as
PHP# writes them, which master's tests were written before. Each now
expects G1's wording, with the same exact assertion:
- tests/sharp.rs
  analyze_types_the_parse_calls_of_the_standard_library_from_the_vendored_package:
  `float|null` and `bool|null` read `float?` and `bool?`.
- crates/analyzer/tests/sharp.rs
  a_bare_call_of_a_method_that_no_function_shares_names_the_member_to_write:
  "Saw type `mixed`" reads "Saw type `Any?`".

The SDK's NodeKind regenerates unchanged from the merged syntax tree.

.
├── composer/src/Sdk/Internal/Analyzer/Protocol.php  <- analyzer protocol 1.10
├── crates/
│   ├── analyzer/
│   │   ├── src/external/protocol.rs                 <- analyzer protocol 1.10
│   │   ├── src/expression/mod.rs                    <- both sides' imports
│   │   └── tests/sharp.rs                           <- both sides' tests; Any? wording
│   ├── semantics/
│   │   ├── src/internal/checker/sharp.rs            <- ClassLike with type parameters and is_static
│   │   └── tests/fixtures/slice.sharp               <- generic section, then Slug
│   └── syntax/
│       ├── src/parser/internal/type_hint.rs         <- is_at_conditional and is_at_generic_hint
│       └── tests/walker.rs                          <- both fixtures, slice_fixture kept
└── tests/sharp.rs                                   <- float? and bool? wording
The generics slice ran PHP# generics erased on the engine that lowered
each file in-process, while reified generics need the typed engine,
which loads the .sharpc unit that mago compile writes. Generics now
merge once, on top of the typed engine.

Build the generics slice on the typed engine:
- ext/sharp/sharp_unit.h names Mago 1e74fab, the generics slice with
  Mago master 9c95c77 merged, so sharp/bin/test installs the checker
  that parses generics. The unit ABI is unchanged
- ext/sharp no longer builds the bridge, so its Cargo.lock names no
  Mago crate

Keep the G1 Goal files running on the typed engine:
- Generics.inc writes the marked receiver cast the typed engine
  compiles every PHP# method call through, ((object) $x)->m(), as
  every other twin does
- opcodes.phpt pins only the twin's docblocks for Generics, because the
  typed engine declares Order and OrderPage as the twin does
- compile_command.phpt names the refused literal types as the generics
  checker writes them in a .sharp file, "text" and 1

mago compile at 1e74fab still refuses Generics.sharp line 128,
new OrderPage(Catalog.orders()): the analyzer does not give an
inherited constructor the type arguments of the class header, so
List<TItem> stays unresolved. The fix belongs to Mago.

Zend/tests/sharp/
├── Generics.inc          <- typed twin: marked receiver casts
├── compile_command.phpt  <- the generics checker's literal wording
└── opcodes.phpt          <- typed engine fixtures plus Generics
ext/sharp/
└── sharp_unit.h          <- SHARP_MAGO_COMMIT 1e74fab
Sections 11 and 25 still carried two limits of erased generics, a static
member that can't use its class's type parameters and a generic class
value that can't be created with new, while type arguments now reach
the running program. They gave no rule for PHP's Serializable or for a
class value with type arguments as a Map key.

Write the generics rules on the typed engine:
- A generic class can't implement PHP's Serializable, and the error
  points to __serialize and __unserialize
- A class value with type arguments can't be a Map key, because
  Class<PaginatedList<Order>> and Class<PaginatedList<Invoice>> share
  the plain class name
- Delete the two erased limits. Their replacement rules come next

docs/
└── spec.md  <- sections 11 and 25
…der fixes

Problem

`OrderPage : PaginatedList<Order>` inherits `PaginatedList`'s constructor,
which takes `List<TItem>`. `new OrderPage(orders)` with a `List<Order>` was
refused, "expected `List<TItem>`, but found `List<Order>`", so `mago compile`
refused Generics.sharp and the engine could not run it. `new
OrderList<Order>(orders)`, where `OrderList<TItem> : PaginatedList<TItem>`,
was refused the same way.

The PHP twin had the same cause with the opposite symptom. `new
OrderPage($invoices)` on a class with `@extends PaginatedList<Order>`
inferred `TItem` from the argument and accepted a `list<Invoice>`.

`populate_template_result_from_invocation` binds the declaring class's
templates to the type arguments the called class passes them only through
`infer_templates_for_method_call`, which needs a receiver object. `new`
calls the constructor with `StaticClassType::Exact`, which has no object,
so the instance path returned before `TItem` got `Order`. The static path
did the same binding with a copy of the loop.

`new OrderList<Order>(…)` also needs `PaginatedList`'s `TItem` to follow
`OrderList`'s `TItem` to `Order`. `get_root_template_type` marked the next
entity as visited before it visited it, so it never followed a bound past
its first step.

Solution

- `seed_inherited_type_arguments` binds a declaring class's templates
  through the called class, with the receiver's type arguments when there
  is a receiver. The static path and the instance path both call it, and
  the instance path calls it with or without a receiver object.
  `infer_templates_for_method_call` keeps only the `where` constraints.
- `get_root_template_type` marks the entity it visits, so a chain of
  bounds resolves to its end and a cycle still stops.

crates/
├── analyzer/
│   ├── src/invocation/template_result.rs     seed_inherited_type_arguments; the instance
│   │                                         path binds inherited type arguments without
│   │                                         a receiver object
│   ├── src/invocation/template_inference.rs  infer_templates_for_method_call checks only
│   │                                         where constraints
│   └── tests/sharp.rs                        four tests: an inherited constructor accepts
│                                             and refuses, an inherited method, and the
│                                             @extends PHP twin
└── codex/src/ttype/template/bounds.rs        get_root_template_type follows a bound chain
The nightly Linux job overflowed the stack in
`a_property_default_of_100_000_terms_is_inferred_on_a_small_stack`. The
parser's path from the `parse_statement` guard into a class property
reaches the lexer with no guard between them, and the stack guard allows
that path only its 100 KiB red zone. In an x86_64 debug build the path
took 102,032 bytes on master and 103,360 on this branch.
`parse_statement_inner` was 43,720 of them: each of its arms unwrapped
its node with `?` and wrapped it again, so an unoptimized build kept
three node-sized values per arm, about 40 arms at once. The type
parameters generics adds to a class-like node grew every one of them.

Each arm now returns its parser's `Result` as it is, mapped to its
`Statement`. `parse_statement_inner` takes 17,144 bytes, and the path to
the lexer 76,832. A thread whose first guard has 102,560 bytes left
overflowed before this change and passes after it.

crates/syntax/
└── src/parser/internal/statement.rs  <- every arm passes its parser's `Result` through
Master brings #120: Mago lives in `sharp/mago/`, and php-sharp pins no
Mago commit. It also brings #105's failing spec examples as one empty
file per example under `sharp/baseline/spec/`.

Two files conflicted:
- `ext/sharp/sharp_unit.h` takes master's side, with no Mago commit. The
  next merge, of mago-sharp `feat/slice-generics` into `sharp/mago/`,
  writes the header its bridge generates.
- The slice's one-file list `sharp/baseline/spec` is removed, as
  docs/architecture/spec-examples.md says. The next merge lists the
  examples the slice fixes and fails in the folder.

ext/sharp/sharp_unit.h    master's header, which names no Mago commit
sharp/baseline/spec       the one-file list removed for the folder
mago-sharp no longer merges anything, so generics moves into php-sharp,
as docs/architecture/mago.md says under "Moving an open mago-sharp
branch". This merges mago-sharp `feat/slice-generics` at cb9e284
into `sharp/mago/`. That branch carries mago-sharp master up to
164ef44, which php-sharp's `sharp/mago/` doesn't hold yet.

Conflicts:
- `sharp/mago/.github/actions/setup-lean/action.yml` and
  `sharp/mago/.github/workflows/ci.yml` are removed. The branch changed
  neither, and `.github/` already carries mago-sharp master's versions.
- `ext/sharp/sharp_unit.h` is the header the merged bridge's `build.rs`
  writes. Its ABI differs from master's.

The failing spec examples list loses 24 examples that pass at this
Mago. The generics ones are §7 method-declarations, §11 generic-statics,
inferred-type-arguments and self-on-type-parameters, and §25
class-values and class-value-equality. The other 18 pass because of
mago-sharp master's commits the branch carries.

ext/sharp/sharp_unit.h          <- the header the merged bridge generates
sharp/
├── baseline/spec/              <- 24 examples that pass leave the list
└── mago/                       <- mago-sharp feat/slice-generics
    └── .github/                <- ci.yml and setup-lean removed
@heyJordanParker heyJordanParker changed the title feat: the engine carries PHP# type arguments (spec section 11, R1 and R2) feat: PHP# generics, checked and carried at runtime (spec section 11, R1 to R5) Oct 13, 2026
Master brings #114: the engine runs section 12's collection methods
and index places, and `sharp/mago/` moves to mago-sharp 3cc39cc. It
updates the five engine fixtures that the slice's Mago refused, so
`mago compile` compiles all 111 again. 3cc39cc also brings mago-sharp
#175 and #177, which git merged into the slice's Mago without a
conflict.

Six files conflicted, and each keeps both sides:
- `ext/sharp/sharp_arginfo.h` is regenerated from the merged
  `sharp.stub.php`, which holds master's `insert`, `removeAt`, `put` and
  `clear` and the slice's `\Sharp\Internal` functions.
- `index_read.inc` keeps master's two `count` calls and the slice's
  three `standing` calls.
- `enum_keys.phpt` and its two JIT twins keep the slice's `TypeError`:
  the Map's check refuses the key "missing" where plain PHP hands the
  Map in, before master's loop would convert it. Master's new `nest`
  line moves `byName` to line 67. `enum_keys.inc`'s comment that plain
  PHP collections are not checked is no longer true, and now says where
  the key fails.
- `opcodes.phpt` keeps master's 16 op arrays for `EnumKeys` and the
  slice's check lines, with one for each of master's `grouped` and
  `groupNames`.

Zend/tests/sharp/
├── enum_keys.inc                   <- the comment says where the key fails
├── enum_keys.phpt, enum_keys_jit_function.phpt, enum_keys_jit_tracing.phpt
│                                   <- the slice's TypeError, at line 67
├── index_read.inc                  <- both sides' calls
└── opcodes.phpt                    <- master's count, the slice's checks
ext/sharp/sharp_arginfo.h           <- regenerated from the merged stub
@heyJordanParker

Copy link
Copy Markdown
Owner Author

Review verdict: CHANGES NEEDED

Head: 66c6b8d44eec3bba34d5526ab0737718e4954905. Engine built with sharp/bin/build, and mago built from sharp/mago/ with rustup run 1.97.0 and CARGO_PROFILE_RELEASE_LTO=off. Master's mago built the same way from b8907a9c1e for the .php comparison.

The blocking change: mago analyze and mago compile abort on ordinary plain PHP. Any .php file that calls a private method without a declared return type ends the process with exit 134. So does a private property whose docblock callable has no return type. A phpunit vendor tree and nikic/php-parser both hit it. mago compile aborts the same way when a project's sources hold such a file, so none of that project's .sharp files compile. Master analyzes the same files with no issue.

Scope note: this review judges #102 as its body describes it at this head, R1 to R5 whole. Every rule the body marks Done is judged as a rule, and the refusals are the body's "What stays refused" table.

Changes

1. Crash: plain PHP aborts the checker (.php difference, crash)

check_private_method_reach and check_private_property_reach in sharp/mago/crates/analyzer/src/utils/template.rs run for every private member read, call or write, in .php files too. Each computes the member's type-parameter positions before report_private_reach tests class.flags.is_sharp(). The positions walk then hits an unreachable! whose guarantee holds only for PHP# code.

Code, Peer.php:

<?php
declare(strict_types=1);

final class Peer
{
    private function reset()
    {
    }

    public function run(): void
    {
        $this->reset();
    }
}

Today, head:

thread 'main' panicked at crates/analyzer/src/utils/template.rs:460:9:
internal error: entered unreachable code: a PHP# method other than a constructor declares its return type
exit 134

Master, same file: INFO No issues found.

The second path, a private property read:

/** @var callable(int) */
private $handler;
...
($this->handler)(1);
thread 'main' panicked at crates/analyzer/src/utils/template.rs:554:17:
internal error: entered unreachable code: a PHP# function type writes its return type

The same panic stops mago analyze vendor/nikic and mago analyze vendor over a phpunit vendor tree, and mago compile on a probe project holding Peer.php as a .inc file.

It must: analyze plain PHP exactly as master does.

Fix: return before the positions walk when the member's class is no PHP# class, in both functions. The unreachable! arms then hold, as the patch-coverage table claims.

 pub(crate) fn check_private_method_reach<A>(…)
 {
     …
-    if !is_private_method(metadata) {
+    if !class.flags.is_sharp() || !is_private_method(metadata) {
         return;
     }
 pub(crate) fn check_private_property_reach<A>(…)
 {
+    if !class.flags.is_sharp() {
+        return;
+    }
     let visibility = if is_write { property.write_visibility } else { property.read_visibility };

Add a .php row for each path to a_variance_breaking_private_member_is_reachable_only_through_this, so the test fails while either path can panic. Today that test has no .php twin, which is why CI stayed green.

With the method gate applied in my scratch tree, the corpus below analyzes with master's output plus one line, which is the ReflectionEnum change the body already lists: vendor/phpunit/phpunit/src/Logging/TestDox/NamePrettifier.php:290:49 less-specific-argument … ReflectionClass::__construct. The corpus was master's 2,567 crates/analyzer/tests/cases files, a phpunit vendor tree with nikic/php-parser and the sebastian packages, and a file of @template, @template-covariant, @implements and class-string<T> uses. Master: 17,815 lines. Head with the gate: 17,816.

2. Program compiled wrong: a type test against a plain PHP @template class

Spec section 11: "a type test against one, such as x is Collection<Order>, is a compile error that says the type argument is unknown while the code runs". The body marks "Plain PHP @template generics keep their fallback" Done. Head compiles the test, and it answers true for a collection of strings.

Code:

<?php
namespace Legacy;

/** @template T */
final class Collection
{
    /** @param list<T> $items */
    public function __construct(private array $items) {}

    /** @return T */
    public function first(): mixed { return $this->items[0]; }
}
namespace Refuse;

import Legacy.Collection;

public class Erased
{
    public static int firstId(Collection<Order> orders) => orders.first().id;
    public static bool test(Any value) => value is Collection<Order>;
}

Today: mago compile accepts Erased.sharp. Then:

var_dump(Erased::test(new Collection(["not an order"])));   // bool(true)
var_dump(Erased::test(new Collection([new Refuse\Order(1)])));   // bool(true)

It must: refuse is, as, a match arm and a catch whose type gives a plain PHP class type arguments, at any depth, so List<Collection<Order>> too.

Fix: in analyze_php_shape in sharp/mago/crates/analyzer/src/expression/mod.rs, report an error for each tested Hint::Generic that resolves to a class without is_sharp(), walking nested type arguments. A message in the spec's words: "Collection<Order> can't be tested: Collection is a plain PHP class, so its objects carry no type arguments while the code runs." Help: "Test Collection alone." Add the rows to the analyzer tests and to type_test_of's bridge rows.

3. False or unfindable messages

3.1 The named constructor help quotes a fix that does not compile

public class Pair<T>
{
    public Pair(public T first { get; }) { }
    public Pair.of<TOther>(T first, TOther other) : this(first) { }
}

Today:

error[parse]: A named constructor takes its class's type arguments and declares none of its own.
 = Help: Declare a generic static method, as in `public static Pair of<T>(T value)`, or make the class generic, as in `class Pair<T>`.

The class is already generic, and the quoted method, compiled in Pair<T>, is refused: "Pair needs its type argument." The help is built in sharp/mago/crates/syntax/src/error.rs from the class name alone.

It must: quote a fix that compiles. Fix: when the class declares type parameters, quote a static method with the class's type arguments: "Declare a static method, as in public static Pair<T> of(T first): it takes the class's type arguments." That form compiled in my probe, called as Twin<int>.of(4). Keep today's text for a class without type parameters, where it compiles.

3.2 A collection that enters with one wrong element says only "array given"

Tools::takeOrders([new Order(1), new Invoice(2)]);
TypeError: Probe\Tools::takeOrders(): Argument #1 ($orders) must be of type List<Probe.Order>, array given, called in … on line 24

$holder->orders = [new Invoice(1)];
TypeError: Cannot assign array to property Probe\Holder::$orders of type List<Probe.Order>

List<Order> orders = Feed.orders();   // plain PHP returns [Order, Invoice]
TypeError: Lib\Feed::orders(): Return value must be of type List<Probe.Order>, array returned

"array given" reads as "a List takes no array", and a 10,000-element list gives no way to find the bad element. The walk already writes [1]: expected Probe.Order, got object Probe.Invoice into sharp_type_problems.

It must: name the first bad value. Fix: when the value is an array, run the failing walk once more with problems and append its first entry, as in "…, array given: [1] expected Probe.Order, got object Probe.Invoice".

3.3 new TItem.of(…) says new TItem is unsupported

new TItem.of(value) gives "new TItem is not supported yet in PHP#.", while new TItem(value) compiles. It must name the form refused: "A named constructor through a type parameter, as in new TItem.of(…), is not supported yet in PHP#."

3.4 A generic interface reached twice through a parent names a false parent type

public interface Feeder<T> { T next(); }
public class Ints : Feeder<int> { public int next() => 1; }
public class Strings : Ints, Feeder<string> { }

Today:

error[incompatible-return-type]: Return type `int` of `Strings.next` is incompatible with parent return type `never` of `Feeder.next`
error[invalid-template-parameter]: Diamond inheritance of `Feeder.next` requires an uninhabited return type.
 = Help: Constrain the template parameter with an object bound, since object intersections stay inhabitable, or remove one of the conflicting parameterizations.

Feeder.next returns T, not never, and PHP# has no "template parameter". The direct form class Both : Supply<int>, Supply<string> gets one clear error, "This header names Supply twice." It must: give the inherited form the same kind of error, as in "Strings implements Feeder twice: Feeder<int> through Ints, and Feeder<string>."

Tests that prove nothing for a rule they cover

4.1 No .php row pins the private-reach checks

Change 1 shipped green because a_variance_breaking_private_member_is_reachable_only_through_this has no .php twin and no analyzer case calls an untyped private method. The fix's rows close it.

4.2 The staleness test has no row for a variance or arity edit

a_compile_after_an_edit_to_a_type_parameter_bound_matches_a_clean_compile edits only bounds. I removed parameter.variance.fingerprint_with_hasher(…) from TypeParameterList's fingerprint in sharp/mago/crates/fingerprint/src/type_hint.rs, and the test still passed. A scratch row that edits Feed<out TItem : Entity> to Feed<TItem : Entity>, with Reader passing Feed<Order> where Feed<Entity> is taken, then fails:

left (warm):  "app/Shop/Reader.sharp": Ok([97, 21, …])
right (clean): "app/Shop/Reader.sharp": Err(["Feed<Order> cannot be used as Feed<Entity>."])

With the line restored, the same row passes. The code is right, the row is missing. Add the variance row, and one that adds a type parameter, as rows of the same test.

4.3 Two tests carry most of the engine's rules

type_arguments_entry_check.phpt names about 25 rules in its title, and type_arguments_call.phpt about 15. I removed the element conversion from sharp_type_convert in ext/sharp/sharp.c, and the suite caught it, as one failure of type_arguments_entry_check.phpt whose name lists every rule. The rows catch the mutation, and the failure doesn't say which rule broke. Split each into one .phpt per rule over the shared fixtures.

What holds

Every probe ran on the built engine without opcache, with the opcache file cache primed and then used, with opcache shared memory, and under the tracing and function JITs. The output matched in every mode.

Rules

  • A generic class with a bound, Page<TItem : Entity>: new Page<Order>(…).first().id is 4.
  • A generic method with an explicit argument, Tools.first<int>([1, 2]): 1. Inferred, Tools.first(["x", "y"]): x.
  • Inference from a lambda's return: Tools.apply(n => n > 2 ? "big" : "small") is big, and Tools.apply(n => n * 2) is 6. The inferred type argument reaches the running code: madeBy(n => "x", "y"), madeBy(n => "x", 5), madeBy(n => new Order(n), new Order(1)), madeBy(n => new Order(n), new Invoice(1)) give true false true false.
  • A nested generic, List<Map<string, Order>>, as a parameter and in is: true for [["a" => Order]], false for [["a" => Invoice]].
  • A generic interface implemented by two classes, Numbers : Source<int> and Words : Source<string>: drain gives 7 and seven. One class implementing it twice is refused: "This header names Supply twice."
  • A generic method value: Function<bool(List<Order>, Any)> test = Tools.holds; gives true false.
  • Self on a type parameter: refill<TBox : Cell<int>>(TBox box) => box.withValue(5) gives 5.
  • A raw object from plain PHP has its bounds: new Cell(2) into Cell<float> throws must be of type Probe.Cell<float>, Probe.Cell<Any?> given, and ReflectionObject::getTypeArguments() of a plain new Page([…]) is ['Probe.Entity'].
  • R3: [1, 2] is List<int> is true, [1, "x"] is not. A match arm of Page<Order> takes a PHP# Page<Order> and not a Page<Invoice>. catch (Failure<Order>) and catch (Failure<string>) each catch their own.
  • R4: two rounds of Counter<Order>.count += 1 twice and Counter<Invoice>.count += 5 give 2 5 0 1 0, then 4 10 0 2 0, with Counter<Entity> untouched and seen per type argument.
  • R5: typeof(Box<Order>) == typeof(Box<Invoice>), == of the same type, !=, and new (type)() tested as Box<Order> and Box<Invoice> give false true true true false.
  • Variance: Feed<out TItem> passes Feed<Order> as Feed<Entity> (11). Without out: "Feed cannot be used as Feed. … Help: TItem is only returned by Feed, so declare it out TItem." A member that breaks out or in is refused on its line.
  • Refused as the spec says: Counter.count ("Counter needs its type argument."), new Box(1), const orders = store.get("orders") ("Nothing fixes the type argument T of the call to Store.get."), Serializable on a generic class, a type parameter named Item, Map<Class<Order>, int> and [typeof(Box<Order>): 1], and value is Function<int(int)>.

Plain PHP crossing in, and int to float

Tools::takeOrders([new Order(1), new Invoice(2)])        TypeError (see 3.2)
Tools::countOrders([["a" => Order], ["b" => Invoice]])   TypeError: must be of type List<Map<string, Probe.Order>>, array given
Tools::kinds([1, 2.5, 3])                                double double double
Tools::sumFloats([1, 2, 3])                              6.0
Tools::mapKinds(["a" => 1, "b" => 2.0])                  a=double b=double
Engine::nestedKinds(["a" => [1, 2.5], "b" => [3]])       a:double a:double b:double
List<float> values = Feed.floats();  // plain PHP [1, 2.5]   double double
$floats->values = [1, 2];                                 [float(1), float(2)]
$values = [1, 2]; Tools::kinds($values)                   the caller's $values stays [int(1), int(2)]
Tools::kinds([1, "2"])                                    TypeError

No copy of a correct value: a 200,000-element List<int> from plain PHP grows memory by 1,024 bytes inside the callee, where a copy is at least 3.2 MB.

Refusals in "What stays refused"

Each gives the body's message, and none crashes:

new TItem.of(value)                         `new TItem` is not supported yet in PHP#.   (wording: see 3.3)
public event Moved<TItem>(TItem item);      A generic event is not supported yet in PHP#.
static … = typeof(Box<int>);                A static member's initial value that is not constant is not supported yet in PHP#.
Map<string> values                          `Map` takes 2 type arguments: the key and the value.
public Pair.of<TOther>(…)                   A named constructor takes its class's type arguments and declares none of its own.   (help: see 3.1)

Staleness

A caller's .sharpc lists the generic class's file as an input. After Holder<T : Entity> became Holder<T : Invoice>:

  • The engine, before a compile: "probe-stale/Call.sharp is out of date (probe-stale/Gen.sharp changed). Run vendor/bin/mago compile."
  • mago compile: "Type argument Order does not satisfy Holder's T."
  • After holds<T> became holds<TValue, T>, mago compile rewrote the caller to pass Stale.Order, Stale.Order, and it ran.
  • The warm path follows bound edits (the PR's test) and a variance edit (my scratch row), as 4.2 says.

Spec examples

sharp/bin/spec: "Checked 179 examples, ignored 1, and 86 fail", matching the list. Not counted: §11 generic-method-inference fails because the harness's App.Cache is also a namespace, and type-parameter-bounds and raw-generic-objects fail on harness classes. These are harness work, like the two examples the body names.

Probe sources

probe/Rules.sharp:

namespace Probe;

public abstract class Entity
{
    public Entity(public int id { get; }) { }
}

public class Order : Entity { }

public class Invoice : Entity { }

public class Page<TItem : Entity>
{
    public Page(private List<TItem> rows) { }
    public TItem first() => this.rows[0];
    public int size() => this.rows.count();
}

public interface Source<T> { T next(); }
public class Numbers : Source<int> { public int next() => 7; }
public class Words : Source<string> { public string next() => "seven"; }

public class Tools
{
    public static T first<T>(List<T> items) => items[0];
    public static TResult apply<TResult>(Function<TResult(int)> make) => make(3);
    public static bool holds<TItem>(List<TItem> items, Any value) => value is TItem;
    public static bool madeBy<TResult>(Function<TResult(int)> make, Any value) => value is TResult;
    public static string nestedTest(Any value) => `${value is List<Map<string, Order>>}`;

    public static string methodValue()
    {
        Function<bool(List<Order>, Any)> test = Tools.holds;
        return `${test([new Order(1)], new Order(2))} ${test([new Order(1)], new Invoice(2))}`;
    }

    public static string lambdaRuns()
    {
        bool a = Tools.madeBy(n => "x", "y");
        bool b = Tools.madeBy(n => "x", 5);
        bool c = Tools.madeBy(n => new Order(n), new Order(1));
        bool d = Tools.madeBy(n => new Order(n), new Invoice(1));
        return `${a} ${b} ${c} ${d}`;
    }

    public static T drain<T>(Source<T> source) => source.next();
    public static int countOrders(List<Map<string, Order>> groups) => groups.count();
    public static List<Map<string, Order>> grouped() => [["a": new Order(1)], ["b": new Order(2)]];
    public static int takeOrders(List<Order> orders) => orders.count();

    public static float sumFloats(List<float> values)
    {
        float total = 0.0;
        for (const value of values) { total += value; }
        return total;
    }

    public static string kinds(List<float> values)
    {
        string text = "";
        for (const value of values) { text = text + gettype(value) + " "; }
        return text;
    }

    public static string mapKinds(Map<string, float> values)
    {
        string text = "";
        for (const [key, value] of values) { text = text + key + "=" + gettype(value) + " "; }
        return text;
    }
}

public class Run
{
    public static string all()
    {
        Page<Order> page = new Page<Order>([new Order(4), new Order(5)]);
        int explicit = Tools.first<int>([1, 2]);
        string inferred = Tools.first(["x", "y"]);
        const fromLambda = Tools.apply(n => n > 2 ? "big" : "small");
        const intFromLambda = Tools.apply(n => n * 2);
        bool yes = Tools.holds([new Order(1)], new Order(9));
        bool no = Tools.holds([new Order(1)], new Invoice(9));
        int number = Tools.drain(new Numbers());
        string word = Tools.drain(new Words());
        int nested = Tools.countOrders(Tools.grouped());
        return `${page.first().id} ${explicit} ${inferred} ${fromLambda} ${intFromLambda} ${yes} ${no} ${number} ${word} ${nested} ${page.size()}`;
    }
}

Run::all() printed 4 1 x big 6 true false 7 seven 2 2.

probe/Engine.sharp and probe/Lib.inc:

namespace Probe;

import Lib.Feed;

public class Holder { public List<Order> orders { get; set; } = []; }

public class Cell<T>
{
    public required Cell(public T value { get; }) { }
    public Self withValue(T value) => new Self(value);
}

public class Floats { public List<float> values { get; set; } = []; }

public class Engine
{
    public static TBox refill<TBox : Cell<int>>(TBox box) => box.withValue(5);
    public static string selfRun() { Cell<int> box = Engine.refill(new Cell<int>(1)); return `${box.value}`; }
    public static string nestedKinds(Map<string, List<float>> groups) { … gettype of each value … }
    public static string boxKind(Cell<float> box) => gettype(box.value);
    public static string resultKinds() { List<float> values = Feed.floats(); … }
    public static int take(List<Order> orders) => orders.count();
    public static int ints(List<int> values) => memory_get_usage() - Engine.base;
    public static int base { get; set; } = 0;
    public static int fetched() { List<Order> orders = Feed.orders(); return orders.count(); }
}
<?php
namespace Lib;

final class Feed
{
    /** @var array<int, mixed> */
    public static array $next = [];

    /** @return list<float> */
    public static function floats(): array { return [1, 2.5]; }

    /** @return list<\Probe\Order> */
    public static function orders(): array { return self::$next; }
}

probe/Later.sharp, R3 to R5:

namespace Probe;

import RuntimeException;

public class Failure<T> : RuntimeException
{
    public Failure(public T item { get; }) : super("failed") { }
}

public class Counter<T>
{
    public static int count { get; set; } = 0;
    public static List<T> seen { get; set; } = [];
}

public class Box<T> { public required Box() { } }

public class Feed<out TItem : Entity>
{
    public Feed(private List<TItem> items) { }
    public TItem next() => this.items[0];
}

public class Later
{
    public static string tests(Any value)
    {
        bool ints = value is List<int>;
        Map<string, float>? prices = value as Map<string, float>;
        string arm = match (value) {
            Page<Order> page => "page of orders",
            Page<Invoice> page => "page of invoices",
            List<int> numbers => "ints",
            default => "other",
        };
        return `${ints} ${prices == null} ${arm}`;
    }

    public static string caught(Any item)
    {
        try {
            if (item is Order order) { throw new Failure<Order>(order); }
            throw new Failure<string>("x");
        } catch (Failure<Order> failure) {
            return `order ${failure.item.id}`;
        } catch (Failure<string> failure) {
            return `string ${failure.item}`;
        }
    }

    public static string statics()
    {
        Counter<Order>.count += 1;
        Counter<Order>.count += 1;
        Counter<Invoice>.count += 5;
        Counter<Order>.seen.add(new Order(3));
        return `${Counter<Order>.count} ${Counter<Invoice>.count} ${Counter<Entity>.count} ${Counter<Order>.seen.count()} ${Counter<Invoice>.seen.count()}`;
    }

    public static string classValues()
    {
        bool a = typeof(Box<Order>) == typeof(Box<Invoice>);
        bool b = typeof(Box<Order>) == typeof(Box<Order>);
        bool c = typeof(Box<Order>) != typeof(Box<Invoice>);
        const type = typeof(Box<Order>);
        const made = new (type)();
        Any held = made;
        bool d = held is Box<Order>;
        bool e = held is Box<Invoice>;
        return `${a} ${b} ${c} ${d} ${e}`;
    }

    public static int newest(Feed<Entity> feed) => feed.next().id;
    public static string variance() => `${Later.newest(new Feed<Order>([new Order(11)]))}`;
    public static Page<Order> orderPage() => new Page<Order>([new Order(1)]);
    public static Page<Invoice> invoicePage() => new Page<Invoice>([new Invoice(1)]);
}

Output, every mode, each of two rounds:

true true ints
false true other
false true other
false true other
false true page of orders
false true page of invoices
order 8
string x
2 5 0 1 0          (round 2: 4 10 0 2 0)
false true true true false
11
array ( 0 => 'Probe.Entity', )

Refusal probes, each its own file:

public class Maker { public static TItem make<TItem : Item>(int value) => new TItem.of(value); }
public event Moved<TItem>(TItem item);
public class Shelf<T> { public static Class<Box<int>> kind { get; set; } = typeof(Box<int>); }
public class Counts { public static int size(Map<string> values) => values.count(); }
public class Pair<T> { public Pair(public T first { get; }) { } public Pair.of<TOther>(T first, TOther other) : this(first) { } }
public class BareStatic { public static int read() => Counter.count; }
public class Unfixed { public static void run(Store cache) { const orders = cache.get("orders"); } }
public class RawNew { public static Box<int> make() => new Box(1); }
public class Serial<T> : Serializable { … }
public class Naming<Item> { }
public class MapKey { … Map<Class<Order>, int> … [typeof(Box<Order>): 1] … }
public class Invariant { public static int newest(Feed<Entity> feed) => …; … newest(new Feed<Order>(…)) … }
public class Sink<out T> { … public void put(T item) { } }   public class Source<in T> { public T take() => …; }
public class FunctionTest { public static bool test(Any value) => value is Function<int(int)>; }
public class Both : Supply<int>, Supply<string> { public int next() => 1; }

Staleness probe, probe-stale/Gen.sharp and probe-stale/Call.sharp:

public class Holder<T : Entity> { public required Holder(public T value { get; }) { } }
public class Tools { public static bool holds<T>(T sample, Any value) => value is T; }

public class Call
{
    public static int made() => new Holder<Order>(new Order(3)).value.id;
    public static bool inferred() => Tools.holds(new Order(1), new Order(2));
}

Master brings #110 (constructors) and #113 (verification). Both add
engine tests, fixtures and slice notes, and neither changes the engine
or `sharp/mago/`. Nothing conflicted. Their three new tests and
`opcodes.phpt`, which reads #110's new fixture, pass on this slice.
…four messages

Problem

- Plain PHP that calls an untyped private method, or reads a private
  property whose docblock callable has no return type, panics the
  analyzer: the PHP# private-reach check walks positions plain PHP has
  no type for.
- `value is Collection<Order>` on a plain PHP `@template` class
  compiles, at any depth and in `as`, a `match` arm and `catch`, and
  then tests only `Collection`: a plain PHP object carries no type
  arguments while the code runs.
- Type parameters on a named constructor of a generic class get help
  that quotes a method that doesn't compile there ("`Pair` needs its
  type argument").
- `new TItem.of(…)` says "`new TItem` is not supported yet", while
  `new TItem(…)` compiles.
- A class that reaches a generic interface twice through a parent, as
  `Strings : Ints, Feeder<string>` with `Ints : Feeder<int>`, gets a
  false `never` return type and "Diamond inheritance … template
  parameter". The staleness test edits only bounds, so a fingerprint
  that dropped variance or a type parameter would pass it.

Solution

- The private-reach checks run only for a PHP# class.
- A type test that gives a plain PHP class type arguments is one
  error: "`Collection<Order>` can't be tested: `Collection` is a
  plain PHP class, so its objects carry no type arguments while the
  code runs." Help: "Test `Collection` alone."
- The parser keeps the type parameter names of the class it reads, so
  the help in a generic class quotes `public static Pair<T> of(T
  value)`: it takes the class's type arguments.
- The message names the form: "A named constructor through a type
  parameter, as in `new TItem.of(…)`, is not supported yet in PHP#."
- A PHP# class-like that reaches a generic class-like with other type
  arguments is one error naming each way: "`Strings` implements
  `Feeder` twice: `Feeder<int>` through `Ints`, and `Feeder<string>`."
  Upstream's diamond check stays for plain PHP.
- The staleness test gains a variance row and an arity row. Each
  fails when its part of the type parameter list fingerprint is
  removed.

sharp/mago/crates/
├── analyzer/
│   ├── src/expression/mod.rs          is, as and match arms refuse erased type tests
│   ├── src/statement/mod.rs           report_erased_type_test, at any depth
│   ├── src/statement/try.rs           catch refuses erased type tests
│   ├── src/statement/class_like/mod.rs check_sharp_reached_twice; diamonds stay plain PHP's
│   ├── src/utils/template.rs          private reach gated on a PHP# class
│   └── tests/sharp.rs                 .php rows for private reach, erased tests, help compiles, reached twice
├── orchestrator/src/service/incremental_analysis/compile.rs  variance and arity rows
├── semantics/
│   ├── src/internal/checker/sharp.rs  names `new TItem.of(…)`
│   └── tests/sharp.rs                 the message's row
├── sharp-bridge/tests/lower.rs        erased is and as refused before lowering
└── syntax/src/
    ├── error.rs                       the error carries the class's type parameter names
    └── parser/                        State.type_parameters_of, set beside members_of
Problem

type_arguments_entry_check.phpt names about 25 rules in its title, and
type_arguments_call.phpt about 15. A broken rule fails the one test
whose name lists every rule, so the failure doesn't say which rule
broke.

Solution

Each rule runs in its own .phpt over the same fixtures, with its
expected lines unchanged. The call tests keep their two rounds, so the
second still runs the code the tracing JIT compiled on the first. The
JIT trace test runs the definitions alone, plus a generic call through
an interface, which gives the DO_FCALL the whole body gave it.

Zend/tests/sharp/
├── type_arguments_entry.inc                       new: the requires and attempt every entry test shares
├── type_arguments_entry_argument.phpt             new: calls from plain PHP, callbacks, constructors, operators, lambdas
├── type_arguments_entry_any.phpt                  new: a written Any? matches only Any?
├── type_arguments_entry_erased.phpt               new: a plain PHP generic class's type arguments are erased
├── type_arguments_entry_unresolved.phpt           new: a type parameter plain PHP leaves unresolved
├── type_arguments_entry_variance.phpt             new: out and in at any depth
├── type_arguments_entry_return.phpt               new: a plain PHP call's return
├── type_arguments_entry_property.phpt             new: a property write and reflection
├── type_arguments_entry_static_property.phpt      new: a static property, a subclass, a reference
├── type_arguments_entry_float.phpt                new: an int for a float becomes a float
├── type_arguments_entry_collection.phpt           new: a collection is checked element by element
├── type_arguments_entry_collection_test.phpt      new: is, as and match test every element
├── type_arguments_entry_collection_property.phpt  new: a whole write walks, an append doesn't
├── type_arguments_entry_open_property.phpt        new: a property typed by its class's type parameter
├── type_arguments_entry_open_reference.phpt       new: no reference to such a property
├── type_arguments_entry_unserialize.phpt          new: unserialize checks what it fills
├── type_arguments_entry_accepts.phpt              new: Sharp\Internal\accepts collects each bad value
├── type_arguments_entry_check.phpt                deleted
├── type_arguments_call_given.phpt                 new: the type arguments a call writes or infers
├── type_arguments_call_fiber.phpt                 new: across a Fiber suspension
├── type_arguments_call_read.phpt                  new: is, as, match, typeof, new and statics read them
├── type_arguments_call_catch.phpt                 new: a catch clause tests them
├── type_arguments_call_bound_lambda.phpt          new: a lambda bound to another class has none
├── type_arguments_call_statics.phpt               new: each type argument's own statics
├── type_arguments_call_class_value.phpt           new: a class value carries its type arguments
├── type_arguments_call_class_value_entry.phpt     new: a class value entering from plain PHP
├── type_arguments_call.phpt                       deleted
├── type_arguments_call.inc                        deleted
└── type_arguments_call_jit_trace_types.phpt       runs the definitions and an interface call
Problem

A List, Map or Set plain PHP passes, assigns or returns with one wrong
element fails as "must be of type List<Probe.Order>, array given". It
reads as "a List takes no array", and a 10,000-element list gives no
way to find the bad element. The walk that refused the array already
writes "[1] expected Probe.Order, got object Probe.Invoice" when it
collects problems.

Solution

When the refused value is an array, the TypeError reruns the failing
walk with problems and appends its first entry: "…, array given: [1]
expected Probe.Order, got object Probe.Invoice". The parameter, return
and property errors all take it. An array whose bad value is the array
itself, as a List with string keys, keeps today's text.

ext/sharp/sharp.c                                 sharp_first_problem, appended by the three TypeErrors
Zend/tests/sharp/
├── type_arguments_entry_collection.phpt          each wrong element named: argument, nested, Map value, Set, return
├── type_arguments_entry_collection_property.phpt a whole property write names it
├── type_arguments_entry_argument.phpt            a wrong object in a List names its type arguments
├── type_arguments_entry_unserialize.phpt         unserialize names it
├── enum_keys.phpt, enum_keys_jit_*.phpt          a wrong Map key is named as a key
└── set_methods.phpt, set_methods_jit_*.phpt      a wrong Set element is named
…rics branch

Problem

#115 landed extensions, spec section 26, on master after #102's last
merge, so #102 conflicts with master and CI doesn't run on it.

Solution

Merge master. Each conflict keeps both sides:

- The doc comments and "supported" messages of a class name both type
  parameters and extensions.
- `MethodParts` of an extension method takes the method's type
  parameters, as `of_method` does, and a computed property's takes
  none.
- `NameWalker::new` starts the branch's type parameter scopes beside
  master's extension receiver.
- The bridge's operator, named constructor and lambdas keep the branch's
  parameter metadata and captured type arguments, and pass master's
  `set_parameters` the parameter sequence it now takes.
- `report_method_access_on_null` and `extension_access` join the
  branch's functions at the same places.

sharp/mago/crates/
├── analyzer/src/resolver/{method,property}.rs  both sides' imports and functions
├── names/src/binding.rs                        extension parts carry type_parameters
├── names/src/internal/walker.rs                type_parameters starts empty in new()
├── semantics/src/internal/checker/sharp.rs     a class's text names both
├── semantics/tests/sharp.rs                    the merged message
├── sharp-bridge/src/lower.rs                   branch metadata, master's set_parameters
└── syntax/src/parser/internal/class_like/method.rs  both doc sentences
Problem

patch-coverage at bb1a691 found two lines of
check_sharp_reached_twice that no test runs: a header entry that
reaches the ancestor with type arguments another entry already gave,
and a class whose header shows only one way to an ancestor reached
twice.

Solution

Two rows. `Twice : Ints, IntFeeder, Feeder<string>` reaches
`Feeder<int>` twice and `Feeder<string>` once, and its error names
`Feeder<int>` once. `Child : Strings` reaches `Feeder` only through
`Strings`, which is refused already, and gets no second error.

sharp/mago/crates/analyzer/tests/sharp.rs   the Twice and Child rows
…s branch

Problem

#121 landed modules and the container, spec section 32, while #102's
CI ran, so #102 conflicts with master again.

Solution

Merge master. Each conflict keeps both sides, and four places where
the features meet are joined:

- The engine's globals, stub and Sharp\Internal functions keep both
  sides. sharp_arginfo.h is generated again from the merged stub.
  Both sides registered `ext_functions` in MINIT, so the engine warned
  "duplicate name" for each function. Master's one call stays.
- A module member resets the parser's type parameter names, as every
  other class-like member does.
- A binding declares no type parameters, so its scan passes an empty
  TypeResolutionContext, and its lambda captures no type arguments.
  A module's comparison follows PHP# rules through `for_dialect`.
- A constructor parameter whose type names a type parameter, as
  `List<TItem>` does, is no service: its objects are of a type each
  type argument fixes. Before this, it got a `Sharp\Internal\Service`
  attribute naming a Mago template id.

ext/sharp/
├── sharp.c              both sides' globals; one ext_functions registration
├── sharp.stub.php       both sides' functions
└── sharp_arginfo.h      generated from the stub
sharp/mago/crates/
├── analyzer/src/statement/module.rs        ComparisonResult::for_dialect(Dialect::Sharp)
├── analyzer/tests/sharp.rs                 both sides' tests
├── codex/src/scanner/{class_like,function_like}.rs  empty TypeResolutionContext for a binding
├── sharp-bridge/src/lower.rs               both fields; dropped_service skips a type parameter
└── syntax/src/parser/internal/module.rs    master's members, with type_parameters_of reset
Problem

`as Map<string, float>?` is refused, as section 14.4 refuses every `?`
that cannot matter, but the error doesn't say what to write instead.
`as` already gives null when the value doesn't fit, so the fix is the
type without its `?`.

Solution

The refusal of a nullable `as` gets the help "Write `as Map<string,
float>`.", quoting the type as written without its `?`. `as void`
keeps today's text.

sharp/mago/crates/semantics/
├── src/internal/checker/sharp.rs   the help names the type without `?`
└── tests/sharp.rs                  `as int?` and `as Map<string, float>?` rows with their help
Problem

patch-coverage at 45cab9a found the `as void` path of the nullable
`as` refusal unrun: no test writes `as void`.

Solution

A row writes `as void`. It gets the refusal, and no help, since
`void` has no `?` to drop.

sharp/mago/crates/semantics/tests/sharp.rs   the `as void` row
…ound's member wins

Problem

#115's extensions and this PR's generics meet here in two places:

- Plain PHP that calls an extension member through its class, as
  `WalletExtensions::counted($wallet, [1, 'x'])`, passes the wrong
  element into PHP# code unchecked. A method, an operator and a named
  constructor end their parameter list with the type texts a call from
  plain PHP is checked against, and an extension member didn't.
- A receiver typed `TRush : RushOrder` ran an extension's `total`
  though `RushOrder` declares its own: the check for a real member that
  hides an extension skipped a type parameter, so its bound hid nothing.

Solution

- An extension member's parameter list ends with the same metadata,
  read from the static method it runs as, so plain PHP's call throws
  "Argument #2 ($amounts) must be of type List<int>, array given: [1]
  expected int, got string 'x'".
- A type parameter shows its bound's types to that check, at any depth,
  so `rush.total(2)` runs `RushOrder`'s own member, and `order.total(2)`
  on `TOrder : Order` still runs the extension.

sharp/mago/crates/
├── codex/src/metadata/mod.rs        get_classes_hidden_by_extension reads a type parameter's bound
├── sharp-bridge/src/lower.rs        extension_parameters ends with parameter_metadata
└── sharp-bridge/tests/lower.rs      a bound that declares the member and one that doesn't
Zend/tests/sharp/
├── WalletExtensions.sharp           counted(List<int> amounts)
└── extension_entry_check.phpt       new: plain PHP calls it with a right and a wrong list
…compile fix (#126)

Problem

Master moved `Sharp\Environment` out of C into the standard library as a
`foreign` class, and added `foreign` classes, `uses` on methods without a
body, and the rule that no static holds a `foreign` object. Generics changed
the same parser, binder, checker, bridge and extension files. Joined, four
things broke:

- `Method` grew by both sides' arena fields, and clippy's
  large_enum_variant refused `ClassLikeMember`.
- A method value of a plain PHP `@template` method, as `List.wrap`, kept its
  unfixed `T`. Generics hold an unfixed type parameter to itself, so
  `Shelf.make(List.wrap)` into a `Function<List<Any?>(Any?)>` was refused.
- Two generics fixtures implement a pure interface method with `sprintf`,
  which has no `extern`, so the effects check refused them.
- The opcodes test pinned its `Generics` difference against the old `link`
  body.

Solution

- Keep both sides in every conflict. `ext/sharp/sharp.c` keeps the type
  texts and takes master's native `Environment.commandLine`, and
  `sharp_arginfo.h` is regenerated from the merged stub. sharp/bin/native
  writes the same `sharp_native.h` and `native.php`.
- A method's `on` clause moves into the arena, as `type_parameters` and
  `uses` already sit there, so `Method` fits clippy's limit again.
- `fix_type_arguments` infers a plain PHP method value's `@template` types
  from the function type it goes into, as it does a PHP# method's. A plain
  PHP method's type arguments never reach the engine, so it records none and
  refuses none, and the value stays PHP's first-class callable.
- The fixtures build their strings with template strings, in the `.sharp`
  and its `.inc` twin alike, and the opcodes test pins the three `.php`
  lines the old `link` body hid.
- A new analyzer test holds the join of the two features: a value whose type
  parameter has a `foreign` bound, and a generic class's `foreign` type
  argument, are refused in a static, and a bound that is no `foreign` class
  is not.

ext/sharp/
  sharp.c                      type texts kept, Environment from master
  sharp_arginfo.h              regenerated from the merged stub
sharp/mago/crates/
  syntax/src/cst/cst/class_like/method.rs     `on` lives in the arena
  syntax/src/parser/internal/class_like/method.rs   allocates it
  syntax/src/parser/internal/statement.rs     internal or foreign, one return path
  names/src/binding.rs         both imports, `on` read as it is
  analyzer/src/resolver/property.rs           plain PHP method values infer
  analyzer/src/statement/class_like/listener.rs     `on` read as it is
  analyzer/src/expression/call/method_call.rs       both imports
  semantics/src/internal/checker/sharp.rs     an enum's `ClassLike` has both fields
  sharp-bridge/src/lower.rs    static_type_text kept, master's class_flags doc
  orchestrator/src/service/incremental_analysis/compile.rs   both tests kept whole
  analyzer/tests/sharp.rs      foreign behind a type parameter or argument
  syntax/tests/sharp.rs        `on` read as it is
Zend/tests/sharp/
  Generics.sharp, Generics.inc, TypeArguments.sharp   template strings
  opcodes.phpt                 three pinned `.php` lines
Problem

type_arguments_requests.phpt fails when a worker's peak grows by 4 MiB over
two requests. Each request reads 20,000 Function texts whose 62 parameters
spell a random number as `string` or `int`. The random high bits change how
many parameters are `string`, so one request's texts can be some 1.8 MB
longer than another's. Locally the heap peak moved between 59,768,832 and
55,574,528 bytes across requests, with nothing kept. On Linux CI the peak
grew by exactly 4,194,304 bytes without opcache and with the tracing JIT,
and the test failed.

Solution

The parameters spell the number as `string` or `float?`, both six bytes, so
every request reads as many bytes. Locally the heap peak is 68,157,440 bytes
in all four requests. A worker that kept the texts would still grow by some
10 MB a request, far over the 4 MiB limit.

Zend/tests/sharp/
  type_arguments_requests.phpt   parameter types of one length
Problem

Master's #124 calls a plain PHP function or constant only through its
namespace, as `global.sprintf(…)`, and refuses a statement that never runs.
Seven files conflicted with generics, and the joined branch broke in four
places:

- Three engine fixtures and three bridge tests called plain PHP functions
  bare, which `mago compile` now refuses.
- The branch analyzed a `.sharp` file's code after `throw` through
  `Context::analyze_dead_code`. Master now refuses that code and stops the
  block there, so the branch's method could no longer change anything, and
  its test expected the old error.
- The Set row for `array_key_exists` called the function bare. Through
  `global.array_key_exists` the call reaches no assertion, so the row lost
  the narrowing it pinned.
- An analyzer row expected the old message for an unknown function.

Solution

- Keep both sides in every conflict. `AnalysisArtifacts` holds the tested
  types and the namespace constants. A property read takes master's
  namespace constant and unknown class arms first, then this PR's class
  constant arm, which reads a generic class too. The staleness tests keep
  this PR's type parameter test and master's constant tests whole. The throw
  test is master's. opcodes.phpt keeps this PR's checks and master's five
  `Interop` op arrays.
- Fixtures and tests call `global.sprintf`, `global.max`,
  `global.get_defined_vars`, `global.count`, `global.str_split` and
  `global.orders`.
- `Context::analyze_dead_code` and its test are deleted. The loop reads
  `settings.analyze_dead_code` again, as master does.
- The Set row moves to plain PHP, which still calls `array_key_exists`
  bare, on the `Set` a PHP# method returns. It fails without the narrowing.

Zend/tests/sharp/
  Generics.sharp, TypeArgumentsCalls.sharp, TypeArgumentsChecks.sharp   global calls
  opcodes.phpt                 both sides' lines
sharp/mago/crates/analyzer/
  src/artifacts.rs             tested types and namespace constants
  src/expression/access/mod.rs master's arms, then the generic class constant arm
  src/statement/function_like/mod.rs   both artifact maps merged up
  src/context/mod.rs           analyze_dead_code deleted
  src/statement/mod.rs         reads the setting again
  tests/sharp.rs               Set row in plain PHP, unknown function message
sharp/mago/crates/orchestrator/src/service/incremental_analysis/compile.rs   both tests whole
sharp/mago/crates/sharp-bridge/tests/lower.rs   master's throw test, global calls
sharp/mago/tests/sharp.rs      the dead code test deleted
@heyJordanParker
heyJordanParker merged commit 753cb01 into master Oct 14, 2026
22 checks passed
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
One file conflicted. crates/syntax/src/parser/internal/statement.rs keeps
master's arms, which return each parse's Result as it is, and this
branch's `"self"` among the tokens that start a local, so `Self copy = …`
still reaches check_self_type.

#102 brings Class<T>, new (type)(…) and typeof of a type parameter, so
typeof-type-parameters and typeof-values pass with this branch's harness
Element and Order and its Class.of, and leave sharp/baseline/spec/§25/.
typeof-types, class-members and generic-class-values stay listed until
Class's attributes member and the harness PaginatedList land.
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
…ments

Problem

Class.of(value) returned the bare class name of any object, so for a
Box<Order> it gave a value that neither equals typeof(Box<Order>) nor
carries Order: Class.of(box) == typeof(Box<Order>) was false, and
new (Class.of(box))() created a Box with its bounds instead of a
Box<Order>. The merge with #102 also changed how Mago refuses Class.of(5),
and no row passed a Class<Badge> parameter on to plain PHP.

Solution

For an object of a generic class, Sharp\Class::of spells the object's
class with the type arguments #102 stores on it and returns the class
value #102 interns for that spelling, the same one typeof(Box<Order>)
gives. An object of any other class still gives its class name. An engine
test checks the comparison both ways and that new (Class.of(crate))()
keeps the type arguments, and a Class<Badge> parameter reaches the plain
PHP Factory::make as its class name. Class.of(5) is now refused once,
"`5` does not satisfy the bound `Object` of type parameter `T`.", and the
analyzer row reads that message.

ext/sharp/
└── sharp.c                         Sharp\Class::of reads the type arguments
Zend/tests/sharp/
├── ClassValues.sharp               Crate<TItem>, sameAsTypeof, fromValue
├── class_of.phpt                   Class.of(crate) equals typeof(Crate<Badge>)
└── class_value_to_plain_php.phpt   a Class<Badge> parameter reaches plain PHP
sharp/mago/crates/analyzer/tests/
└── sharp.rs                        Class.of(5) is refused once
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
…oose) included

Problem

Spec section 25 says new (type)(…) needs a required constructor, as
new Self(…) does, whatever the class value holds. #102 refused it for a
Class<Loose> parameter but accepted a value that holds exactly one class:
new (typeof(Loose))() and `const type = typeof(Loose); new (type)()`
compiled with a constructor no subclass has to keep.

Solution

The required check in analyze_class_instantiation now covers every new
through a class value in a PHP# file, a literal one included. Its message
says "a class value can hold any subclass of `Loose`", which reads true
for both forms. Two rows show the refusal of the exact forms beside the
parameter's.

sharp/mago/crates/analyzer/
├── src/expression/instantiation.rs   the required check covers an exact value
└── tests/sharp.rs                    rows for typeof(Loose) and a const of it
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
… section 25 shows

Problem

Spec section 25's generic-class-values example failed on "Cannot find type
`PaginatedList`.": the spec harness had no PaginatedList, so nothing
showed that typeof(PaginatedList<Order>) creates a PaginatedList<Order>
and that new (any)() on an open generic class is refused for its own
reason rather than for the missing class.

Solution

The harness declares PaginatedList<TItem : DatabaseEntity> with a required
constructor whose rows default to [], which new (pages)() and section 11's
plain PHP new PaginatedList($rows) both call. Each annotated line now
gives its annotated result: fresh() and ofOrders() compile, and open()
gets "`PaginatedList` needs its type argument.". The example leaves the
list. Section 11's raw-generic-objects now passes the checker and fails
only when it runs, on its elided bodies, so it stays listed. The design
note records the merge's states.

sharp/
├── baseline/spec/§25/        generic-class-values leaves
└── harness/app/
    └── PaginatedList.sharp   NEW: PaginatedList<TItem : DatabaseEntity>
docs/
└── architecture/slices/
    └── 25-class-values.md    the states after the merge with #102
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
Brings #102: reified generics, with their type checks of values plain PHP
gives, and makes them hold this branch's Map and Set objects.

Problem

#102 keeps master's model of a Map and a Set: a PHP array keyed by each
backing value, read back through `from` or `(string)`. This branch made
each one a `Sharp\Map` or `Sharp\Set` object that keeps every key as
itself. After a plain merge:
- #102's type walk took a Map or a Set only as a PHP array, so every
  `Sharp\Map` plain PHP passed to a `Map<…>` parameter was refused, and a
  PHP# typed property took a PHP array from plain PHP without crossing it.
- A union or nullable key type, as `Map<string|Level, int>`, refused the
  int key PHP holds the string "5" as.
- The checker refused `Map<TKey, int>` with `TKey : Status & HasLabel`.
- The lowering, the checker, the analyzer and the codex each carried both
  key models.

Solution

This branch's model wins for keys. Every generics feature of #102 stays.
- The type walk reads a `Sharp\Map` or `Sharp\Set` entry by entry, each
  key as the value it is, and a refusal names the bad entry's path. A PHP
  array it takes for a PHP# Map or Set property crosses into the object,
  as the property's #[\Sharp\Crossing] plans it. A parameter's PHP array
  still crosses in the method's first statements, by its crossing plan.
- A union or a nullable key type takes the keys any member takes.
- An intersection keys a Map when one of its members does.
- Master's backing-key read-back, `Types::backed_enum` and
  `get_sole_backed_enum` go. A class value keys no Map, as #102 rules.
- `Lowering::call` takes a generic method's type arguments, so one path
  crosses arguments and appends them. `Lowering::instantiation` gives a
  generic class's `new`, `new TItem(…)`, `new (type)(…)` and `new Self(…)`
  their type arguments beside an object initializer.
- `erase` lowers a Map or a Set to its class. A Map property's type is
  `Sharp\Map` under the type text a plain PHP write is checked against.
- A struct header takes a generic interface.
- The dead `target_dialect` of template inference goes.
- The spec baseline drops struct-parse, which passes once both sides meet.

php-sharp
├── Zend/tests/sharp/
│   ├── Generics.inc                  <- the twin's Map properties are Sharp\Map
│   ├── TypeArgumentsChecks.sharp     <- ordered and counted take a Map and a Set
│   ├── type_arguments_entry_collection.phpt
│   │                                 <- rows: a Sharp\Map or Sharp\Set object passes,
│   │                                    a bad entry fails naming its path, a PHP array
│   │                                    converts, the key "5" stays "5" for string and
│   │                                    string?
│   ├── type_arguments_call_hidden.phpt
│   │                                 <- reads the Map's keys with keys()
│   ├── table_property_writes.phpt    <- a key no case backs is the walk's TypeError
│   ├── enum_keys*.phpt               <- the walk refuses "missing" before the crossing
│   ├── set_methods*.phpt             <- the walk refuses 1.5 for Set<string>
│   └── opcodes.phpt                  <- both sides' rows
├── ext/sharp/
│   ├── sharp.c                       <- the walk reads Sharp\Map and Sharp\Set;
│   │                                    sharp_property_accepts crosses a PHP array;
│   │                                    sharp_type_holds_key reads T? and unions
│   ├── php_sharp.h                   <- both sides' declarations
│   └── sharp_arginfo.h               <- regenerated from the stub
├── Zend/zend_compile.c               <- both sides' prop_decl
├── sharp/baseline/spec/§10/struct-parse
│                                     <- removed: the example passes
└── sharp/mago/crates/
    ├── codex/src/ttype/mod.rs        <- is_key_type reads intersections;
    │                                    get_backing_key_type composed
    ├── semantics/src/internal/checker/sharp.rs
    │                                 <- check_generic keeps this branch's key rule
    ├── analyzer/src/invocation/template_inference.rs
    │                                 <- direct key comparisons, no target_dialect
    ├── sharp-bridge/src/lower.rs     <- call with type arguments; one instantiation;
    │                                    erase of Map and Set
    ├── sharp-bridge/src/lower/types.rs
    │                                 <- backed_enum goes
    ├── syntax/src/parser/internal/   <- struct header takes a generic interface
    └── */tests/                      <- both sides' rows in this branch's key model
heyJordanParker added a commit that referenced this pull request Oct 15, 2026
…Any?> first

Decision 5 as approved: a list pattern's first test is #102's
`is List<Any?>`. `php_shape` writes it as `instanceof` a name spanning
the `[`, where the analyzer records `List<Any?>`, so the analyzer narrows
an `Any` to a list. The bridge lowers it as `\is_array` on a value the
analysis knows is a `List` or a `List?`, so those keep their opcodes and
never walk the elements, and as `SHARP_IS_TYPE List<Any?>` otherwise.
The "A list pattern on a `Any` is not supported yet" arm is gone; a
value that can hold no `List` still never matches.
@heyJordanParker
heyJordanParker deleted the feat/slice-generics branch November 3, 2026 22:08
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