Skip to content

feat: give PHP# classes a hierarchy, class members and typeof - #34

Merged
heyJordanParker merged 11 commits into
masterfrom
feat/slice-classes
Oct 7, 2026
Merged

heyJordanParker merged 11 commits into
masterfrom
feat/slice-classes

Conversation

@heyJordanParker

Copy link
Copy Markdown
Owner

The engine half of the PHP# classes slice, whose checker half shipped in mago-sharp 0.1.0.

Run PHP# classes:

  • a class header : Base, IFace, interfaces, abstract and final, virtual and override, and super
  • class constants and static members, and Class.y reads resolved when they run
  • typeof(X)
  • the classes marks (ZEND_FETCH_CLASS_MEMBER_SYNTAX, ZEND_FETCH_CLASS_MEMBER, ZEND_ACC_PARENT_IN_INTERFACES) in the PHP# marks register, each with its static assert

The checker now checks every classes fixture: the libraries moved into harness/, Demo\Page renamed, and a valid Members.sharp. The differential compiles Header, Members, Page and Site.

Proof on macOS: sharp/bin/test --opcache --repeat --passes --census --differential exits 0, 81 of 81 in every mode, empty census.

A .sharp file could not run a class constant, a static member, a
`Class.name` read, `typeof(X)`, or an abstract, final or interface
declaration. PHP# decides when it runs whether `Class.name` is a
constant or a static property, so the engine now reads the static
property when the class has no constant by that name.

Read Class.name as a constant, an enum case or a static property:
- The bridge marks the read's class constant fetch with
  ZEND_FETCH_CLASS_MEMBER, below the fetch's cache slot
- The compiler, compact_literals and the optimizer keep the mark, and
  the VM handler, which the JIT also calls, reads the static property
  when the class has no constant by that name, and never caches it
- A read of neither throws "Undefined constant or static property"

Run constants, statics, typeof and class kinds:
- Class constants, static members and their writes, `typeof(X)`,
  abstract and final classes and interfaces run as their PHP twins

Zend/
├── zend_compile.h*                      <- the ZEND_FETCH_CLASS_MEMBER mark
├── zend_compile.c*                      <- carries the mark into the fetch
├── zend_vm_def.h*                       <- falls back to the static property
├── zend_vm_execute.h*                   <- regenerated from zend_vm_def.h
├── Optimizer/compact_literals.c*        <- keeps the mark when it moves the cache slot
├── Optimizer/zend_optimizer.c*          <- keeps the mark when it gives the fetch a cache slot
└── tests/sharp/
    ├── Kinds.sharp*                     <- added, the classes typeof names
    ├── typeof.phpt*                     <- added, typeof(X) is X::class
    ├── Members.sharp*                   <- added, declares, writes and reads constants and statics
    ├── static_members.phpt*             <- added, constants and statics are PHP's
    ├── class_members.inc*               <- added, reads constants, an enum case and statics
    ├── class_members.phpt*              <- added, Class.y reads without and with opcache
    ├── class_members_jit_tracing.phpt*  <- added, the same reads under the tracing JIT
    ├── Shapes.sharp*                    <- added, abstract, final and interface declarations
    ├── Shapes.inc*                      <- added, the PHP twin of Shapes.sharp
    ├── class_kinds.phpt*                <- added, PHP code extends and implements them
    └── opcodes.phpt*                    <- compares Shapes with its twin
ext/sharp/
└── sharp.c*                             <- maps the new kinds to their zend_ast kinds
# Conflicts:
#	Zend/tests/sharp/opcodes.phpt
#	ext/sharp/sharp.c
A .sharp constant's value, a static property's initial value and a
parameter default now read `Class.name`, which the engine evaluates as
the class constant or enum case. The tests run them in all three opcache
modes and under the tracing JIT.

Zend/tests/sharp/
├── Registry.inc*                        <- added, the PHP enum and class the members read, shared by two tests
├── Members.sharp*                       <- a constant value, an initial value and a default read Class.name
├── class_members.inc*                   <- loads Registry.inc and dumps the three reads
├── class_members.phpt*                  <- expects them
├── class_members_jit_tracing.phpt*      <- expects them under the tracing JIT
└── static_members.phpt*                 <- loads Registry.inc, which Members.sharp's constants read
A .sharp class header, `class Page : Entity, Linkable`, names its base
class among its interfaces, and only link time knows which name is the
class. PHP# classes also need `parent` for `super`, and checked
arithmetic skipped static properties.

Link a PHP# class hierarchy:
- A class marked ZEND_ACC_PARENT_IN_INTERFACES (bit 31) finds the one
  class among its interface names when it links, and takes it as the
  parent, through autoloading, the inheritance cache, the file cache and
  preloading
- Two classes, or a name that is neither a class nor an interface, fail
  with an error naming both
- `parent` compiles in a marked class, so `super.m()` calls the parent
- `override` lowers to `#[\Override]`, which PHP checks at link time

Throw on overflow in static properties:
- `++`, `--` and `+=` on a static property in a .sharp file throw
  ArithmeticError, with and without the tracing JIT

Prove PHP# compiles to its PHP twin:
- opcodes.phpt checks the Members and Site fixtures against their twins,
  and pins each difference PHP# makes on purpose

Zend/
├── zend_compile.h                  <- ZEND_ACC_PARENT_IN_INTERFACES, the last free class flag
├── zend_inheritance.c              <- finds the parent among the interface names at link time
├── zend_compile.c                  <- `parent` in a marked class; static ++/-- carry the overflow mark
├── zend_vm_def.h                   <- static ++/-- read the cache slot without the mark
├── zend_vm_execute.h               <- regenerated from zend_vm_def.h
├── Optimizer/compact_literals.c    <- keeps the mark when it moves static property cache slots
└── tests/sharp/
    ├── Header.sharp, Header.inc    <- added, a header, `virtual`, `override` and `super`
    ├── Header*.sharp               <- added, a header with two classes, a trait, a missing name, a stray override
    ├── class_header*.phpt          <- added, linking, autoloading, both caches, preloading and errors
    ├── Site.sharp, SiteLib.inc     <- added, the goal class and the PHP library it links to
    ├── Site.inc, Members.inc       <- added, the PHP twins of Site.sharp and Members.sharp
    ├── site.phpt                   <- added, runs the goal class
    ├── opcodes.phpt                <- compares Members and Site with their twins
    ├── Shapes.sharp                <- writes `public interface`
    ├── Tally.sharp                 <- added, static counters
    └── overflow_static_property*   <- added, static overflow with and without the JIT
ext/sharp/sharp.c                   <- maps SHARP_AST_NAME_LIST
# Conflicts:
#	Zend/tests/sharp/opcodes.phpt
#	ext/sharp/sharp.c
…ass in an attribute

The Architect ruled that a PHP# class replaces a plain PHP parent's method
under PHP's own rule, with `override` required, and that `typeof(X)` may
name a class in an attribute argument. Nothing ran either case end to end.

The Site fixture now covers both:
- `Site\Page` implements `Lib\Entity`'s abstract protected `render()` and
  replaces its `id()`, which has a body, calling it through `super`
- `[Access(typeof(Page))]` on `Site\Page` reads back through reflection as
  the class-name string
- The PHP twin compiles to the same opcodes for the new methods and the
  attribute, so the pinned differences only move down by 12 lines

Zend/tests/sharp/
├── Site.sharp    <- Page replaces Entity's methods and carries Access(typeof(Page))
├── Site.inc      <- the PHP twin, with #[\Override] and Page::class
├── SiteLib.inc   <- Entity gains abstract render() and show(), and the Access attribute
├── site.phpt     <- runs the replaced methods and reads the attribute
└── opcodes.phpt  <- Site's pinned lines after the new methods
…s under the JIT

The runtime reviewer found that the tracing JIT read a reference held in a
static property array as the reference itself. The optimizer typed a marked
class constant fetch as a constant, whose arrays never hold references, so
`item === 1` over such an array counted 0 under the tracing JIT and 1 in the
VM. A `Class.y` static property read also cached nothing, so a hot loop ran
about twice the instructions of its PHP twin. The linking reviewer found a
latent crash for a `parent` type in a header class, and test gaps.

Read Class.y as PHP reads a static property:
- The optimizer types a marked fetch without a known constant as an array
  that may hold references, so the JIT dereferences each element
- A marked fetch caches the class, the property's address and its info in 3
  slots, as FETCH_STATIC_PROP_R does, under its own cache-key kind; a loop of
  10 million reads went from 11.69 to 6.60 billion instructions, against
  6.18 for the PHP twin on the same debug build
- The bridge marks the read with ZEND_FETCH_CLASS_MEMBER_SYNTAX, `1 << 15`,
  above the fetch flags a constant expression passes in the same attr
- The optimizer keeps the overflow mark when it rebuilds a static property's
  or an object property's increment cache slots

Link a class header safely:
- A `parent` type resolves at run time until a header class links, as php-src
  does for traits and closures
- One helper throws "neither a class nor an interface"
- Tests cover a base class between two interfaces, a variance check while
  the class links, a final or enum parent, and preloading through
  opcache_compile_file

Zend/
├── zend_compile.h                  <- ZEND_FETCH_CLASS_MEMBER_SYNTAX at 1 << 15
├── zend_compile.c                  <- maps the mark, 3 cache slots; parent type waits for its name
├── zend_inheritance.c              <- zend_sharp_throw_not_inheritable
├── zend_vm_def.h                   <- caches and reads the static property as FETCH_STATIC_PROP_R does
├── zend_vm_execute.h               <- regenerated
├── Optimizer/
│   ├── compact_literals.c          <- LITERAL_CLASS_MEMBER with 3 slots
│   ├── zend_inference.c            <- a marked fetch may hold references
│   └── zend_optimizer.c            <- keeps ZEND_SHARP_OPERATOR on increments
└── tests/sharp/
    ├── Header.inc, Header.sharp    <- Card between two interfaces; Shelf, Sealed, Suit
    ├── HeaderFinal.sharp           <- added, a final parent
    ├── HeaderEnum.sharp            <- added, an enum parent
    ├── class_header.phpt           <- Card's parent, interfaces and copy()
    ├── class_header_final.phpt     <- added, final and enum parents as PHP reports them
    ├── class_header_inheritance_cache.phpt  <- Card through the inheritance cache
    ├── class_header_preload.phpt   <- Card through preload
    ├── class_header_preload_compile.inc     <- added, preloads with opcache_compile_file
    ├── class_header_preload_compile.phpt    <- added, links what opcache_compile_file compiled
    ├── Registry.inc, Members.sharp, Members.inc  <- items with a reference, late typed property
    ├── class_members.inc           <- counts ones over a referenced array, reads late
    ├── class_members.phpt          <- the VM's answer
    ├── class_members_jit_tracing.phpt       <- the tracing JIT's answer
    ├── class_members_jit_function.phpt      <- added, the function JIT's answer
    ├── overflow_static_property_jit_function.phpt  <- added, overflow under the function JIT
    └── opcodes.phpt                <- Members' two new reads
…eat/slice-classes

expressions-2 brings master's register of PHP# marks, the generated
sharp_kind, the (int) cast mark, the census and the per-pass differential,
and pins the bridge at mago-sharp 0.1.0 (6d6bdf2), which holds the classes
checker half. Every behaviour both branches added is kept.

Conflicts:

ext/sharp/sharp.c: classes added CLASS_NAME, CLASS_CONST_GROUP,
CLASS_CONST_DECL, STATIC_PROP and CLASS_CONST to the hand-written
sharp_zend_kind switch. expressions-2 replaced the switch with a cast and a
static assert per kind over the generated SHARP_KINDS list. The switch goes.
All five kinds are in kind.rs at 6d6bdf2, so SHARP_KINDS asserts each one
and the cast covers it. The file now equals expressions-2's.

Zend/tests/sharp/opcodes.phpt: classes gave each fixture the PHP library its
classes link against and printed every differing line. expressions-2 added
the opcache dump before the optimizer, because phpdbg prints no property
hook, and counted op arrays by "; (before optimizer)". The merged test:
- runs all eleven fixtures, Checkout and Page included, with classes'
  library prelude and line diff.
- takes the dump with php -l, which compiles without running. Run as a
  script, Site fails to link without its library, and the .sharp and .php
  runs fail with different messages.
- counts each op array name either listing prints once. phpdbg prints
  abstract and interface methods, the dump prints property hooks, so every
  count both branches expect still holds (Shapes 5, Site 13, Checkout 11,
  Page 10).
- expects the dump's copy of each difference classes pins: six .sharp and
  six .php lines for Members, four and three for Site. Every line either
  branch expected is kept.

Resolved without a textual conflict:

Zend/zend_compile.h: the register of PHP# marks now lists the four marks
classes adds, each with a static assert per field and kind:
- ZEND_SHARP_OPERATOR in the extended_value of the ZEND_*_INC_STATIC_PROP
  and ZEND_*_DEC_STATIC_PROP opcodes, asserted against ZEND_FETCH_OBJ_FLAGS.
- ZEND_FETCH_CLASS_MEMBER_SYNTAX in the attr of ZEND_AST_CLASS_CONST,
  asserted against every ZEND_FETCH_CLASS_* flag.
- ZEND_FETCH_CLASS_MEMBER in the extended_value of
  ZEND_FETCH_CLASS_CONSTANT, asserted below the cache slot.
- ZEND_ACC_PARENT_IN_INTERFACES in ce_flags, asserted against every class
  flag.
The two ZEND_FETCH_CLASS_MEMBER defines move from their own comment into
the register, beside the ZEND_SHARP_OPERATOR defines. The class flag stays in
the ZEND_ACC_* table.

Zend/Optimizer/compact_literals.c: the census flagged the two writes of
FETCH_CLASS_CONSTANT's extended_value, which kept the mark through a local.
They now name ZEND_FETCH_CLASS_MEMBER, as the static property writes beside
them name their marks. Same behaviour.

Zend/Optimizer/zend_optimizer.c and zend_inference.c: both branches made the
same ZEND_SHARP_OPERATOR changes to zend_optimizer_update_op1_const and
update_op2_const. One copy is kept, beside classes' ZEND_FETCH_CLASS_MEMBER
mask and expressions-2's cast mask.

Zend/zend_vm_def.h: classes' Class.y handler and static property masks and
expressions-2's (int) cast and overflow result sit in different handlers.
Zend/zend_vm_execute.h regenerated with Zend/zend_vm_gen.php equals the
merged file.
Problem: the checker-against-engine differential loads every .sharp
fixture plus the plain-PHP helpers in Zend/tests/sharp/harness/ into one
workspace. After expressions-2 merged into classes, it refused fixtures
for reasons unrelated to the program each one runs:
- Header.sharp and Page.sharp both declared Demo\Page, so the checker
  refused Page.sharp as a duplicate definition.
- Header.inc, Registry.inc and SiteLib.inc sat outside harness/, so the
  checker could not see the PHP classes Header.sharp, Members.sharp and
  Site.sharp link against.
- Header.inc, SiteLib.inc and harness/Attributes.inc each declared
  Lib\Entity, and SiteLib.inc and Registry.inc each declared Lib\Registry.
- Members.sharp wrote `??=` on a static property typed string, which can
  never be null.

Solution: the three libraries move into harness/, as Box.inc did. Each
colliding name gets its own class: Header.sharp's Demo\Page becomes
Demo\Article, Header.inc's Lib\Entity becomes Lib\Record, SiteLib.inc's
Lib\Entity becomes Lib\Resource, and SiteLib.inc's Lib\Registry becomes
Lib\Catalog. Members' last becomes string?, so `??=` checks a value that
can be null. Every require, expected line and pinned opcode follows the
new names and paths. Header.sharp, Site.sharp and Page.sharp now pass the
checker. Members.sharp is refused only for missing() and hidden(), the
two reads class_members.phpt runs to see the engine's errors.

Zend/tests/sharp/
├── harness/
│   ├── Header.inc            moved, Lib\Entity -> Lib\Record
│   ├── Registry.inc          moved
│   └── SiteLib.inc           moved, Lib\Entity -> Lib\Resource,
│                             Lib\Registry -> Lib\Catalog
├── Header.sharp              Demo\Page -> Demo\Article
├── HeaderTwoClasses.sharp    Lib\Entity -> Lib\Record
├── Members.sharp, Members.inc   last is string?
├── Site.sharp, Site.inc      Lib\Resource, Lib\Catalog
├── class_header*.phpt, class_header_preload*.inc   new path and names
├── class_members.inc, static_members.phpt, site.phpt   new paths
└── opcodes.phpt              new library paths, lib\resource
Problem: Members.sharp held two reads that exist to make the engine
throw: missing() reads a static property Lib\Registry does not declare,
and hidden() reads a protected one. The checker refuses both, so it
refused all of Members.sharp, and the checker-against-engine
differential never compared the rest of the fixture with php -l.

Solution: the two reads move into their own error fixture,
MembersErrors.sharp, with its twin, as the Header* error fixtures hold
one fault each. The checker now accepts Members.sharp and refuses
MembersErrors.sharp only on those two reads. class_members.inc calls
missing() and hidden() on Demo\Misread and late() on Demo\Members, so
the three class_members tests still see the same three engine errors.
opcodes.phpt compares MembersErrors with its twin and pins its two
Class.y reads, and the Members lines move up with the removed methods.

Zend/tests/sharp/
├── Members.sharp, Members.inc            missing() and hidden() removed
├── MembersErrors.sharp, MembersErrors.inc   added: Demo\Misread
├── class_members.inc                     calls the reads on Misread
└── opcodes.phpt                          MembersErrors block, Members lines
@heyJordanParker
heyJordanParker merged commit a71ab1f into master Oct 7, 2026
6 checks passed
heyJordanParker added a commit that referenced this pull request Oct 13, 2026
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
@heyJordanParker
heyJordanParker deleted the feat/slice-classes 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