Repository navigation
feat: run extension members and give string its trim(), spec section 26 - #115
Conversation
A static class declares `extension(Type value) { … }` blocks. Each method or
computed property in one runs as a public static method of the class that takes
the receiver first, and `value.member(…)` calls it wherever the file imports the
class, declares it, or gets it from the default import of `Sharp`.
- The parser reads the block, and the binder makes the receiver a parameter.
- The checker refuses a block without exactly one typed receiver, a member that
hides a real member of the receiver, and two extensions that fit one call.
- A wrapped function called directly names the method that replaces it.
- The bridge lowers a call on a receiver no unseen class can hold to the static
call, or to the library's inline form, as `trim($name)` for `name.trim()`. Any
other receiver goes through `\Sharp\Internal\extension`, where a real member of
the object's class runs instead.
- The incremental compile re-analyzes a file when the members an extension may
not hide change.
- A law that reaches an extension member proves it as the static call it runs
as. On an open receiver, where another member can run, it is refused with
`unmodeled-construct`.
# Conflicts: # crates/analyzer/src/statement/class_like/method.rs # crates/semantics/src/internal/checker/class_like/mod.rs
The engine gains \Sharp\Internal\extension($receiver, $class, $member,
$property, ...$arguments), which Mago writes for an extension member on a
receiver an unseen class can hold. A public declared method or property of the
receiver's class runs, as spec section 26 says a real member wins. Otherwise
the extension's static method runs with the receiver first.
The standard library declares `extension(string text) { trim() }` in
Sharp/Text/Text.sharp, so `name.trim()` runs as `trim($name)`, and a direct
`trim(name)` is refused with the method that replaces it.
SHARP_MAGO_COMMIT moves to the Mago that reads extension blocks. The spec
example `§26 extensions` passes and leaves sharp/baseline/spec.
The extension arm grew parse_classlike_member's unoptimized frame from 0x3970 to 0x3C70 bytes on x86_64, so nightly CI's 128 KiB stack test of a 100,000-term property default overflowed in a plain PHP class. The arm moves into parse_sharp_member_with_attributes_and_modifiers, which only PHP# reaches, and parse_classlike_member's frame is master's again.
…ection 26 adds A member named after its static class with no return type, the PHP# constructor form, compiled inside an extension block as a static method. It is now "A static class has no constructor.", as it is in the class's own body. The bridge's extension method without a return type and the semantics note for an extension's place can no longer run, so each is an unreachable! arm. The analyzer tests mark a file under vendor/heyjordanparker/php-sharp-composer/ as the standard library, as the bridge tests do, so a wrapped function's extension member, a plugin reading an extension's arguments, an ambiguous computed property, a receiver no extension fits and a member declared twice are tested where patch-coverage measures them. The bridge tests add an Any receiver, a named argument, a block body that inlines and a library constant.
\Sharp\Internal\extension took only an object, so an extension member read on a value of a type such as `Wallet|string` or `Any` threw a TypeError when the value was a string. A value that is no object has no member of its own, so the extension's static method runs with it first.
Jordan's ruling: a class or extension in the file's own namespace applies with no import, as in Kotlin, C# and Java. An extension is in scope where its class is imported, where the default import of Sharp brings it, or in a file of its class's namespace, which includes the declaring file. A file of another namespace is still told the import line to add, and every class such a file lacks needs one, so the message's fallback for a same-namespace class is gone.
It refuses a constructor in an extension, applies an extension in its class's own namespace with no import, and merges mago-sharp master 9339e1f.
A project class named like a default Sharp class, such as App.Cache, could
not be used bare from another App file. The bare name always meant the
Sharp class, so `Cache?` failed with "Cannot find type `Cache`" unless
the file imported App.Cache. Kotlin, C# and Java resolve a same-package
class first, and PHP# now does too.
Use a class of the file's namespace by its bare name:
- A bare default name means the class of the file's namespace when the
project declares one, as a type, a `new`, an `is` and a static call
- With no such class it still means the Sharp class, so `Environment`
stays Sharp.Environment
- Int, Float, Bool and List are reserved PHP class names, so they always
mean the Sharp class
Keep analysis and compiled files right when such a class comes or goes:
- Analysis scans every file once, collects the project's classes named
like a default class, and scans again only the files that name one
- Watch mode re-analyzes the project when a change adds or removes such
a class, and analyzes only the changed file otherwise
- A compiled file lists the files that would declare each such class in
its folder as inputs, so adding app/App/Cache.sharp makes it stale
- Analyzing one file in an editor resolves against the same classes
.php files resolve names exactly as before.
crates/
├── names/
│ ├── src/lib.rs <- lists the default classes a namespace class can win over, records the ones a file names
│ ├── src/resolver.rs <- resolve_in takes the project's NamespaceClasses
│ ├── src/internal/walker.rs <- a bare default name resolves to the namespace class when the project has it
│ └── tests/binder.rs <- type, new, static call and is rows, the Environment row, the reserved Int row
├── analyzer/
│ └── tests/sharp.rs <- every default effect name as a project class, plus the Environment row
└── orchestrator/src/service/
├── incremental_analysis.rs <- collects NamespaceClasses, rescans the files that name one, re-analyzes when it changes
├── incremental_analysis/compile.rs <- lists the namespace class files as compile inputs, warm and clean compile rows
├── body_return.rs <- resolves body returns against NamespaceClasses
└── analysis.rs <- single-file analysis keeps file-local names
…apped ones The mutants job found two survivors on #178. Deleting the walk into an extension's methods and computed properties left every test green, so a PHP construct in an extension member's body could compile unchecked. Turning `!report_wrapped_function_call` into its opposite did too, because only the root package, which the job does not run, tested the replaced-by-syntax report. Each new row fails with its mutant applied.
Once a class of the file's namespace takes a default name, the refusals of
`__DIR__`, `__FILE__` and the other magic constants still told the user to
write `Position.current()`, and the superglobal note still named
`Environment`. In `App` with its own `Position`, that fix named
`App.Position` and was refused. A full name like `Sharp.Position` is
refused outside imports too.
Follow a refusal's help in a namespace that shadows a standard class:
- The binder records, per .sharp file, each default class its short name
no longer reaches: one the file imports or declares, or one of its
namespace
- The magic-constant help then writes `SharpPosition.current()` after
`import Sharp.Position as SharpPosition;`, and the superglobal note
names `SharpEnvironment` the same way
- An imported or declared `Position` gets the same help, which was
already false before this change
Keep the watch-mode scan of an edited file covered:
- The clean-versus-warm compile row now also edits the file that names
the namespace class
Stop rescanning the standard library's own files:
- A bare `Replaces` in `namespace Sharp;` no longer records
`Sharp.Replaces` as a class of its namespace
crates/
├── names/
│ ├── src/lib.rs <- ResolvedNames::shadows_default_class, per file
│ ├── src/internal/walker.rs <- class_meaning splits from resolve_class; walk_out_namespace records shadowed defaults
│ └── tests/binder.rs <- namespace, import, declaration, no-shadow and Sharp-namespace rows
├── semantics/src/internal/checker/
│ └── sharp.rs <- magic-constant and superglobal helps name the standard class as the file reaches it
└── orchestrator/src/service/incremental_analysis/
└── compile.rs <- help row that compiles the quoted fix, and the edited-file row
…Kotlin A member the receiver's static type declares or inherits wins over an extension of its name. Otherwise the extension that applies in the file runs, on an object of a subclass with its own member of that name too. So `Order order = new RushOrder(); order.total();` runs the extension when only `RushOrder` declares `total()`, and `RushOrder rush` runs `RushOrder`'s member. - The analyzer resolves an extension only when the type the code shows has no member of its name, and records a reference to that member on each class of the type, so the call site is analyzed again when the class gains or loses it. - `get_classes_hidden_by_extension` takes the receiver type and the member name, and no longer looks below the type. A subclass's member is no longer a compile error for the extension. - The bridge lowers every extension access to the static call of its method. `Types::is_closed` and the Lean translator's `runs_statically` are deleted, and the orchestrator no longer reads the receiver's subclasses for a compiled file. - The orchestrator test compares warm and clean refusals and the compiled body after the header. A warm key can still differ: the incremental analysis keeps the references a re-analyzed method made before, which costs one needless recompile.
mago-sharp 3126aa4 chooses an extension from the receiver's static type, as in C# and Kotlin, and lowers every extension access to the static call of its method. So the engine looks nothing up while the code runs: `\Sharp\Internal\extension` and its native entry are deleted. - extensions.phpt runs an `AuditedWallet`, a subclass of `Wallet` with its own `total()` and `isEmpty`, through code typed `Wallet`: the extension runs. Code typed `AuditedWallet` runs its own member. - The spec states the static choice in place of the rule that refused an extension a subclass's member could hide. - Build the PHP# bridge from mago-sharp 3126aa4.
Patch coverage reads only the analyzer, semantics and bridge tests, and the shadowed branch of the magic-constant and superglobal helps was run only by an orchestrator row. A file that imports its own `Position` and `Environment` now gets the aliased-import help in the semantics tests. crates/semantics/tests/ └── sharp.rs <- an imported Position and Environment take the help's aliased import
…kips The receiver's type always traces to a signature that names its class, so the incremental analysis already analyzes the access again when a class of the type gains or loses a member of its name. Removing the references left every row green, so they and the two parameters that carried them are deleted. The orchestrator row's caller now reaches the wallet through `Purse.wallet()` and never names `Wallet`, and its compiled body still matches a clean compile.
Every push to a pull request started up to eight hour-long mutation shards. They block no merge, but they held the runners, so twelve runs across both repositories sat queued and every builder waited for checks. Builders already prove each new test row fails with its code removed, and the review checks that proof. The shards now run only when a pull request carries the `mutants` label. .github/workflows/ └── ci.yml* <- mutants-plan runs only on a pull request labelled mutants
# Conflicts: # crates/sharp-lean/src/translate/mod.rs
ci: run mutation testing only on a pull request labelled mutants
`order?.amount.kind` runs `kind` only when `order` is not null, so its type gains `null`, as a real member's does. The analyzer passed no null-safe null from the receiver to the extension's call, so it typed the chain as never null and refused `order?.amount.kind ?? "none"` as a redundant null coalesce. The bridge's null-safe row now reads an extension property with `.` below `?.`. It lowers under the conditional that tests `order`, and fails when `untested_link` skips the extension check on a plain property link: the two mutants that survived on 7480059.
feat: a class of the file's namespace wins over a Sharp default name
# Conflicts: # crates/names/src/internal/walker.rs # crates/orchestrator/src/service/incremental_analysis/compile.rs
# Conflicts: # docs/spec.md # ext/sharp/sharp_unit.h # sharp/baseline/spec~HEAD
# Conflicts: # sharp/mago/.github/actions/setup-lean/action.yml # sharp/mago/.github/workflows/ci.yml
The merge of mago-sharp feat/extensions into sharp/mago gives `mago compile` extension blocks, so the `extensions` example of docs/spec.md §26 compiles. `sharp/bin/spec` lists it as passing and still in sharp/baseline/spec. sharp/baseline/spec/§26/extensions leaves the list. The other examples that pass come from mago-sharp master's merged pull requests, and leave the list in the pull requests that move those pins.
…lt one Spec section 26, as master states it: "One in the file's own namespace shadows a default extension of the same name (section 23)." Section 23 gives a class the file imports the same precedence. The checker treated the three alike, so `name.shout()` in a file of `App`, beside an `App.Loud` extension `shout` on `string`, was refused as two imported extensions, `Words` and `Loud`. The file cannot drop the default import, so the refusal's help, "Import only one of them", had no fix. `resolve_extension` now picks among the extensions the file imports or its namespace declares, and only where none of those fits, among the standard library's. Two of the file's own still compete. `mago analyze --watch` analyzed only the new file when a namespace gained an extension, so `Report` kept the default's `string` where a clean analysis refused its `int`. The warm path now analyzes the project again when a file's extension members, or their receivers' types, change, as it does for `[Replaces]` wrappers and `extern` declarations. A body edit of an extension member still analyzes only its own file. sharp/mago/crates/ ├── analyzer/src/resolver/extension.rs # own extensions shadow default ones ├── analyzer/tests/sharp.rs # the rule's three rows ├── orchestrator/src/service/ │ ├── incremental_analysis.rs # extensions_in, full analysis on change │ └── incremental_analysis/compile.rs # warm compile matches clean, 4 rows x 2 modes
…r runs Jordan ruled that an extension member its receiver type, or a class above it, already declares stays a compile error, because it can never run, as Swift refuses an `invalid redeclaration`, and that spec section 26 states it. The checker said "An extension cannot hide the real member `Money.total`.", which named neither the receiver nor the consequence. The checker now says "`Order` already declares `label()`, so this extension member never runs." It names the receiver type the extension block writes, with `()` on a method and none on a property. Section 26 states the rule with the example `extension-hidden-member`, and its scope bullet says that an extension the file imports, or one its own namespace declares, shadows a default one, as a class does. `extension-static-choice` now calls `caption()`: the harness `Order` inherits `label()` from `DatabaseEntity`, so an `OrderLabels.label()` would itself be refused. docs/spec.md # section 26 rules and example sharp/mago/crates/ ├── analyzer/src/statement/class_like/method.rs # check_hidden_member's message ├── analyzer/tests/sharp.rs # the message's exact text, 7 rows └── orchestrator/src/service/incremental_analysis/compile.rs # hidden_members reads it
…aseline
`extension-static-choice` failed with "Class `RushOrder` not found", and
`extension-overloads` with "Method `total` does not exist on
`List<App.Line>`". The harness declared none of the classes they name.
sharp/harness/ now declares them, one class per file at its namespace's
path. Each body returns a constant or throws `Elided`, so no stub gives a
value an example claims. `sharp/bin/spec` passes all four section 26
examples, and both entries leave `sharp/baseline/spec`.
sharp/harness/app/
├── RushOrder.sharp # RushOrder : Order, with its own caption()
└── Billing/
├── OrderLabels.sharp # extension(Order order) { caption() }
├── LineTotals.sharp # extension(List<Line> lines) { total() }
└── PriceTotals.sharp # extension(Map<string, Money> prices) { total() }
sharp/baseline/spec/§26/
├── extension-overloads # deleted: passes
└── extension-static-choice # deleted: passes
…sion Spec section 26 applies an extension of the file's namespace with no import, and one there shadows a default one. A compiled `Report` whose `name.shout()` ran the standard library's `Words.shout` kept running it after `App/Loud.sharp` declared a shadowing `shout`, or after `App/Helpers.sharp` gained an extension block: no input of `Report.sharpc` named either file, so the engine loaded the old code. That is a program compiled wrong. A compiled file whose code reaches an extension member now lists, as inputs, each `.sharp` file of its folder and the folder's listing, `App/*.sharp`. The listing's stamp hashes the names of the folder's regular `.sharp` files, each followed by a newline, in byte order, so a file appearing or going makes the compiled file stale, and an edit reaches it through the file's own input. `unit::stamp` and the engine's `sharp_stamp_of` compute the same stamp. A file whose code reaches no extension lists neither: a member its type declares wins over any extension, and a call with no member is a compile error, so no new file can change it. Whether a file reaches an extension comes from the analysis `lower_all` runs for that one file, because the warm path keeps references a method made before it was edited. The engine compares a stamp it already hashed by its hash alone, so a listing, whose modification time is zero, is never taken as current for its size alone. ext/sharp/sharp.c # sharp_stamp_listing, the hash comparison Zend/tests/sharp/extension_inputs.phpt # new: 4 rows through the engine's stale check sharp/mago/crates/ ├── sharp-bridge/src/unit.rs # SOURCE_LISTING, stamp of a listing ├── sharp-bridge/tests/unit.rs # the listing's stamp, 6 rows └── orchestrator/src/service/incremental_analysis/compile.rs # LoweredUnit.reaches_extension, folder inputs
|
Review verdict: CHANGES NEEDED Head: php-sharp #115 at 1. A static call of an extension member crashes
|
# Conflicts: # sharp/mago/crates/semantics/src/internal/checker/sharp.rs
- A call through the extension's class, as `WalletExtensions.total(w)`, compiles to that static call. `Types::extension` returns None for a static call, so the bridge and the Lean translator no longer lower the class name as a receiver and panic. - The listing of a folder's `.sharp` files skips a dangling link and a file named only `.sharp`, as the loader and the engine do, so `mago compile` no longer fails on an Emacs lock link. - Of the extensions that fit a receiver, the one whose receiver fits inside every other's runs, as in C# and Kotlin. Two where neither fits inside the other stay an error. - An extension member is refused as "never runs" only when every part of its receiver that is not `null` declares it, and the message names those parts. - The ambiguity error says where each extension comes from, the file's namespace, an import or the standard library, and its help names the imports to remove, or the member to rename. - Section 26 states the call through the class, the most specific receiver and the union receiver rule.
…st specific receiver - `WalletReport.direct` calls `WalletExtensions.total(wallet, 4)` and `WalletExtensions.isEmpty(wallet)` through the class. - `AuditExtensions` adds `rank()` to `AuditedWallet` beside `WalletExtensions`' `rank()` on `Wallet`, and `WalletReport.ranks` shows the type the code shows picking each. - `§23/own-namespace-shadows` passes, so it leaves the baseline.
A compiled file lists, as inputs stamped absent, the files a class name could resolve to, as `Environment.php` beside a file that names the standard `Environment`. A disk that ignores case, as macOS's does by default, opens `environment.php` for `Environment.php`. So the engine refused that compiled file as out of date while run-tests wrote `environment.php` for `environment.phpt`, and a compile beside it stamped `Environment.php` with `environment.php`'s hash. - The engine's `sharp_folder_holds_name` keeps an input stamped absent current unless its folder holds a file of exactly that name. - The bridge's `unit::stamp` stamps a file only when its folder holds it under its exact name, through `folder_holds_name`. A compile on a disk that ignores case and one on Linux now stamp the same inputs, and the engine reads them the same way.
patch-coverage found seven lines no test ran on Linux. - `unit::stamp` asks `folder_holds_name` before it reads the file, so a missing file on Linux reaches the same lines a file named in another case reaches on a Mac. A missing folder holds no file, and a path through a file fails with `NotADirectory`, for a file and for a listing alike. - An ambiguity among extensions of the global namespace says "of the global namespace". - `listed` never gets an empty list, and `check_hidden_member` never gets a receiver with no part, because `to_non_nullable` leaves `never` where only `null` was. Both are `unreachable!` with that reason.
A compiled file lists, as inputs stamped absent, the files a class name could resolve to, as `Environment.php` beside a file that names the standard `Environment`. A disk that ignores case, as macOS's does by default, opens `environment.php` for `Environment.php`. So the engine refused that compiled file as out of date while run-tests wrote `environment.php` for `environment.phpt`, and a compile beside it stamped `Environment.php` with `environment.php`'s hash. - The engine's `sharp_folder_holds_name` keeps an input stamped absent current unless its folder holds a file of exactly that name. - The bridge's `unit::stamp` stamps a file only when its folder holds it under its exact name, through `folder_holds_name`. A compile on a disk that ignores case and one on Linux now stamp the same inputs, and the engine reads them the same way. Cherry-picked-from: be812ec on feat/extensions (#115), without that branch's SOURCE_LISTING Co-Authored-By: Claude <[email protected]>
…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 Master gained #110 (constructors), #113 (the verification slice) and #115 (extensions). Four Mago files conflicted with this branch's modules, and the bridge's extension members called `attributes` and `parameter` without the service argument this branch added. The analyzer tests also declared `STANDARD_LIBRARY` twice. Solution Each conflict keeps both sides: the codebase keeps its modules and its extensions, and merges and removes each of them. The warm path reanalyzes when modules or extensions change, and when a namespace's classes change. A compiled file lists its namespace's class files and folder files, and its module files. The semantics checker keeps both `unreachable!` notes. An extension member is no service the container fills, so its attributes and parameters pass `None`. ```text sharp/mago/crates/ ├── codex/src/metadata/mod.rs modules and extensions, both merged and removed ├── orchestrator/src/service/incremental_analysis.rs modules, extensions and namespace classes each reanalyze ├── orchestrator/src/service/incremental_analysis/compile.rs namespace files and module files both inputs ├── semantics/src/internal/checker/sharp.rs the module and extension notes both unreachable ├── sharp-bridge/src/lower.rs an extension member's attributes and parameters take no service └── analyzer/tests/sharp.rs one STANDARD_LIBRARY ```
Brings #115's extension blocks. Both sides keep their behaviour: - flags.rs: EXTENSION_METHOD and EXTENSION_PROPERTY keep bits 49 and 50, FOREIGN keeps bit 51, and the one-bit test lists all three. - names: #115's shadowing of a default class by one of the file's namespace stays. Its default-class list names the ten effect classes, `Events`, `Position` and `Replaces` directly, since this branch removed STANDARD_EFFECTS. `default_class` replaces this branch's `standard_class`, which held the same names, so `uses` still takes the `Sharp` effect over a file's own class. - binding.rs: an extension method carries its `uses`, a computed property none. - #115's tests read `Environment` as the library's `foreign` class with `currentDirectory()`, not the deleted C class. The absent-input engine test names `Position`, which Mago's prelude still declares. - §29's `pure-interface` passes now that `string` has `trim()`, so it leaves sharp/baseline/spec.
…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
Brings #110, #113, #115, #118, #121 and #126. Both sides keep their behaviour: - #115 wraps `trim` with the extension `string.trim()` through `[Replaces]`, which this branch retires for the checker's table. The table gains `trim -> Sharp.Text.Text.trim`, and the table's member form renders an extension member on the call's first argument, as #115's wrapper did: `name.trim()`, `name.trim(…)`, `name.trim`, and the class's import only where the file lacks the extension by default. `Sharp\Replaces` leaves the default class names. #115's tests move to the table row. - Every PHP# source master adds calls plain PHP through `global.`: the library's Environment and Text extension, Accessors.sharp, Constructors.sharp, the test fixtures, and the slice notes. - The import check keeps #115's reference to an imported class, so its extensions reach the file. - Issue codes hold both sides': bare-function-call and function-import beside the effect and module codes. - §29 pure-interface joins sharp/baseline/spec again: this branch's example writes through `Files`, which ships with the effect classes.
Completes: §26
Problem
Spec section 26 lets a static class add members to a type it does not own, and spec sections 8 and 23 build the standard library on it:
name.trim()is an extension onstringthat every file gets from the default import ofSharp. Mago had noextensionblock, so none of it parsed, and the standard library could not ship one method.This PR is the whole feature. It moved here from mago-sharp #178 when mago-sharp froze:
sharp/mago/takes mago-sharp'sfeat/extensions(14068d7) bygit subtree merge, asdocs/architecture/mago.mdsays, and this branch's engine tests, library and baseline change sit beside it.Solution
A static class declares
extension(Type value) { … }. Each method or computed property in the block runs as a public static method of the class that takes the receiver first.Scope.
value.slug("-")resolves where the file imports the class, is in the class's own namespace (the declaring file among them), or gets it from the default import ofSharp. Jordan ruled that a same-namespace extension applies with no import, as a class does in Kotlin, C# and Java. The default import covers the standard library's extensions onstring,int,float,List,MapandSet, and classes directly inSharp. A caller in another namespace without the import is refused, and the refusal names the import line to add.Shadowing. An extension the file imports, or one its own namespace declares, shadows a default extension of the same name, as section 23 rules for a class. Section 26 now says so. Before,
name.shout()beside anApp.Loudextensionshoutonstringwas refused as "The imported extensionsWordsandLoudeach addshouttostring", and its help, "Import only one of them", had no fix, because no file can drop the default import. Two of the file's own extensions still compete.Choice (Jordan's ruling). An extension is chosen from the type the code shows, as in C# and Kotlin. A member the receiver's static type declares or inherits wins. Otherwise the extension that applies in the file runs, even when the object is a subclass with its own member of that name:
Most specific receiver. Of the extensions that fit a receiver, the one whose receiver type fits inside every other's runs, as C# overload resolution and Kotlin do. Two that fit where neither receiver is inside the other are an error:
The checker refuses:
thisin a member, and a modifier other than an access modifier;List.count,Map.hasandSet.add, because it can never run (Jordan's ruling, as Swift refuses aninvalid redeclaration). The message names the receiver type and the member: "Orderalready declareslabel(), so this extension member never runs." On a union receiver it is an error only when every part that is notnulldeclares the member, and the message names each part: "MoneyandWalletalready declaregross()". OnWallet|stringthe extension runs for astring, so it is accepted. A class below the type never makes an extension a compile error;A wrapped function called directly names the method that replaces it: "
trimis wrapped by the standard library: writename.trim()."Lowering. Every extension access is the static call of its method, or the library's inline form of a one-call body, as
trim($name)forname.trim(). A call through the class, asWalletExtensions.total(w)orWalletExtensions.doubled(w), is that static call already, as in C#:Types::extensionanswers no for a static call, so the bridge and the Lean translator lower the plain static call. Before, both panicked atlower.rs:3377andmago compilewrote no file. The engine looks nothing up while the code runs, soext/sharp/sharp_native.handsharp/bin/nativeequal master.ext/sharp/sharp.cchanges only for the compiled-file inputs below and for inputs named in another case.The library's first extension.
sharp/composer/library/Sharp/Text/Text.sharpdeclaresextension(string text) { [Replaces("trim")] public string trim() => trim(text); }.Incremental analysis. The receiver's type always traces to a signature that names its class, so the existing invalidation cascade analyzes the call site again when a class of the type gains or loses a member of that name. The orchestrator row's caller reaches the wallet through
Purse.wallet()and never namesWallet. Its refusals and compiled body still match a clean compile. A file that gains or loses an extension member, or changes a member's receiver type, now makesmago analyze --watchanalyze the project again, as a change to[Replaces]wrappers orexterndeclarations does. Without it, a namespace that gained a shadowing extension kept the default's result in every other file of the namespace. A body edit of an extension member still analyzes only its own file.Compiled-file inputs. A compiled file whose code reaches an extension member lists each
.sharpfile of its folder and the folder's listing,app/App/*.sharp, as inputs. Before, the engine kept running aReportwhosename.shout()called the defaultWords.shoutafterapp/App/Loud.sharpdeclared a shadowingshout, or after another file of the folder gained an extension block. The listing's stamp is the xxh3-128 of the names of the folder's regular.sharpfiles, each followed by a newline, in byte order, with that text's length as its size and a modification time of zero. A link counts as the file it reaches. A dangling link, as Emacs leaves beside a buffer with unsaved changes (.#Report.sharp), and a file named only.sharpare left out.unit::stampand the engine'ssharp_stamp_ofcompute it the same way. Before, a dangling link failed all ofmago compilewith "Database error: I/O error" and named no file.An input is there only under its exact name, case included, as on Linux. A compiled file lists, as inputs stamped absent, the files a class name could resolve to, as
Environment.phpbeside a file that names the standardEnvironment. A disk that ignores case, as macOS's does by default, opensenvironment.phpforEnvironment.php. So on a Mac the engine refusedDeploy.sharpas out of date while run-tests wroteenvironment.phpforenvironment.phpt, and a compile beside that file stampedEnvironment.phpwithenvironment.php's hash. Four engine tests failed in a whole-folder run on a Mac, on master too. Now the engine'ssharp_folder_holds_namekeeps an input stamped absent current unless its folder holds a file of exactly that name, and the bridge'sunit::stampstamps a file only under its exact name, throughfolder_holds_name. The engine reads its folder only for an input stamped absent whose path opens. A file whose code reaches no extension lists neither, because no new file can change it: a member its type declares wins, and a call with no member is a compile error. Whether a file reaches an extension comes from the analysislower_allruns for that one file, not from the warm path's references, which keep what a method reached before an edit. The engine now compares a stamp it already hashed by its hash alone, so a listing is never taken as current for its size alone.A warm
.sharpckey can still differ from a clean one: the incremental analysis keeps the references a re-analyzed method made before, which costs one needless recompile and runs no wrong code. team-lead files that master bug as its own task.Laws (spec section 28). A law that reaches an extension member translates it as the static call it runs as: a
defthat takes the receiver first, called asApp.Shared.ShapeMath.doubled s. Before this change, the method form was refused with the false "a call of a function value … lambdas", and the computed property form crashedmago compileattypes.rs:143("App\Shared\Shape.isFlat, which names no member"). Because the checker chooses the extension statically, a law reaches it on an open receiver too. A body Lean cannot model is refused as any method body is, as in "Law summed reaches a loop in ShapeMath.sum."The spec. Section 26 changes in six places:
title.slug(); title.isBlank; +TextExtensions.slug(title); // the same call, written through the class, as in C#extension-static-choicenow callscaption()instead oflabel(). The harnessOrderinheritslabel()fromDatabaseEntity, so anOrderLabels.label()onOrderwould itself be refused by the rule above, andorder.label()would runOrder's own member.The harness gains the classes section 26's examples name, one class per file at its namespace's path. Each body returns a constant or throws
Elided, so no stub gives a value an example claims:sharp/harness/app/RushOrder.sharp:RushOrder : Orderwith its owncaption().sharp/harness/app/Billing/OrderLabels.sharp:extension(Order order) { caption() }.sharp/harness/app/Billing/LineTotals.sharp:extension(List<Line> lines) { total() }.sharp/harness/app/Billing/PriceTotals.sharp:extension(Map<string, Money> prices) { total() }.readonly-values(§13), already listed, now also reports thatRushOrderlacks the constructor of theOrderthat example declares. A harness subclass of a harness class has this cost wherever an example replaces the parent.sharp/baseline/specloses all three §26 entries:extensions,extension-overloadsandextension-static-choice. The newextension-hidden-memberpasses. It also loses§23/own-namespace-shadows, which the shadowing makes pass. §8 and §23 still have entries, soCompletes:names §26 only.New Architecture (accepted by team-lead)
sharp/mago/crates/analyzer/src/resolver/extension.rs,sharp/mago/crates/syntax/src/cst/cst/class_like/extension.rs,sharp/mago/crates/syntax/src/parser/internal/class_like/extension.rsCodebaseMetadata::get_classes_hidden_by_extension(&self, receiver: &TUnion, name: &[u8]) -> Vec<Word>: the classes of the receiver's type that declare or inherit a member of that name.Types::extensioninsharp/mago/crates/sharp-bridge/src/lower/types.rswent frompub(crate)topub, because the Lean translator asks it the same question the lowering asks.Deleted by the static choice:
Types::is_closed, the Lean translator'sruns_statically, the orchestrator's read of a receiver's subclasses for a compiled file, and the engine function\Sharp\Internal\extension.Master is merged
This branch merges master 5d5724a, with #114, #110 and #113.
mago compilecompiles all 106 engine fixtures, andsharp/bin/specmatches the baseline. The one conflict, insemantics/src/internal/checker/sharp.rs, keeps master'sPlace::Modulearm beside this branch'sPlace::Extensionarm. #110's fixtureConstructors.sharpcalledtrim(json), which this PR refuses because the standard library wraps it, so the merge writesjson.trim(). It inlines to the sametrim($json).Verification
New tests:
an_extension_is_its_receiver_and_its_members_in_braces,extension_after_a_modifier_or_in_a_body_stays_a_namean_extension_member_binds_its_receiver_as_a_parameteran_extension_in_a_static_class_adds_methods_and_computed_properties,an_extension_outside_a_static_class_is_an_error,an_extension_receiver_is_one_plain_parameter,an_extension_holds_only_methods_and_computed_properties,an_extension_member_takes_only_an_access_modifier,this_in_an_extension_member_is_an_error,an_extension_member_body_is_checked_as_a_method_body,two_members_of_one_static_class_cannot_share_a_name_across_its_extensionsphp_calls_an_extension_member_as_the_static_method_it_runs_as,an_imported_extension_is_a_member_of_its_receiver,a_null_safe_extension_access_skips_a_null_receiver,an_extension_applies_where_its_class_is_imported_or_in_its_namespace,the_standard_library_extensions_on_the_default_types_need_no_import,an_extension_the_file_imports_or_its_namespace_declares_shadows_a_default_one,the_receiver_type_picks_among_imported_extensions_of_one_name,an_ambiguous_extension_names_where_each_competitor_comes_from,an_extension_named_like_a_real_member_of_its_type_is_an_error,an_extension_member_reads_its_receiver_as_a_parameter_of_its_type,the_analyzer_checks_only_the_members_an_extension_holds_once,a_plugin_reads_an_extension_members_receiver_as_its_first_argumentan_extension_member_is_the_static_method_that_takes_the_receiver_first,an_extension_member_is_the_static_call_of_its_method,the_type_the_code_shows_chooses_between_an_extension_and_a_subclass_member,the_extension_with_the_most_specific_receiver_runs,an_extension_member_passes_a_named_argument_by_its_name,a_standard_library_extension_member_inlines_as_the_call_its_body_makes,a_null_safe_extension_member_runs_only_on_a_receiver_that_is_not_nulla_file_reads_each_class_it_imports,a_compile_after_a_class_an_extension_receiver_is_gains_or_loses_its_member_matches_a_clean_compile,a_compile_after_the_namespace_gains_or_loses_an_extension_that_shadows_a_default_one_matches_a_clean_compile,a_file_whose_code_reaches_an_extension_lists_the_sharp_files_of_its_folder_as_inputsa_source_listing_stamps_the_names_of_the_sharp_files_of_its_folderanalyze_names_the_extension_member_that_replaces_a_wrapped_function,compile_proves_a_law_through_an_extension_member_as_the_static_call_it_runs_as,a_law_reaching_an_extension_member_lean_cannot_see_is_refused,compile_skips_a_dangling_link_beside_a_file_that_reaches_an_extensionZend/tests/sharp/extensions.phpt,Zend/tests/sharp/extension_inputs.phptThe compiled-file input rows run through the engine's stale check with
sharp.compile_commandset:extension_inputs.phptprinteddefaultwhere it expectsloudafterApp/Loud.sharpappears, anddefaultwhere it expectshelperafterApp/Helpers.sharpgains an extension block. The row that deletesApp/Loud.sharpalready passed, because the recompile it follows madeLoud.sharpan input throughReport's reference to it.a_file_whose_code_reaches_an_extension_lists_the_sharp_files_of_its_folder_as_inputsfails:Reportlists neitherapp/App/*.sharpnorapp/App/Plain.sharp. With the reference check inverted, it fails the same way.Plaincurrent after its folder gainsExtra.sharp.The static choice's rows each fail with its code removed:
Order order = new RushOrder(); order.total();lowers to the extension's static call. With the old lowering it went through the engine's lookup.RushOrder rush; rush.total(2)lowers to$rush->total(2). Without the call-site check inresolve_extension, it lowered to the extension.Moneyitself declares is still refused (Money.net, inherited byCoin). The old check also refusedCoin.cents, a member only a subclass declares.method.rs:181.order?.amount.kind, an extension property read with.below?., lowers to$order === null ? null : Extensions::kind($order->amount), and the analyzer types it as nullable. Withuntested_link's extension check on a plain property link removed, the bridge row lowers toExtensions::kind($order?->amount), which passesnullto the static call. Without the receiver's null-safe null inanalyze_extension_access,title?.slug("-").isBlanktypes asbool, andorder?.amount.kind ?? "none"is refused as a redundant null coalesce.The shadowing rows fail with their code removed:
resolve_extension, the same-namespace row reportedambiguous-object-method-accessforWordsandLoud, andinvalid-return-statementfor the default'sstring.extensions_in, the warm path keptReportaccepted afterLoudarrived, where a clean compile refused it. With the receiver's type left out ofextensions_in, the row "Loud's receiver became string" fails the same way.The review's five rows each fail on the code before them:
stamp_gives_the_size_and_hash_of_a_file_and_none_where_no_file_isstampsapp/report.sharpfromapp/Report.sharp. Inrefusal_absent_input.phpt,Deploy.sharpbesideenvironment.phpwas refused as "out of date (Environment.php changed)", and refused again after a compile beside that file once it was deleted. A realEnvironment.phpis still refused.an_extension_member_is_the_static_call_of_its_method'sExtensions.total(order, 2)row and thethroughTheClasslaw panic with "check_slice refuses the nameLocalbound as Some(Class)".NotFound, andcompile_skips_a_dangling_link_beside_a_file_that_reaches_an_extensionfails with "Orchestrator error: Database error: I/O error". With the bare.sharpcheck removed, the listing's size goes from 24 to 31.TwoandOneeach addranktoAuditedWallet." Withmost_specifictaken out, the bridge row is refused the same way.extension(Money|string loose) { tax() }is refused as "string|Moneyalready declarestax()", and the two refused unions name the whole union instead of its parts.OwnOneandOwnTwo… Import only one of them."Each Lean piece fails its rows with its code taken out:
membersarm that translates extension blocks, every law says "Mago did not translate ShapeMath.doubled, which the law reaches."doublesandtwiceare refused as "a default argument".s?.doubled()is refused as "the overridable method Shape.doubled". Without the null-safe property branch,s?.isFlatcrashes attypes.rs:143.Runs on this branch at 87c5605:
cargo test -p mago-analyzer: 388, 2569 and 610 pass.cargo test -p mago-orchestrator: 144 pass.cargo test -p mago-sharp-bridge -p mago-sharp-lean: 7, 277, 27, 20, 1 and 1 pass.cargo test -p mago-semantics: 375 pass.tests/compile.rsrows for extensions and the dangling link: 3 pass. The rest of that file runs Lean on every row and is left to CI.cargo clippy -p mago-analyzer -p mago-sharp-bridge --all-targets -- -D warningsandcargo fmt --checkare clean.Runs on this branch for the exact-name inputs and patch coverage:
Zend/tests/sharpfolder on a Mac: at be812ec, 175 of 175 pass one at a time and 175 of 175 two at a time. At 4c45bd7, 175 of 175 pass two at a time.cargo test -p mago-sharp-bridge: 7, 277, 27, 1 and 1 pass.cargo test -p mago-analyzer --test sharp: 610 pass. The roottests/compile.rsrows for extensions, the dangling link, staleness and absent inputs: 5 pass.cargo clippy -p mago-analyzer -p mago-sharp-bridge --all-targets -- -D warningsandcargo fmtare clean.mago compileof the 105 engine fixtures finds their inputs in 13.6 to 16.5 ms, against 16 to 50 ms before.unreachable!with its reason:listednever gets an empty list, and a receiver never has no part afterto_non_nullable.Zend/tests/sharp/extensions.phptandextension_inputs.phptpass in six modes: without opcache, opcache in shared memory run twice, priming the file cache, from the file cache, the tracing JIT run twice, and the function JIT.extensions.phptnow also prints9 full 4 emptyfor the call through the class andwallet auditedfor the most specific receiver.sharp/bin/specchecks 180 examples and matches the baseline. Every §26 example passes.mago compilecompiles all 105 engine fixtures.