Repository navigation
feat: PHP# generics, checked and carried at runtime (spec section 11, R1 to R5) - #102
Conversation
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
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
|
Review verdict: CHANGES NEEDED Head: The blocking change: 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. Changes1. Crash: plain PHP aborts the checker (
|
…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
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.
…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
…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
… 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
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
…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.
Problem
A PHP# developer writes
class Counter<T>,T first<T>(List<T> items),List<Order> orders = cache.get("orders");andnew PaginatedList<Order>(rows). Spec section 11 makes all of them valid, and says the running program knowsOrderin 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,iscan't test aList<int>or a type parameter, andCounter<Order>andCounter<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 insharp/mago/, so #152's checker half is merged into this branch and #152 is closed.The checker
<TItem : DatabaseEntity & Shareable>),inandoutmarkers, and type arguments on types, headers,new, calls,typeofand a class read as an expression, as inCounter<Order>.count. Each type parameter binds to its declaration.Any?as the bound of an unbounded parameteroutandinas spec 11.1 rules them, and invariance for a parameter with neitherSelfon a receiver typed by a type parameterSerializablerefused on a generic classnew, written without its type arguments is refusednew Box<Pair<int>>()is refused??and?:. One that neither fixes is refused, as C#'s CS0411 is: "Nothing fixes the type argumentTof the call toStore.get." A generic method value takes its type arguments from the function type it goes into.is,as, amatcharm and acatchtest aList, aMap, aSet, a union, a nullable type, a type parameter and a class with type arguments. A function type andClass<T>have no test, and the checker says why.new TItem(…),typeof(TItem)andTItem.LIMITread the type argument while the code runs.Counter<Order>.count,Counter<Order>.reset()andCounter<Order>.LIMITread and write the statics of that type argument. A static method of a generic class takes its class's type arguments.typeof(Box<Order>)is aClass<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 twoTypes. A class value keys noMap.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.SHARP_AST_VERIFY_TYPE_ARGSwherever 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.List,MapandSetare refused, for example.The engine
ZEND_ACC_SHARP_HIDDEN, that holds its object's type arguments.newfills it throughZEND_SHARP_TYPE_ARGS.clone,serializeandunserializekeep it, and==compares it. No view of the object shows it.ZEND_SHARP_RECV_TYPE_ARGS. A lambda captures them. A plain PHP call pays nothing.App.PaginatedList<Set<int>>is one descriptor, so equal types are one pointer.sharp_type_acceptswalks aList, aMap, aSet, a union and an object with type arguments, and turns anintafloattakes into afloat. Each place plain PHP hands PHP# a value runs it and throwsTypeErroron a mismatch:ZEND_SHARP_VERIFY_TYPE_ARGSZEND_ACC_SHARP_TYPED, so a subclass, a reference and reflection are checked toounserializeSHARP_IS_TYPEtests a value foris,as, amatcharm and a genericcatch.outandinkeep their variance in the class'ssharp_variance, and the entry checks honor it."".\Sharp\Internal\staticsreturns an entry by reference and copies the defaults on first use. Plain PHP and reflection neither name nor list the store.typeof(Box<Order>)returns the descriptor's own interned class name, whichsharp_class_valuesmaps 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. AClass<Box<Order>>parameter, result or property takes only a class value of that type 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.sharp/bin/censuschecks every write of a markedop1orop2.Test any PHP# type (R3)
type_test_ofis the one decision of which typesisandastest. A type with no PHPinstanceoflowers toSHARP_IS_TYPE, which carries the type text the engine walks:An
asoristhat always holds says so in the code's words.outandinare@template-covariantand@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++andCounter<Customer>.count++change two numbers. A method call on a static collection field binds the field by reference, soLog<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 aClass<Box<Order>>, and it reaches plain PHP as the class name.new (type)()gives aBox<Order>.type.count = 1writes the static ofBox<Order>, astype.countreads 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:type_arguments_call_class_value.phptprintsfalse, true, true, true, falsefor these. Without the lowering it printstrue, true, true, false, true.One check,
is_map_key, refuses a class value as aMapkey in all three places one can appear:Map<Class<Order>, int>[typeof(Order): 1]MapthatgroupByorassociateByinfers from a key function that returns a class valueEach is "A
Map's keys areint,stringor a type with anintorstringbacking value, andClass<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,operatorandlambda_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_argumentspins all five.The bridge wraps a value in
SHARP_AST_VERIFY_TYPE_ARGSwhen 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:Plain PHP passes a
PaginatedList<Customer>where PHP# expects aPaginatedList<Order>. Thetype_arguments_entry_*.phpttests show each TypeError, one rule per test:Every TypeError names an object's class with dots, as the expected type is written:
Checks.Customer, neverChecks\CustomerbesideApp.PaginatedList<App.Order>. A class value with type arguments is named by itsClasstype. 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
IS_OBJECT | ZEND_SHARP_OPERATOR, so plain PHP takes none of it.receiver#Nfollowscompound_assignment's temporaries.TypeOf.type_argumentsfollowsInstantiation's precedent. A static write through a class value and the one Map-key check are part of R5, because R5 owns class values.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 showsPaginatedList<Order>" is met byReflectionObject::getTypeArguments()on the object.sharp/harness/is guarded.PaginatedList.sharpand theElement.sharpchange go in a harness-only PR after this one merges, sotypeof-type-parametersandgeneric-class-valuesstay listed insharp/baseline/spec/.= 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#."unused-template-parameterwhen 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 bareCounter.trackmessage that omits the missing type argument (Reflection throws on a method with a plain PHP callable parameter #514).==between class values: it compares the whole type, type arguments included, as C# does. This PR builds it.value is Function<int(int)>stays refused.Plain PHP stays the same
mago analyzeover a plain PHP corpus, built from master5d5724a95aand 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,@implementsandclass-string<T>uses, an untyped private method and a privatecallable(int)property. Master gives 17,812 lines and this head 17,813, with no panic:It comes from the
ReflectionEnumfix that4c501c237keeps, the line the review found too.Section 11 rules and their state
new, calls, headers, statics and class values carry them, and the engine keeps them on the objectPaginatedList<Order>ReflectionObject::getTypeArguments()returns["App.Order"].ReflectionTypestays PHP'sReflectionObject::getTypeArguments()page is PaginatedList<Order>is checked while the code runsas, amatcharm and acatchvalue is Collection<Order>on a plain PHP@templateclass is a compile erroris,as, amatcharm and acatch: "Collection<Order>can't be tested:Collectionis a plain PHP class, so its objects carry no type arguments while the code runs."TypeErrorunserialize, a collection's elements includedintwhere PHP# expects afloatbecomes afloatfloatparameter, aT = floatparameter, and the typed local and property checks, inside collections toonewalways names its type argumentsnew Box(1)is refused, "Boxneeds its type argument"new Self(…)names noneClass<PaginatedList>@templategenerics keep their fallbacknewrulevalue is TItemT&Any?SerializableMapkeyMap==compares two class values by their whole type!=and a collection search, through\Sharp\Internal\equalsSelfon a receiver typed by a type parameter is that type parameterout,in, invariantcatchWhat stays refused
new TItem.of(1)new TItem.of(…), is not supported yet in PHP#."new TItem(value)compilesevent Moved<TItem>(TItem item);Maptakes 2 type arguments: the key and the value."public static Pair<T> of(T value), which compiles thereStringsimplementsFeedertwice:Feeder<int>throughInts, andFeeder<string>."Feedertwice isThe review of
66c6b8d44eEach change the review asked for, at head
ea2ea81e9b:f4ae6879bcmerges php-sharp master5d5724a95a(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.bb1a691414merges php-sharp mastere19d4c27c8(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 newset_parametersargument.a6cd08c91efixes the checker:.phprows pin it.is,as, amatcharm and acatch. Analyzer and bridge rows pin it.new TItem.of(…)names the form refused.neverreturn type and "Diamond inheritance … template parameter". Upstream's diamond check stays for plain PHP.7b4ac21a28splitstype_arguments_entry_check.phptinto 16 tests andtype_arguments_call.phptinto 8, one per rule over the same fixtures, with every expected line unchanged.d5be88d8d4makes a wrong element from plain PHP name its path and the type found: "…, array given: [1] expected Probe.Order, got object Probe.Invoice".b48d4e71cfadds 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 reachingFeedertwice is not refused again.c340ebdff4merges php-sharp masterf208b11e74(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:Sharp\Internalfunctions in the engine's startup, which warned "duplicate name". Master's one registration stays.List<TItem>does, is no service the container gives. Before this, it got aSharp\Internal\Serviceattribute naming a template id.45cab9a4fdmakesas T?, as inas Map<string, float>?, say what to write: "Writeas Map<string, float>."asalready gives null when the value doesn't fit.32ba9db945adds theas voidrow patch-coverage asked for: it keeps the refusal, with no help.7c01edba21joins extensions and generics:extension_entry_check.phptpasses[3, 4]tocounted(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.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.e30c8462famerges php-sharp masterc6a673cdde(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\Environmentis now master's library class, so the engine keeps this PR's type texts and master's nativecommandLine, andsharp_arginfo.his regenerated from the merged stub.usesand this PR's type parameters together tookMethodpast clippy'slarge_enum_variantlimit again. A method'sonclause now lives in the arena too.@templatemethod, asList.wrappassed where aFunction<List<Any?>(Any?)>goes, takes its type arguments from that function type, as a PHP# method's does. Before, its unfixedTwas refused. It records none, so the engine still runs PHP's first-class callable.foreignobject behind a type parameter's bound or a generic class's type argument. A new analyzer test pins both, and a bound that is noforeignclass.sprintf, which master's effects check refuses. They use template strings, andopcodes.phptpins three.phplines the old body hid.bc49d3928asteadiestype_arguments_requests.phpt. Its random type texts spelled each bit asstringorint, 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 nowstringorfloat?, 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.ea2ea81e9bmerges php-sharp master660ad5a094(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:global.sprintf,global.maxand the rest in place of bare calls..sharpfile's code afterthrow. Master refuses that code and stops the block there, soContext::analyze_dead_codeand its test are deleted.global.array_key_existsa call reaches no assertion, so the Set row moves to plain PHP, which still calls it bare on theSeta PHP# method returns.The move into
sharp/mago/14cfa4bad4merges php-sharp masterf670be8f1e(#120). Two files conflicted:ext/sharp/sharp_unit.htook master's side, which names no Mago commit.sharp/baseline/specwas removed for master's folder.cf3e3c4256merges mago-sharpfeat/slice-genericsatcb9e2842fintosharp/mago/, as docs/architecture/mago.md says under "Moving an open mago-sharp branch":sharp/mago/.github/actions/setup-lean/action.ymlandsharp/mago/.github/workflows/ci.ymlare removed. The branch changed neither, and.github/carries mago-sharp master's versions.ext/sharp/sharp_unit.his the header the merged bridge'sbuild.rswrites. Only its ABI differs from master's.sharp/baseline/spec/because they pass. Six are generics: §7method-declarations, §11generic-statics,inferred-type-argumentsandself-on-type-parameters, and §25class-valuesandclass-value-equality. The other 18 passed because the branch carries mago-sharp master up to164ef442d, which php-sharp'ssharp/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 compilerefused five of master's engine fixtures, which still used the collection methods and keywords from before mago-sharp164ef442d. The self-test'srefusalexample also failed, because #173's braces rule refusesif (true) return;as a real error. #114 fixes both, and66c6b8d44emerges it, masterb8907a9c1e. That also bringssharp/mago/to mago-sharp3cc39cc8c, 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.his regenerated from the mergedsharp.stub.php, which holds master'sinsert,removeAt,putandclearand this PR's\Sharp\Internalfunctions.index_read.inckeeps master's twocountcalls and this PR's threestandingcalls.enum_keys.phptand its two JIT twins keep this PR'sTypeError: 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.phptkeeps master's 16 op arrays forEnumKeysand this PR's check lines, with one for each of master'sgroupedandgroupNames.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 theparse_statementguard 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_innerwas 43,720 of them, because each arm unwrapped its node with?and wrapped it again.cb9e2842freturns each arm'sResultas it is:parse_statement_innertakes 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
7931eb3admerged Mago master164ef442d(#166, #170, #171, #173 and #176) and resolved 21 files, keeping both sides of each:.sharplexer keeps a keyword only in exact lowercase (feat: a constant's value is any expression built from constants #173), soList,ClassandFunctionlex as names. The slice's keyword arms for them are deleted, and a name followed by<or(starts a generic or function hint.is_map_key, inside master's fix: a PHP form PHP# never has is refused for good, with what PHP# writes instead #166 paths forgroupByandassociateBy.onclause and the slice's type parameters together tookMethodpast clippy'slarge_enum_variantlimit inClassLikeMember. A method's type parameters now live in the arena, as a local's hint does.On the engine side,
1a0320ac17brought R3 to R5 over round 2's call checks. R3 removedZEND_SHARP_VERIFY_SET_HOOK, since every property now checks on PHP's typed property path, soZEND_SHARP_VERIFY_TYPE_ARGSchecks only a plain PHP call's result.1fa9c8ccb3merged masterb1fa0fdb0d(#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:sharp-bridgeerase, three armscheck_slicejoins only classes with&and refuses every other type.Types::type_argumentsnew.Types::member_declaration__get.Types::atomic_text, three armsstatic_type_text$and#in a static's type text.GenericClass::analyzeTypeOf::analyzeresolve_static_propertiestrystatement, a genericcatchfind_template_usesfind_method_positionsfind_atomic_template_positions, two armsexplain_blocked_substitutionMutants
The mutants job at mago-sharp
6b923c21dleft 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-sharp0a3ba8119's body and in #152's review round 2 comment.Verification
At
ea2ea81e9b, the merge of #124, with the engine built here andmagobuilt fromsharp/mago/bysharp/bin/test's owncargo build: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-test17 of 17.At mago-sharp
cb9e2842f, before the move:At
cf3e3c4256, CI'sbuild-and-test (ubuntu-latest, nightly), the job that overflowed, passed in 11m23s. CI runs every mode, the census and Mago's full suites.Files