Skip to content

feat: events run, Events.on listens for a while, and PSR-14 dispatchers reach PHP# listeners (spec section 15) - #127

Merged
heyJordanParker merged 23 commits into
masterfrom
feat/events-engine
Oct 14, 2026
Merged

heyJordanParker merged 23 commits into
masterfrom
feat/events-engine

Conversation

@heyJordanParker

@heyJordanParker heyJordanParker commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

PHP# events now run: emit reaches every listener through the app's dispatcher, Events.on<T> listens for as long as its handle lives, and a plain PHP library's PSR-14 dispatcher reaches PHP# listeners (spec section 15). The checker and the bridge already did section 15, and the engine did none of it. docs/architecture/slices/15-events.md is the design note, with every decision and ruling.

Completes: §15

emit runs every listener through the app's dispatcher

  • emit hands the event and one function per listener to the app's Sharp.Dispatcher, whoever emits: an app class, a PHP# package in vendor/, or plain PHP. The spec says "An app replaces the dispatcher once at startup", so one binding serves the whole app.
    • Exactly one app module binds it: of the base and environment modules outside vendor/ that bind it, the one whose namespace has the fewest parts. A binding in any other app module is a compile error, "Only app/Module.sharp binds Dispatcher: an app binds it once, in its top module.", and two top modules of the same depth are each an error. Spec section 15 states the rule with the example one-dispatcher.
    • mago compile names that module in .sharp/listeners.php, as 'dispatcher' => ['app/Module.sharp', 'app'].
    • A running test's module binding replaces it, whatever namespace the test module names. With no app binding, the standard library's ImmediateDispatcher runs the listeners before emit returns.
  • Dispatcher.dispatch(Any emitted, List<Function<void(Any)>> listeners) calls each listener(emitted). emit and PSR-14 hand out the same closures.
  • Each function creates its listener's object through the container when it runs, with its namespace's services, so every event gets a new object whatever lifetime a module gives the class.
  • An implementation of Dispatcher.dispatch may reach any effect, because the listeners it runs may. dispatch declares uses Events, so calling it has the effect emit has.
  • mago compile writes .sharp/listeners.php in every PHP# project, with its inputs: every PHP# file, and the listing of its folder and each folder above it. A listing names a folder's .sharp files and its namespace folders, those whose name starts with an uppercase letter.
    • A missing table means no listeners. A damaged one throws ".sharp/listeners.php is damaged. Run vendor/bin/mago compile." A row naming a class or method the code lacks throws ".sharp/listeners.php is out of date: it lists App.Demo.Gone, which no longer exists. Run vendor/bin/mago compile."
    • With sharp.compile_command set, the table is read past opcache, and a table whose inputs changed runs the command once. So a listener in a new folder, or an on added to a class nothing loads, runs at the next emit.
  • The container runs a module file in a symbol table of its own, which fixed a tracing-JIT leak.

Events.on<T> listens until its handle goes

  • sharp/composer/library/Sharp/Events.sharp declares extern Internal.listen uses Events; and Events.on<TEvent>, whose body calls Internal.listen(typeof(TEvent), listener). So on has the effect Events by inference, as every plain PHP function's effect is declared. Events stays the one standard effect with no foreign class.
  • The engine's Sharp\Listening handle stops the listener in its destructor: when its function returns, and when an exception leaves it, in every opcache and JIT mode.
    • The handle owns the listener's function and reports it to the cycle collector, and the engine's list of scoped listeners holds no reference. So a handle kept in a property of the object its listener uses is collected with that object, and the listener stops.
  • Events.on<T> refuses a T that is not an event or an interface an event implements, with the on clause's messages. Events.on(e => { }) gives only missing-template-parameter.
  • Only the standard library imports Sharp.Internal, with the new code internal-outside-library, so PHP# code listens with Events.on and raises events with emit.
  • Only the standard library declares code in namespace Sharp or a namespace under it. A project file there is refused with reserved-name-outside-library: "Sharp.Mine is a namespace of the standard library, and only the standard library declares code in it." This replaces the refusal of a project class named Sharp.Int, Sharp.Float or Sharp.Bool.
  • Events.on carries [NoDiscard]. The unused-result check now reads a PHP# Class.m() call as it reads PHP's Class::m(), and in a .sharp file it speaks PHP#: "The value Events.on returns must be used.", with "[NoDiscard] on Events.on says the value it returns matters."

A plain PHP library's events reach PHP# listeners through PSR-14

  • Sharp\Psr\ListenerProvider, beside Sharp\Psr\Container, implements PSR-14's ListenerProviderInterface over the engine's new Sharp\Internal\listenersFor. It returns the closures emit would hand the app's dispatcher.
  • A PHP# app binds a library's PSR-14 dispatcher with new ListenerProvider(), as the new spec example psr-listeners shows. No adapter is built for any framework.
  • sharp/composer requires psr/event-dispatcher ^1.0, and sharp/phpunit/composer.lock locks 1.0.0.
  • The checker's prelude declares Sharp\Internal\listenersFor, and sharp/composer/mago.toml analyzes src/Psr/ListenerProvider.php against the harness's PSR-14 interfaces.

Harness changes

  • sharp/harness/app/Stubs/Laravel.sharp: extern event JobFailed;, the text the example extern-event writes.
  • sharp/harness/app/Imports/RowImported.sharp: public event RowImported(int row);, the text the example standalone-event writes.
  • sharp/harness/Psr/EventDispatcher/EventDispatcherInterface.php and ListenerProviderInterface.php: psr/event-dispatcher 1.0's interfaces.
  • sharp/harness/Vendor/Events/EventDispatcher.php: a plain PHP dispatcher that follows PSR-14, for psr-listeners.
  • sharp/harness/Sharp/Psr/ListenerProvider.php: an exact copy of sharp/composer/src/Psr/ListenerProvider.php, because sharp/bin/spec copies only sharp/composer/library/ into an example's project. Without it psr-listeners fails with "Class ListenerProvider not found."

Known follow-up, as its own pull request after this one: write_project in sharp/bin/spec copies all of sharp/composer into an example's project, as a Composer install does, and the harness copy of ListenerProvider.php is deleted. sharp/bin/spec is guarded, so this pull request can't change it.

Spec examples

  • listeners and scoped-listener leave sharp/baseline/spec, and the folder §15 is gone. psr-listeners and one-dispatcher are new and pass. No example newly fails.
  • sharp/bin/spec --completes with this body gives "§15: all 10 checked examples pass."

Checks run locally

  • sharp/bin/test --spec: 261 of 261 engine tests, the spec self-test 17 of 17, and the examples match sharp/baseline/spec ("Checked 185 examples, ignored 1, and 64 fail").
  • sharp/bin/test --opcache --repeat --passes: 261 of 261 without opcache, with the opcache file cache priming and using it, twice in one process, and under optimizer passes 1 to 11 alone. The 13 events* and extension_inputs tests pass under all 16 passes and both JITs.
  • sharp/bin/test --phpunit --census --differential: PHPUnit OK in one process and with process isolation, the census clean, and every accepted file passes php -l.
  • In sharp/mago: the analyzer crate (395 unit, 2569 PHP cases, 812 PHP#), the root compile (78) and sharp (69) tests, the codex crate, and the sharp-bridge, orchestrator, server, database and prelude crates pass. cargo clippy --workspace --all-targets -- -D warnings and cargo fmt --check are clean.
  • Each new test was seen failing before its code, except two whose code feat: declare effects as foreign classes, and ship Environment as one #118 and feat: call plain PHP through its namespace, and refuse bare calls and statements that never run #124 built: the effect of Events.on, and code without a body that emits.
  • mago analyze of sharp/composer finds no issues, and sharp/bin/native and build/gen_stub.php -f --generate-optimizer-info --verify change no file.

heyJordanParker and others added 23 commits October 12, 2026 03:37
Problem: no part of spec section 15 compiles. An event declaration, a
nested interface, a dotted type, emit, an on clause and extern event are
parse errors on mago-sharp master, an event inside a class is misread as
an abstract method, and new Order.Paid(...) is read as a named
constructor. Section 15 holds 7 of the examples Guard 1 lists as failing,
and nothing says what each construct lowers to or what the engine adds.

Solution: a design note for v1 plan Slice 13, for team-lead to approve
before anyone builds. It records each rule's state from the built mago,
what it lowers to, the standard-library choices the spec leaves open with
their precedent, three spec syntax questions for Jordan, the spec-files
changes and errata the examples need, the PR order with its dependency on
generics and on section 32, the public names, and the tests.

docs/
└── architecture/
    └── slices/
        └── 15-events.md    new: the section 15 design note
Problem

Jordan ruled that nothing nests: every type, events and interfaces
included, is declared at file level in a namespace, in its own file.
The section 15 note still named a nested event `App\Order\Paid`,
autoloaded it through its outer class, resolved a bare name to the
nested type first, read a dotted type and `new X.Y`, and asked Jordan
three questions he has since answered.

Solution

The note opens with the ruling and names every PR whose scope shrinks
or changes: mago-sharp PR 1 (#162) and PR 3, php-sharp PR A and the
spec-files PR. Decisions 1 (nested-type naming) and 6 (autoload
through the outer class) go, and the rest take new numbers. Language
rule 6 is now the nested-type refusal, and rule 7 goes. The questions
become Jordan's rulings, `extern event … uses` gives the class its
effects, and `Effect::Emit` carries no payload. Every example names
`OrderPaid` and `OrderEvent`, and the states #162 now shows, on the
checker and on the engine, are quoted from a run.

docs/architecture/slices/
└── 15-events.md    the ruling, the PRs it reshapes, and file-level names throughout
Problem

The engine work for section 15 builds on master's spec guard
(`sharp/baseline/spec`), the rewritten spec examples and the static
collection fix, which feat/slice-events predates.

Solution

Merge master. No file conflicts.

Files

(no changes beyond master's)
Problem

Spec section 15 says `emit` raises an event and every listener for it
runs before `emit` returns. mago-sharp #170 compiles `emit e;` to
`\Sharp\Internal\emit($e);` and writes every `on` listener into
`.sharp/listeners.php`, but the engine has no `Sharp\Internal\emit`, so
an emitting method fails with "Call to undefined function".

Solution

The engine gains `Sharp\Internal\emit(object $event): void`. It finds
the `.sharp/` folder above the file that declares the event's class, as
the engine finds it for a source file, so an `extern event` in vendor/
finds its project's table. It reads the table once per request through
`zend_compile_file`, so opcache serves it, as the constant array the
file returns, without running it: code run from inside `emit` gives the
caller a symbol table a tracing-JIT frame never frees. For each event
class it keeps, for the request, the rows whose listed types the event
is an instance of, in table order. Each listener runs on a new object
of its class, created as `new` creates it, with the event when its
method takes one. An exception from a listener leaves `emit`, and the
listeners after it do not run. A missing or damaged table throws
CompileError ".sharp/listeners.php is missing or damaged. Run
vendor/bin/mago compile.".

The Mago pin moves to #170's head, so sharp/baseline/spec loses
standalone-event, extern-event, extern-event-effects and emit-forms,
and the §9.1 and §12 examples that Mago master already runs.

Files

ext/sharp/
├── sharp.stub.php     <- function Sharp\Internal\emit(object $event): void
├── sharp_arginfo.h    <- regenerated: its arginfo and ext_functions
├── sharp.c            <- emit, the table read, the per-request caches,
│                         ext_functions registered in MINIT
└── sharp_unit.h       <- SHARP_MAGO_COMMIT bb0566e, #170's head
Zend/tests/sharp/
├── OrderEvent.sharp, OrderPaid.sharp, OrderRefunded.sharp
│                      <- new: an interface and two events, one per file
├── OrderNotices.sharp, Receipts.sharp, Shipping.sharp
│                      <- new: the listeners, a private one, one without
│                         a parameter, one listed twice, one on the
│                         interface, one on an extern event, one that
│                         throws, one that emits
├── Register.sharp     <- new: raises both events with emit
├── harness/JobFailed.inc
│                      <- new: the plain PHP class the extern event marks
├── events.inc, events.phpt, events_jit_function.phpt,
│   events_jit_tracing.phpt
│                      <- new: every listener runs before emit returns,
│                         in table order, once; an exception stops the
│                         rest; a nested emit runs first; plain PHP's
│                         emit and an extern event; a TypeError; a
│                         read-only event property
└── events_table.phpt  <- new: a missing or damaged table, and a gone
                          listener class or method
sharp/baseline/spec    <- ten examples pass and leave the list
docs/architecture/slices/15-events.md
                       <- the table read, its refusals and the files
Problem

Spec section 15's checker and bridge landed with mago-sharp #162 and #170,
and php-sharp #121 checks each listener's services, but the engine has no
Sharp\Internal\emit. The first emit that runs throws "Call to undefined
function", and the listeners and scoped-listener examples still fail.

Solution

A design note for team-lead to approve before anyone builds. It states
every line of section 15 with its state on master, observed with a release
mago and the engine built from 76d220c. It reuses feat/slice-events'
table read and fixtures, creates each listener's object through #121's
container, makes the dispatcher a standard library service a module binds,
and lists the five questions and the dependency on #102 and #118 that
section 15's completion waits on.

docs/
└── architecture/
    └── slices/
        └── 15-events.md    new: the section 15 engine design note
The engine's Sharp\Internal\emit, its listener table read and its tests
come from feat/slice-events. This branch's note replaces that branch's,
master's ext/sharp/sharp_unit.h and sharp/baseline/spec/ folder replace
the pinned header and the one-file list, and MINIT registers the stub's
functions once, as master already does.
…er creates each listener

Problem

Spec section 15: PHP# creates a new object for every event and passes
its constructor's services from the module of its namespace, the
default dispatcher runs listeners before emit returns, an app replaces
it once at startup or in tests, and Events.on listens until its handle
goes out of scope. The engine created a listener with new, so a
listener with services threw ArgumentCountError, ran every listener
itself, threw CompileError for a project without listeners, and had no
scoped listener. A new listener file stayed silent in development until
something else made mago compile run.

Solution

- emit resolves Sharp.Dispatcher for the class whose code emits, as
  that class resolves any service, and hands it the event and one
  function per listener, even when no listener hears it. The standard
  library binds ImmediateDispatcher, which runs them in order.
- Each function is a closure over a Sharp\Internal\Listener, which
  builds a table listener's object with sharp_container_build when it
  runs, whatever lifetime a module gives its class.
- Sharp\Internal\listen starts a scoped listener and returns a
  Sharp\Listening, whose destruction stops it. Scoped listeners run
  after the table's, in the order they started, and one whose handle
  is gone runs nothing when a dispatcher calls it later.
- mago compile writes the table in every project with a PHP# file, with
  its inputs: each source folder's listing and each listener's file.
  With sharp.compile_command set, emit runs the command when one
  changed, and reads the table it wrote past opcache. A missing table
  lists no listeners. The compiled count no longer counts the table.
- Dispatcher's parameter is emitted, since event is a PHP# keyword.

ext/sharp/
├── sharp.c            <- emit through the dispatcher, Listener, listen,
│                         Listening, table inputs, sharp_stamp_current
├── sharp.stub.php     <- Sharp\Listening, Sharp\Internal\Listener, listen
└── sharp_arginfo.h    <- regenerated
sharp/composer/library/Sharp/
├── Dispatcher.sharp, ImmediateDispatcher.sharp   <- new
└── Module.sharp       <- binds Dispatcher
sharp/mago/
├── src/commands/compile.rs   <- the table's inputs, the compiled count
└── tests/compile.rs          <- the table's text, its quoted paths
Zend/tests/sharp/
├── events_container.phpt, events_dispatcher.phpt, events_fresh.phpt,
│   events_scoped.inc, events_scoped*.phpt   <- new
├── events.inc, events_table.phpt   <- the library's module, the table
├── Container.inc, library_autoload.inc   <- the dispatcher's classes
└── OrderEvent.sharp   <- an interface member takes no modifier
Problem

emit reads a module file when it resolves the dispatcher, and so does
Sharp\Container::get. sharp_container_read ran the file with
zend_execute, which rebuilds the symbol table of the PHP code that
called the engine and leaves it on that frame. A tracing-JIT frame
never frees it: events_scoped_jit_tracing.phpt leaked a 56-byte
HashTable and its 320-byte data when run twice in one process.

Solution

sharp_container_execute runs the op_array as zend_execute does, with
the exported zend_vm_stack_push_call_frame, zend_init_code_execute_data
and zend_execute_ex, in a symbol table it owns and destroys after.

ext/sharp/
└── sharp.c    <- sharp_container_execute, called by sharp_container_read
… RowImported

Problem

Spec section 15's listeners example listens to the plain PHP
Illuminate\Queue\Events\JobFailed, which no file of the harness marks
with extern event, so the checker refused it: "JobFailed is not an
event." scoped-listener imports App.Imports.RowImported, which the
harness does not declare.

Solution

Each file sits at the path its own section 15 example writes, so
extern-event and standalone-event replace it with the same text.
listeners passes and leaves sharp/baseline/spec. scoped-listener stays
listed until Events.on<T> lands with #102.

sharp/
├── harness/app/Stubs/Laravel.sharp       <- new: extern event JobFailed;
├── harness/app/Imports/RowImported.sharp <- new: public event RowImported(int row);
└── baseline/spec/§15/listeners           <- deleted
… and the container's own symbol table

docs/architecture/
├── slices/15-events.md   <- rulings 1 to 5, the open foreign static question,
│                            what the branch holds, the table's format
└── modules.md            <- the container builds each listener emit runs,
                             runs a module in its own symbol table, and
                             the library binds Dispatcher
Master brings #118, foreign classes and the standard library's
Environment.sharp. The container tests and library_autoload.inc copy
the library's Environment and the Dispatcher and ImmediateDispatcher
this branch binds, and sharp_arginfo.h is regenerated from the merged
stub.
…ws emit with uses Events

Problem

Spec section 15: an app replaces the dispatcher to run listeners later,
after a save, with retries, and the listeners it runs may reach any
effect. #118 holds every implementation to its declaration's uses, so
a dispatcher that wrote to the database was refused against the pure
Dispatcher.dispatch, and a getter could call dispatch as if it were
pure. "Code without a body allows it with uses Events" had no test of
its own.

Solution

- No implementation of Sharp\Dispatcher::dispatch is held to its
  declaration, as team-lead ruled: it runs the listeners of every
  event. Any other declaration still holds its implementations.
- Dispatcher.dispatch declares uses Events, so a call of it has the
  effect emit has.
- A test holds an implementation that emits to an interface or
  abstract method that lists Events, and refuses it against a pure one
  and one that lists only Mail.

sharp/composer/library/Sharp/Dispatcher.sharp   <- dispatch uses Events
sharp/mago/crates/analyzer/
├── src/effects/mod.rs   <- runs_listeners, skipped by unfit_implementations
└── tests/sharp.rs       <- a_dispatcher_may_reach_any_effect_and_a_call_of_dispatch_has_the_effect_events,
                            code_without_a_body_allows_emit_with_uses_events
… and what emit costs

docs/architecture/slices/15-events.md   <- what the branch holds after #118,
                                           the open foreign static question,
                                           the dispatcher's emitted and uses Events,
                                           Sharp\Internal\Listener, the measured cost,
                                           the file tree and the tests as built
…rom extern Internal.listen through #124

Co-Authored-By: Claude <[email protected]>
…ener

Jordan ruled that a plain PHP library's own events reach PHP# listeners through PSR-14. Sharp\Psr\ListenerProvider, beside Sharp\Psr\Container, returns Sharp\Internal\listenersFor($event): the listeners emit would hand the dispatcher, in its order, each a closure over Listener::hear that takes the event as PSR-14 calls it, and runs a table listener on a new object from the container. emit and the provider build their lists through one function, sharp_listeners_for. sharp/composer requires psr/event-dispatcher ^1.0, which sharp/phpunit's lock pins at 1.0.0. Spec section 15 states the rule.

Co-Authored-By: Claude <[email protected]>
…ry listener

Section 15's PSR-14 rule now shows how a PHP# app wires it: import Sharp.Psr.ListenerProvider and the library's dispatcher, and bind the dispatcher with new ListenerProvider(). sharp/bin/spec checks the example psr-listeners against new harness stand-ins: psr/event-dispatcher's two interfaces, Vendor\Events\EventDispatcher, and a copy of ListenerProvider.php, since the guarded sharp/bin/spec copies only sharp/composer/library/ into an example's project.

Co-Authored-By: Claude <[email protected]>
…feat/events-engine

Kept both sides of sharp.stub.php's Sharp\Internal declarations and regenerated sharp_arginfo.h. The dispatcher's effects test calls global.fetch, since #124 refuses a bare call.

Co-Authored-By: Claude <[email protected]>
…goes

sharp/composer/library/Sharp/Events.sharp declares extern Internal.listen uses Events and a static Events.on<TEvent> whose body calls Internal.listen(typeof(TEvent), listener), so on has the effect Events by inference. The prelude declares Sharp\Listening and Sharp\Internal\listen for the checker. Events.on<T> refuses a T that is not an event or an interface an event implements, with the on clause's messages (ruling 1). Only the standard library imports Sharp.Internal (internal-outside-library). A PHP# Class.m() call now names its method for the unused-result check, so a dropped Events.on handle is reported, as [NoDiscard] says. scoped-listener leaves sharp/baseline/spec, and every section 15 example passes.

Co-Authored-By: Claude <[email protected]>
…ng class

check_events_on read a missing class's refused type as a type that is not an event and reported "`` is not an event." beside "Cannot find type". A refused type now passes, as a type parameter does. The rows for a missing class and for Events.on<TEvent> inside a generic method run every line of check_events_on, which patch-coverage asks for.

Co-Authored-By: Claude <[email protected]>
…, into feat/events-engine

Kept both imports in static_method_call.rs and regenerated sharp_arginfo.h.

Co-Authored-By: Claude <[email protected]>
One dispatcher serves the whole app: mago compile names the app's top module that binds Sharp.Dispatcher in the listener table, and emit resolves it whoever emits, after a running test's binding. Dispatcher.dispatch takes List<Function<void(Any)>>, so emit and PSR-14 share one closure kind, and Listener::run is gone.

Every PHP# file and the listing above it are inputs of the table, and a listing names its namespace folders. While developing, the table is read past opcache. Sharp\Listening owns its function and reports it to the cycle collector. namespace Sharp is refused outside the standard library. A dropped [NoDiscard] value is reported in PHP# words, an out-of-date table says so, Events.on(e => { }) gives one error, and the prelude declares listenersFor.
Spec section 15 says an app replaces the dispatcher once at startup. So the base or environment module outside vendor/ with the fewest namespace parts is the one app module that binds Sharp.Dispatcher. A binding in any other app module is refused with invalid-binding, naming the top module, and two top modules of the same depth are each refused, never picked by file name. A test module still replaces it, and the standard library's module, the one module of the root namespace, never counts.

top_dispatcher_namespaces in codex serves the analyzer's refusal and mago compile's choice of the table's dispatcher module, and section 15 states the rule with the example one-dispatcher.
@heyJordanParker
heyJordanParker merged commit bd3fa40 into master Oct 14, 2026
22 checks passed
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
Problem:
Master's #127 refuses a PHP# file outside the standard library that
declares `namespace Sharp`. The `Sharp.ClassMembers` fixture of the
analyzer's class value tests sat at `src/Sharp/ClassMembers.sharp`, so on
the merge with master it was app code in a library namespace, and
`a_member_of_class_wins_over_a_static_of_the_held_class` failed with
`reserved-name-outside-library`.

Solution:
The fixture lives where the library does,
`vendor/heyjordanparker/php-sharp-composer/library/Sharp/ClassMembers.sharp`,
which the test helper marks as the standard library.

sharp/mago/crates/analyzer/tests/
└── sharp.rs   CLASS_MEMBERS moves under the library's folder
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
… 25's class values

Problem:
#129 is at the head of the landing queue, and master gained the events
engine (#127) and readonly (#128) since its last merge.

Solution:
Both conflicts keep both sides:
- The parser starts a local declaration at `self`, which section 25's
  `Self copy = …` refusal needs, and at `readonly`, which #128 adds.
- The extension protocol's tests keep the class value test and #128's
  test that an external analyzer's class is never readonly.

sharp/mago/crates/
├── syntax/src/parser/internal/statement.rs   "self" | "readonly"
└── analyzer/src/external/protocol.rs         both tests
@heyJordanParker
heyJordanParker deleted the feat/events-engine 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