Skip to content

feat: Self members, named constructors through a type parameter, generic events and intersections - #177

Merged
heyJordanParker merged 6 commits into
masterfrom
feat/generics-complete
Oct 19, 2026
Merged

heyJordanParker merged 6 commits into
masterfrom
feat/generics-complete

Conversation

@heyJordanParker

@heyJordanParker heyJordanParker commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Problem

Three forms Jordan ruled on 10-18 (proposals 6, 8 and 9, each option A) were refused as "not supported yet":

  • Self.TABLE and Self.count += 1, and new TItem.fromJson(json) through a type parameter.
  • A generic event, public event Saved<T : DatabaseEntity>(T entity) : EntityEvent;, and a listener on Saved<Order>.
  • An intersection type, Shippable & Billable, as a property, a parameter, a return type, a local and a pattern.

Solution

Self and type-parameter static access (sections 9.1, 11, 25)

Precedent: Swift's Self.name, and Swift's required init, which every subclass declares so T(json:) can call it.

public class Store
{
    public const string TABLE = "items";
    public const string LABEL = Self.TABLE;   // compile error: a constant reads no class a call picks
    public static string table() => Self.TABLE;   // OrderStore.table() gives OrderStore's TABLE
}

public class Record
{
    public required Record.fromJson(Map<string, string> json) : this() { … }
    public Record.blank() : this() { }
}
public class Repository<TItem : Record>
{
    public TItem load(Map<string, string> json) => new TItem.fromJson(json);   // the type argument's fromJson
    public TItem empty() => new TItem.blank();                                 // compile error: Record.blank is not required
}
public class Refund : Entry { … }   // compile error: Refund must declare the named constructor fromJson, which Entry requires
  • Self.name reads and writes a constant or a static member of the class the call ran on, and plain PHP that calls the method on a subclass gets the subclass's value. In a generic class, Self.count is the static of the type arguments the code runs with.
  • A named constructor takes required. A class with objects of its own that inherits one without declaring its own is a compile error.

Generic events (section 15)

Precedent: C#'s EventHandler<TEventArgs>, and C#'s CS0305 for a generic type named without its type arguments.

public event Saved<T : DatabaseEntity>(T entity) : EntityEvent;
emit new Saved<Order>(this);
public void deliver(Saved<Order> e) on Saved<Order> { … }   // hears a Saved<Order> only
public void record(EntityEvent e) on EntityEvent { … }      // hears every Saved<…>
public void any(Saved<Order> e) on Saved { … }              // compile error: `Saved` needs its type argument
  • Events.on<Saved<Order>>, plain PHP's emit and a PSR-14 provider hear the same events as the on clause.
  • The listener table writes a generic event as its type text, as 'App.Saved<App.Order>'. The engine tests an emitted event against that type with its type arguments, and keeps the rows for the request per class and per type arguments.

Intersection types (sections 21, 24)

Precedent: TypeScript's intersections and Swift's protocol compositions, with Swift's (A & B)? for one that holds null.

public (Shippable & Billable)? last { get; set; } = null;
public int cost(Shippable & Billable item) => item.weight() * item.amount();
public int count(int & string amount) => 0;            // compile error: `&` joins classes and interfaces only, and `int` is neither.
public void hold(Shippable & Billable? item) { }       // compile error: write (Shippable & Billable)?
Shippable & Billable held = new Parcel();               // a typed local
shared is Order & Shareable both ? both.total : 0;      // tests every type
  • Plain PHP that passes a value of only some of the types gets a TypeError, on a parameter and on a property.

Removed

  • Every "not supported yet" arm for these forms, with its tests: the checker's Self member and intersection arms, its named-constructor-through-a-type-parameter arm, the analyzer's is_refused arm, and the parser's generic-event refusal.
  • ParseError::NotSupportedYetInSharp, which nothing raises once the generic-event refusal goes.
  • git grep -n "not supported yet" lists none of the three forms. What is left is a static constructor, an interface property such as { get; init; }, and the messages that sharp/bin/spec and its docs quote.

Public API

  • mago_sharp_bridge::type_text is now exported, so the orchestrator writes a generic event in the listener table in the same type text the bridge writes everywhere else.

  • Listener.events in mago-orchestrator is now Vec<String>, because a listed type with type arguments is a type text, not a single class name.

  • ClassLikeMetadata.type_parameter_named_constructors in mago-codex is new: the scanner records each new T.name(…) a class's code calls through a type parameter, so a type argument that is a plain PHP class is refused where it is written.

The review of #177

Each row was first seen failing with this PR's previous head, 678713a69b.

  • Self.KEY on a private member is a compile error that names Vault.KEY, as Swift's Self reaches only what every subclass has.
  • Self.TABLE and Self.name() as a parameter default run at the call, on the class the call ran on, as C# and Kotlin evaluate a default at the call.
  • Self.TABLE in a pattern tests the value of the class the code is called on, as Store.TABLE does Store's.
  • A static method's value keeps its class's type arguments: Counter<int>.bump and Self.bump. Master has the same defect: Function<bool(Any)> g = Counter<int>.holds; g("a") gives true with master's mago.
  • required passes down, as Swift's required init: a bound below the class that requires fromJson, an abstract one included, accepts new TItem.fromJson(…), and an abstract class may declare a required named constructor.
  • new Self.fromJson(…) compiles when fromJson is required and builds the class the call ran on.
  • A plain PHP class as the type argument of a type parameter the code calls a named constructor through is a compile error that names the class and the constructor.
  • & joins at most one class, as in Swift and Java. A type written twice in one & is a compile error, as in a union.
  • & binds tighter than |, as in TypeScript: Shippable & Billable | Order is a PHP DNF type, and the parentheses change nothing.
  • on Saved<T> with a type parameter is a compile error that says to name the type or listen on the interface. A bare on Saved reports only the missing type argument.

Verification

Each row was first seen failing on master, with master's mago built from 5c2ddae8bb:

  • The four new engine fixtures: GenericEvents/Saved.sharp gave "A generic event is not supported yet in PHP#.", NamedThroughType/Repository.sharp gave "A named constructor through a type parameter … is not supported yet in PHP#.", SelfMembers/Store.sharp gave "This expression is not supported yet in PHP#.", and Intersections/Desk.sharp gave a parse error.
  • The six new spec examples (type-parameter-named-constructors, required-named-constructors, generic-events, intersection-tests, intersection-types and self-members): "Checked 246 examples, ignored 1, and 6 fail."

On this branch, after merging master with #178:

  • sharp/bin/spec: "Checked 257 examples, ignored 1, and 0 fail." sharp/bin/spec --self-test: "24 of 24 self-test examples give the problems they expect."
  • sharp/bin/test --opcache --repeat --passes on generic_events, self_members, named_through_type, intersections, each with its _preload twin, and type_arguments_call_statics and type_arguments_call_inline: all pass in every mode, the 16 optimizer passes alone and both JITs included.
  • Zend/tests/sharp without opcache, with the file cache primed and used, and with shared memory twice in one process: 406 passed in each, one skipped in the repeat mode.
  • cargo test: mago-semantics --test sharp 438, mago-syntax --test sharp 243, mago-analyzer --test sharp 1063, mago-sharp-bridge --test lower 467, and mago --test compile 98.
  • cargo clippy --workspace --all-targets -- -D warnings and cargo fmt --all -- --check: clean.
  • cargo llvm-cov over the three measured packages, with CI's unreachable filter: no added line in their src goes unrun.

…ric events and intersections

Problem

Three forms Jordan ruled on 10-18 were refused as "not supported yet":

- `Self.TABLE` and `Self.count += 1` (proposal 6), and
  `new TItem.fromJson(json)` through a type parameter.
- A generic event, `public event Saved<T : DatabaseEntity>(T entity)
  : EntityEvent;`, and a listener `on Saved<Order>` (proposal 8).
- An intersection, `Shippable & Billable`, as a property, parameter,
  return type, local or pattern (proposal 9).

Solution

Self and type-parameter static access, spec sections 9.1, 11 and 25.
Precedent: Swift's `Self.name` and `required init`, which every
subclass declares so `T(json:)` can call it.

- `Self.name` reads and writes a constant or a static member of the
  class the call ran on. In a generic class it reads the statics of the
  type arguments the code runs with. A constant's value can't read it.
- A named constructor takes `required`. `new TItem.fromJson(…)` calls
  it on the type argument. A non-`required` one through a type
  parameter is a compile error that names it, and a class with objects
  of its own that leaves out a `required` named constructor is a
  compile error.

Generic events, spec section 15. Precedent: C#'s
`EventHandler<TEventArgs>`, and C#'s CS0305 for a generic type named
without its type arguments.

- An event declares type parameters as a class does, and `emit new
  Saved<Order>(this)` raises a `Saved<Order>`.
- `on Saved<Order>` hears only a `Saved<Order>`. `Events.on<…>`, plain
  PHP's emit and a PSR-14 provider hear the same. A bare `on Saved` is
  "`Saved` needs its type argument.", and a listener on an interface
  the event implements hears every `Saved<…>`.
- The listener table writes a generic event as its type text, as
  `App.Saved<App.Order>`, and the engine tests an emitted event against
  it with its type arguments, keeping the rows per class and per type
  arguments for the request.

Intersection types, spec sections 21 and 24. Precedent: TypeScript's
intersections and Swift's protocol compositions, with Swift's
`(A & B)?` for one that holds null.

- `&` joins classes and interfaces wherever a type goes. `int & string`
  is "`&` joins classes and interfaces only, and `int` is neither."
- `Shippable & Billable item = parcel;` is a typed local, and
  `x is Order & Shareable` tests every type.
- Plain PHP that passes a value of only some of the types gets a
  TypeError, on a parameter and on a property.

Every "not supported yet" arm for these forms is gone with its tests,
as is the unused `ParseError::NotSupportedYetInSharp`. Six new spec
examples run under sharp/bin/spec. Each failed on master's mago and
passes now. Four engine tests and their preloaded twins pass with no
opcache, the file cache, shared memory, each optimizer pass and both
JITs.

php-sharp/
├── docs/spec.md                                        sections 9.1, 11, 15, 21, 24, 25
├── ext/sharp/sharp.c                                   sharp_hears, sharp_listeners_of
├── Zend/tests/sharp/
│   ├── GenericEvents/, generic_events{,_preload}.*     emit, Events.on, plain PHP, PSR-14
│   ├── Intersections/, intersections{,_preload}.*      parameter, property, pattern, local
│   ├── NamedThroughType/, named_through_type{,_preload}.*
│   └── SelfMembers/, self_members{,_preload}.*         subclass constants, generic statics
└── sharp/mago/
    ├── crates/syntax/          generic events, `on Saved<Order>`, `&` typed locals
    ├── crates/names/           an on clause resolves as a type
    ├── crates/codex/           `required` named constructors, listed types as types
    ├── crates/semantics/       the refusals go, and `required` on a named constructor
    ├── crates/analyzer/        Self members, required named constructors, listed events
    ├── crates/sharp-bridge/    Self statics, `new TItem.name`, type_text exported
    ├── crates/orchestrator/    the listener table's type texts
    └── tests/compile.rs        a generic event's listener row
…s rulings

#174 lets an interface hold constants and operators and an enum declare
operators, so is_undecided keeps only an interface property in another
form than `{ get; }`, `{ get; set; }` and `=> expr;`. A member of `Self`
and an intersection type stay supported, as this branch builds them.

- The refusal-notes test refuses `{ get; init; }` in an interface, as
  master does, and `extra is int & Report` in a pattern.
- The lowering test of a refused construct and the spec self-test's
  refusal example use `int max { get; init; }` in an interface, the one
  form still not supported yet. The self-test's old example,
  `Order & Line`, now compiles.
Problem

The patch-coverage job found seven lines no test ran: a listed event
whose named class the codebase lacks, PHP's own intersection rule in a
plain PHP file, an intersection of three types, parentheses around one
member, a refused intersection in a method body, and the note of a
refusal inside an event.

Solution

- check_listed_events reads the listed class through listed_class, so
  the arm for a named object with no class, which no `on` clause
  reaches, is gone. An undeclared name stays a reference and keeps
  "Cannot find type".
- No form reaches the note of a refusal inside an event: `enter` places
  every part of an event, and its parameters take a parameter's note.
  It is unreachable!, as a struct's is.
- The intersection test adds `Lib & Other & Third`, a local
  `int & Lib`, a member in parentheses, and a plain PHP
  `int&string`, which keeps PHP's own error.

sharp/mago/crates/
├── analyzer/src/statement/class_like/listener.rs   listed_class
├── semantics/src/internal/checker/sharp.rs        the event note
└── semantics/tests/sharp.rs                       the intersection rows
Self members (spec section 25)
- `Self.KEY` on a private constant or static is a compile error that
  names `Vault.KEY`: a subclass has no private member of its parent, and
  Swift's `Self.name` reaches only what every subclass has.
- `Self.TABLE` and `Self.name()` as a parameter default run where the
  call left the argument out, on the class the call ran on, as C# and
  Kotlin evaluate a default at the call. The default lowers to the
  static closure a default that calls a method lowers to, and the engine
  binds it to the called class.
- `Self.TABLE` in a pattern is the value of the class the code is called
  on, as `Store.TABLE` is `Store`'s.
- A static method's value keeps its class's type arguments, so
  `Counter<int>.bump` and `Self.bump` run `bump` with them, as a call
  does. Master has the same defect for `Counter<int>.holds`.

Named constructors through a type parameter (spec sections 9.1 and 11)
- `required` passes down, as Swift's `required init` does: a bound below
  the class that requires `fromJson`, an abstract one included, accepts
  `new TItem.fromJson(…)`, and an abstract class may declare a `required`
  named constructor.
- `new Self.fromJson(…)` compiles when `fromJson` is `required`, and
  builds the class the call ran on.
- A plain PHP class as the type argument of a type parameter the code
  calls a named constructor through is a compile error that names the
  class and the constructor.

Intersections (spec section 24)
- `&` joins at most one class with any number of interfaces, as in Swift
  and Java.
- A type written twice in one `&` is a compile error, as in a union.
- `&` binds tighter than `|`, as in TypeScript, so `A & B | C` is the
  union of the intersection and `C`, and the parentheses change nothing.

Generic events (spec section 15)
- `on Saved<T>` with a type parameter is a compile error that says to
  name the type or listen on the interface, as C#'s handler names its
  event's type.
- A bare `on Saved` reports only the missing type argument.
…eside the review fixes

The one conflict is the note that lists what a method body takes: it
keeps #178's loop names and this branch's `new Self.name(...)` and
`new TItem.name(...)` with a `required` named constructor, and `Self.name`.
The lowering test of a static method's value now also takes
`Counter<int>.bump` through a class written with its type arguments,
which keeps `int` on `Counter::class`, and `Self.one` in a class that
isn't generic, which stays PHP's first-class callable. The record of a
value's class type arguments drops its dialect check: a plain PHP class
reaches neither read, and a class that isn't a generic PHP# one records
none.
@heyJordanParker
heyJordanParker merged commit 12be272 into master Oct 19, 2026
26 checks passed
@heyJordanParker
heyJordanParker deleted the feat/generics-complete branch November 3, 2026 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant