Repository navigation
feat: class values, Class.of and generic extension blocks complete section 25 - #129
Merged
Merged
Conversation
Problem Nine examples of spec section 25 fail on master, so factories, registries and plugin code that create objects from a class value can't be written. Generics (#102) builds most of the machinery, and nothing recorded what is left, what each rule's state is, or which parts wait on #102. Solution The design note states every line of section 25 with its state on master and on #102's head, both built and run, its mechanism and the code it reuses, with team-lead's decisions and rulings. Left for this Slice: Class.of, the refusal of typeof on a local, Class's own attributes member and the static that clashes with it, new (type)(…) through an exact class value, the required rule's message in section 25's words, how a class value reaches plain PHP, and the harness and setup three examples need. docs/ └── architecture/slices/ └── 25-class-values.md NEW: the rule-by-rule states, the decisions, the rulings, the files and the build order
…uired constructor
Problem
Spec section 25's self-return and required-constructors examples failed.
self-return wrote `{ … return new Self(row); }`, which never declares row
and which the spec checker turns into `throw new Elided() return …`, a parse
error. Both examples declare a DatabaseEntity with a required constructor
that the shared harness can't have, since 13 spec lines write
`new Order()`, so the harness Order refused it and required-constructors
had no constructor to call. No engine test ran new Self(…) or Self.m().
Solution
self-return declares row with `Row row = …;`, the erratum team-lead
approved, and its hidden setup declares the Order it calls. The first
marker of required-constructors is a template whose setup declares the
DatabaseEntity it extends. The harness Element and Order get the required
constructors typeof-type-parameters and typeof-values need, and Order's
takes an optional id so every `new Order()` still compiles. Both examples
pass and leave the list. An engine test pins that new Self(…) creates the
class a static method is called on and Self.m() calls its static, below a
required constructor, a grandchild included.
docs/
└── spec.md self-return's body and setup;
required-constructors' template marker
sharp/
├── baseline/spec/§25/ self-return and required-constructors leave
└── harness/app/
├── Element.sharp a required constructor
└── Order.sharp public required Order(int id = 1)
Zend/tests/sharp/
├── SelfReturn.sharp NEW: a required constructor, new Self, Self.m()
└── self_return.phpt NEW
…says to write it Problem Spec section 25 makes typeof take a type only and gives an object's runtime class as Class.of(value). Class.of was "Method `Class.of` does not exist.", so a developer had no way to name the class of the object a value holds. typeof(order) on a local compiled silently: the binder resolved order to the class Order, because PHP compares class names without case. Plain PHP that takes a class name, as Laravel's make(Foo::class) does, had no row proving a class value reaches it, now that Order::class is removed. Solution Class.of is a static method of the engine class Sharp\Class, as List.wrap is Sharp\List::wrap: the prelude declares it with @template T of object and returns class-string<T>, the type a class value already has, the binder names Class as the standard library's in every .sharp file, and the engine returns the object's class name. typeof of a local in scope is the binding error LocalAsType: "`typeof` takes a type, and `order` is a local: write `Class.of(order)`." A class value is its class name while the code runs, so typeof(GoldBadge) and Class.of(badge) reach a plain PHP Factory::make(string $class) with no conversion written, and the checker reads its class-string<T> to type the object it returns. Decision 41 now records Class.of, as the spec has since 4ad0600. An object with type arguments waits for #102, which stores them. sharp/mago/crates/ ├── names/src/ │ ├── binding.rs BindingError::LocalAsType │ ├── internal/walker.rs walk_in_type_of looks up the locals │ └── lib.rs default_class: Sharp\Class ├── prelude/assets/extensions/sharp.php final class Class { of } ├── semantics/src/internal/checker/ │ └── sharp.rs LocalAsType's message └── names, semantics, analyzer and sharp-bridge tests ext/sharp/ └── sharp.c Sharp\Class::of Zend/tests/sharp/ ├── ClassValues.sharp NEW ├── class_of.phpt NEW: Class.of gives the runtime class ├── class_value_to_plain_php.phpt NEW: plain PHP takes a class value as its name └── harness/Factory.inc NEW: a plain PHP factory of a class name docs/ └── decisions/041-typeof-value.md Class.of(value)
…ules it breaks Problem Spec section 25 lets new Self(…) create any subclass, so every constructor below a required one starts with its parameters and gives each parameter it adds a default. The checker refused a constructor that broke either rule, but with upstream Mago's text: "`Invoice.__construct` must accept at least 1 required parameters like `Entity.__construct`". It named PHP's __construct, stated the count backwards, and said the same for a constructor whose first parameter was the wrong one. Solution For a PHP# constructor below a required one, report_required_constructor_mismatch reports the rule it breaks, in the words a PHP# class is written in, and keeps upstream's issue code: `Invoice`'s constructor adds `clock` with no default, so `new Self(row)` cannot call it: give `clock` a default. `Reordered`'s constructor must start with `Row row`, as `DatabaseEntity`'s does, so `new Self(row)` can call it. The second is the message for a leading parameter that is missing, renamed or of another type. Below a class that is not marked, it names that class's constructor, as `Order`'s for a `Shipment : Order`. sharp/mago/crates/analyzer/ ├── src/statement/class_like/mod.rs report_required_constructor_mismatch └── tests/sharp.rs one row per form
Problem Spec section 25 writes Self only as a return type, and removes PHP's Order::class. Both were refused, but neither said why. `Self copy = new Self();` was a generic "Parse error encountered during parsing", and `Order::class` was "`::` is PHP syntax: PHP# writes static access with `.`", which points at `Order.class`, no form either. Solution The parser reads Self as a local's type, so check_self_type reports "`Self` is only a return type in PHP#." for a local, as it does for a parameter and a property. Before `class`, `::` after a bare name is the parse error ClassNameConstantInSharp: "`Order::class` is PHP syntax: PHP# writes `typeof(Order)`". A lowercase name is a value, since spec section 24 capitalizes every type but the built-in ones, so `order::class` names `Class.of(order)`. sharp/mago/crates/ ├── syntax/src/ │ ├── error.rs ParseError::ClassNameConstantInSharp │ └── parser/internal/ │ ├── expression.rs `::class` after a bare name │ ├── local_declaration.rs Self starts a typed local │ └── statement.rs the same ├── hir/src/lower/error/mod.rs the new error is an unexpected token └── syntax and semantics tests
One file conflicted. crates/syntax/src/parser/internal/statement.rs keeps master's arms, which return each parse's Result as it is, and this branch's `"self"` among the tokens that start a local, so `Self copy = …` still reaches check_self_type. #102 brings Class<T>, new (type)(…) and typeof of a type parameter, so typeof-type-parameters and typeof-values pass with this branch's harness Element and Order and its Class.of, and leave sharp/baseline/spec/§25/. typeof-types, class-members and generic-class-values stay listed until Class's attributes member and the harness PaginatedList land.
…ments Problem Class.of(value) returned the bare class name of any object, so for a Box<Order> it gave a value that neither equals typeof(Box<Order>) nor carries Order: Class.of(box) == typeof(Box<Order>) was false, and new (Class.of(box))() created a Box with its bounds instead of a Box<Order>. The merge with #102 also changed how Mago refuses Class.of(5), and no row passed a Class<Badge> parameter on to plain PHP. Solution For an object of a generic class, Sharp\Class::of spells the object's class with the type arguments #102 stores on it and returns the class value #102 interns for that spelling, the same one typeof(Box<Order>) gives. An object of any other class still gives its class name. An engine test checks the comparison both ways and that new (Class.of(crate))() keeps the type arguments, and a Class<Badge> parameter reaches the plain PHP Factory::make as its class name. Class.of(5) is now refused once, "`5` does not satisfy the bound `Object` of type parameter `T`.", and the analyzer row reads that message. ext/sharp/ └── sharp.c Sharp\Class::of reads the type arguments Zend/tests/sharp/ ├── ClassValues.sharp Crate<TItem>, sameAsTypeof, fromValue ├── class_of.phpt Class.of(crate) equals typeof(Crate<Badge>) └── class_value_to_plain_php.phpt a Class<Badge> parameter reaches plain PHP sharp/mago/crates/analyzer/tests/ └── sharp.rs Class.of(5) is refused once
…oose) included Problem Spec section 25 says new (type)(…) needs a required constructor, as new Self(…) does, whatever the class value holds. #102 refused it for a Class<Loose> parameter but accepted a value that holds exactly one class: new (typeof(Loose))() and `const type = typeof(Loose); new (type)()` compiled with a constructor no subclass has to keep. Solution The required check in analyze_class_instantiation now covers every new through a class value in a PHP# file, a literal one included. Its message says "a class value can hold any subclass of `Loose`", which reads true for both forms. Two rows show the refusal of the exact forms beside the parameter's. sharp/mago/crates/analyzer/ ├── src/expression/instantiation.rs the required check covers an exact value └── tests/sharp.rs rows for typeof(Loose) and a const of it
… section 25 shows
Problem
Spec section 25's generic-class-values example failed on "Cannot find type
`PaginatedList`.": the spec harness had no PaginatedList, so nothing
showed that typeof(PaginatedList<Order>) creates a PaginatedList<Order>
and that new (any)() on an open generic class is refused for its own
reason rather than for the missing class.
Solution
The harness declares PaginatedList<TItem : DatabaseEntity> with a required
constructor whose rows default to [], which new (pages)() and section 11's
plain PHP new PaginatedList($rows) both call. Each annotated line now
gives its annotated result: fresh() and ofOrders() compile, and open()
gets "`PaginatedList` needs its type argument.". The example leaves the
list. Section 11's raw-generic-objects now passes the checker and fails
only when it runs, on its elided bodies, so it stays listed. The design
note records the merge's states.
sharp/
├── baseline/spec/§25/ generic-class-values leaves
└── harness/app/
└── PaginatedList.sharp NEW: PaginatedList<TItem : DatabaseEntity>
docs/
└── architecture/slices/
└── 25-class-values.md the states after the merge with #102
…st<T> items) Problem An extension block took no type parameters, so one block could not serve a receiver of any type argument: `extension<T>(List<T> items)` was a parse error, and `extension(Class<T> type)` was "Cannot find type `T`.". Section 25 needs one, since Class's own members are a standard library extension on every class value. Jordan ruled that a block declares its own type parameters, as C# 14 does. Solution The parser reads type parameters after `extension`, and the binder scopes them over the receiver and every member. Each member runs as a static method whose type parameters are the block's and then its own, so MethodParts merges them and the scanner, the HIR and the bridge read the member as any generic method. The analyzer infers the block's type parameters from the receiver before it compares it, so a `Pair<int, Order>` fits `Pair<TLeft, TRight>` and a `List<int>` misses `TEntity : DatabaseEntity`. Written type arguments fill only the member's own, as `orders.blank<string>()`, and the lowered call carries all of them. Semantics refuses a block type parameter its receiver doesn't use, as C#'s CS9295 does, a member's that reuses a block's name, and `in` or `out` on one. The fingerprint hashes them. Spec section 26 states the rule, with the generic-extensions and extension-unused-type-parameter examples. A type parameter can't be a Map key today, since a bound is a class or an interface, so the two-parameter row is `Pair<TLeft, TRight>` and the Map row is `Map<string, List<TValue>>`. docs/ └── spec.md section 26: a block's type parameters sharp/mago/crates/ ├── syntax/src/ │ ├── cst/cst/class_like/extension.rs Extension.type_parameters │ ├── cst/node.rs, walker/mod.rs visit and walk them │ └── parser/internal/class_like/ │ └── extension.rs extension<T>(…) ├── names/src/ │ ├── binding.rs a block's type parameters come first │ └── internal/walker.rs a block scopes its type parameters ├── semantics/src/internal/checker/ │ └── sharp.rs check_extension_type_parameters ├── analyzer/src/ │ ├── resolver/extension.rs fits infers a block's type parameters │ ├── invocation/template_result.rs seed_extension_type_arguments │ └── expression/call/ written type arguments reach a member ├── sharp-bridge/src/lower.rs, types.rs a generic member's call carries them ├── fingerprint/src/class_like/mod.rs hash a block's type parameters └── syntax, names, semantics, analyzer, sharp-bridge and fingerprint tests
… Class's member wins Problem Spec section 25 gives every class value Class's own member, `attributes<TAttribute>()`, which wins over a static of the class the value holds, and refuses a static named like it. `type.attributes<Listen>()` was "Method `Order.attributes` does not exist.", and `public static string attributes()` compiled, so typeof-types and class-members failed. Solution The standard library's Sharp.ClassMembers declares `extension<T>(Class<T> type)` with `attributes<TAttribute>()`, PHP# over ReflectionClass::getAttributes(…, IS_INSTANCEOF) and newInstance(), so the list holds the attributes the class itself declares, subclasses of TAttribute included. It is imported by default, as every class directly in Sharp is. is_class_member decides what Class's members are: what a standard library extension adds to a class value. The class value branches of a read and a call leave those out through class_value_static_classes, so `type.attributes` resolves the extension, while `type.defaultTag()` still calls the held class's static. A PHP# static method, static property, constant or enum case named like one is refused, as TypeScript's error 2699: "`attributes` is a member of `Class`, so `type.attributes` on a class value never reaches this static. Rename it." An engine test runs it. Both examples pass, so sharp/baseline/spec/§25/ is empty. sharp/composer/library/Sharp/ └── ClassMembers.sharp NEW: extension<T>(Class<T> type) sharp/mago/crates/analyzer/ ├── src/resolver/extension.rs is_class_member ├── src/expression/access/mod.rs class_value_static_classes ├── src/expression/call/mod.rs a call through a class value uses it ├── src/statement/class_like/mod.rs report_statics_named_like_class_members └── tests/sharp.rs Class's member wins; the clash rule Zend/tests/sharp/ ├── ClassValues.sharp Listen, Loud, attributes on Badge └── class_attributes.phpt NEW sharp/baseline/spec/§25/ typeof-types and class-members leave docs/architecture/slices/ └── 25-class-values.md decisions 3 and 4 as built
Two files conflicted, and each keeps both sides. ext/sharp/sharp.c: master replaced the old Sharp\Set and its `from` with Sharp\Map and Sharp\Set tables, at the place this branch added Sharp\Class. The merge keeps Sharp\Class and its `of` after Sharp\List, drops the old Set's lines that only this branch still held, and registers Sharp\Class before master's Sharp\Struct, tables and Crossing. crates/semantics/src/internal/checker/sharp.rs: master's check_struct_declaration and this branch's check_extension_type_parameters were added at one place. Both stay whole, the extension check first.
…nference Problem The merge with structs (#123) compiled no analyzer: master's infer_unfixed_templates no longer takes the target's dialect, and fits in resolver/extension.rs still passed `Dialect::Sharp`, so a generic extension block's receiver could not be matched at all. Solution fits calls infer_unfixed_templates as master declares it, and the Dialect import it no longer needs is gone. The analyzer and bridge suites, the class value engine tests and every spec example pass on the merge. sharp/mago/crates/analyzer/src/ └── resolver/extension.rs fits drops the dialect argument
Problem patch-coverage found five lines of this branch that no test ran: a receiver that names a class beside its block's type parameter, a refused receiver on a block with type parameters, the impossible arm after get_template_types, and two branches for a parameter without a type, which only a file the parser refused declares. Solution Two semantics rows run the first two: `extension<TItem>(Function<TItem(Order)> make)` compiles, and `extension<T>(List<T> items, int count)` gets only the receiver's refusal. The arm after get_template_types is unreachable! with its reason, since that function gives only type parameters and their class values. The parser builds an untyped parameter after its error, so the language server can reach the other two: fits keeps the is_some_and chain it had before this branch, so such a receiver fits nothing, and the required constructor's message reads such a parameter as `Any?`. sharp/mago/crates/ ├── analyzer/src/ │ ├── invocation/template_result.rs unreachable! after get_template_types │ ├── resolver/extension.rs fits as one chain again │ └── statement/class_like/mod.rs an untyped parameter reads as Any? └── semantics/tests/sharp.rs two rows
… type Problem The review of #129 found section 25 rules that fail: - `type.attributes<int>()` compiled and threw while the code ran. - A subclass below a `required` constructor was compared with its parent's constructor, so `Narrowed`, `DroppedDefault` and `Shipment` got wrong messages or wrong refusals. - A class value was decided by how its expression was written, so `Class.of(order).defaultTag()` and `this.kept.defaultTag()` were refused, and an imported `string` extension named `attributes` took over `Class`'s member. - A user's `extension<T>(Class<T> type)` compiled and could never be called. - `typeof(int)`, `typeof(List<Order>)`, `typeof(Map<string, int>)` and `typeof(Set<int>)` failed. - `names.saved` outside `TEntity`'s bound, a union receiver, `Self::class` and `Demo.Order::class`, and a static named `Attributes` got messages that read as upstream PHP or named the wrong thing. Solution - `Object` is a bound, as C#'s `where T : class` and TypeScript's `T extends object` are, and `attributes<TAttribute : Object>()` uses it. - `required_constructor_class` finds the nearest ancestor whose own constructor is written `required`, and the message names it and the parameters the shortest `new Self(…)` leaves without a default. - One rule decides a class value by the receiver's analyzed type, whatever expression gives it, and `Class`'s members by that receiver type. - Semantics refuses an extension of `Class<…>` outside the standard library. - `TypeOf` holds a type, `TypeOf::type`, so `typeof` takes any one type: a class, a built-in type, a collection and `Self`, which is PHP's `static::class`. A type that is no class runs as the engine's `SHARP_TYPE_OF` of its text, as `typeof(TItem)` does. A nullable or union type is not supported yet. `typeof(int)` no longer lexes as a cast, and PHP# reads `Int`, `Float`, `Bool` and `String` as classes, as `(Int)` is. - A receiver outside a block type parameter's bound names the bound, a union of one generic class misses a method once, `Self::class` and `Demo.Order::class` point to `typeof(Self)` and `typeof(Order)`, and the clash message quotes the static's own name. sharp/mago/crates/ ├── syntax/src/ TypeOf.type; typeof( never starts a cast; scalar │ names lowercase only; the name before ::class ├── names/src/ walk_in_type_of keeps only the local rule ├── semantics/src/ Object bound; Class extensions; typeof's type ├── codex/src/scanner/ a required constructor's flag ├── analyzer/src/ class values by type; required ancestor; bound │ and union messages; typeof of any type └── sharp-bridge/src/ typeof of any type and of Self sharp/composer/library/Sharp/ClassMembers.sharp attributes<TAttribute : Object> Zend/tests/sharp/ static calls through Class.of and a field; typeof forms docs/ spec sections 11 and 25; slice notes 11 and 25
Problem patch-coverage found two lines of `access/mod.rs` that no test ran: the analysis of a type parameter's object before a static method value is read through it, and the restore of a class value's type after `?.` when it has none, which cannot happen. Solution A row reads `TItem.make` without a call, a `Function<int()>`. A class value is found by its object's type, so `analyze_through_class_value` takes that type as given, and a missing one is `unreachable!`. sharp/mago/crates/analyzer/ ├── src/expression/access/mod.rs the object's type is given └── tests/sharp.rs TItem.make as a function value
…luded
Problem:
The spec says `typeof(X)` is typed `Class<X>` for any one type `X`, but
`typeof(int?)` and `typeof(int|string)` were "not supported yet", and a
written `Class<int>`, `Class<int?>` or `Class<int|string>` was refused, so
a developer could not keep or pass the class value of a type that is no
class.
Solution:
A class value's type holds a whole type: `TClassLikeString::OfType`'s
constraint is a `TUnion`, so `typeof(int|string)` is one
`Class<int|string>`, as it runs as one value. `Class<X>` fits `Class<Y>`
when `X` fits `Y`. A `Class<T>` parameter given a `Class<int|string>`
infers `T` as `int|string`. `new (t)()` of a `Class<int>` is "`t` is a
`Class<int>`, and only a class's `Class` creates objects." PHP's
`class-string<A|B>` keeps one class string per class, and the extension
protocol sends a class value of several types as `class-string`, since
the SDK's class-like string holds one type. The invocation resolver
resolves only a class string of a written type, the one kind that names a
parameter.
sharp/mago/crates/
├── codex/src/
│ ├── ttype/atomic/scalar/class_like_string.rs OfType holds a TUnion
│ ├── ttype/comparator/class_string_comparator.rs Class<X> fits Class<Y> when X fits Y
│ ├── scanner/ttype.rs Class<int|string> holds that type
│ ├── ttype/template/inferred_type_replacer.rs Class<T> of a non-class type keeps it whole
│ └── ttype/{union,expander,atomic/mod,atomic/derived/new,template/definition_type_replacer}.rs
├── analyzer/src/
│ ├── expression/type_of.rs typeof of any one type is one Class
│ ├── expression/instantiation.rs new of a Class<int> is refused in PHP#'s words
│ ├── invocation/template_inference.rs Class<T> infers T from Class<int|string>
│ ├── invocation/resolver.rs resolves only a class string of a written type
│ ├── external/protocol.rs a class value of several types goes as class-string
│ └── {invocation/analyzer,reconciler/assertion_reconciler,resolver/class_name,utils/names}.rs
├── semantics/src/internal/checker/sharp.rs both refusals removed
└── sharp-bridge/src/lower/types.rs spells Class<int|string> and Class<int?>
Zend/tests/sharp/{ClassValues.sharp,class_of.phpt} unions, nullables and a Class<int|string> parameter
docs/spec.md typeof(int|string) example
docs/architecture/slices/25-class-values.md ruling 5
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
… 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
…es only its own text from plain PHP
Problem
- `t.MAX`, `t.make()` and `t.count = 1` on a `Class<int>` got upstream's
"non-object type" message, then a `null` or `Any?` cascade.
- The engine let any string into a `Class<int>` or `Class<int|string>`
parameter, so plain PHP could pass `"Classes\Badge"` into PHP#.
Solution
- A static read, call or write through a class value of a type that is no
class is refused once: "`t` is a `Class<int>`, and only a class's `Class`
has statics." The access is a refused value, so nothing reports again.
`new (t)()` shares the predicate and the report.
- The bridge sends `Class<int|string>` as the parameter's entry check, and
the engine takes only the text `typeof` gives that type. `Class<Any>`,
`Class<Object>` and an unresolved type parameter still take any string.
Files
ext/sharp/sharp.c sharp_class_value_is compares the text
sharp/mago/crates/
analyzer/src/
resolver/class_name.rs holds_no_class, report_class_value_of_no_class
resolver/{method,property}.rs a class value of no class is a class value
expression/access/mod.rs refuse_statics_of_no_class
expression/access/property_access.rs read
expression/call/method_call.rs call
expression/assignment/property_assignment.rs write
expression/instantiation.rs new, through the shared report
analyzer/tests/sharp.rs rows for the read, call and write
sharp-bridge/src/lower/types.rs checked_text sends the type
sharp-bridge/tests/lower.rs row for the entry check
Zend/tests/sharp/{ClassValues.sharp,class_of.phpt} rows for plain PHP's calls
docs/architecture/slices/25-class-values.md the two rulings
Problem
- The engine took only the exact text `int|string` into a `Class<int|string>`
parameter from plain PHP. The checker lets `Class<int>` fit
`Class<int|string>`, so a `typeof(int)` that PHP# gave to plain PHP was
refused when plain PHP passed it back.
Solution
- `sharp_class_value_fits` reads the value as a type, a class name as its
dotted text, and takes it when it fits the parameter's type, through
`sharp_type_argument_takes` with `'+'` variance, as the checker does.
`"int"`, `"string"` and `"int|string"` enter, and `"Classes\Badge"`,
`"float"` and the unsorted `"string|int"` are refused. A
`Class<(Badge|int)?>` takes `"Classes\GoldBadge"`.
Files
ext/sharp/sharp.c sharp_class_value_fits
Zend/tests/sharp/{ClassValues.sharp,class_of.phpt} rows for each value plain PHP passes
docs/architecture/slices/25-class-values.md ruling 2
heyJordanParker
added a commit
that referenced
this pull request
Oct 15, 2026
…owing Problem: #129 landed on master, and both sides changed the imports of the call analyzer's dispatch. Solution: keep both imports. Master's `seed_extension_type_arguments` and this branch's `NamedCall` sit side by side, and git merged the dispatch body itself: master's dropped class-value arms and the `false` argument of `analyze_static_method_call` sit beside this branch's function call hooks. sharp/mago/crates/analyzer/src/expression/call/ └── mod.rs imports seed_extension_type_arguments and NamedCall
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Spec section 25, referring to classes, had nine failing examples. A developer couldn't name the runtime class of an object (
Class.of(order)), read a class value's attributes (type.attributes<Listen>()), or rely on the rules that keepnew (type)(…)andnew Self(…)safe. Factories, registries and plugin code that create objects from a class value couldn't be written as the spec shows them.Solution
Class values.
Class.of(value)is a static method of the engine classSharp\Class, asList.wrapisSharp\List::wrap. It returns the object's class, and for an object of a generic class the interned class value with its type arguments, soClass.of(box) == typeof(Box<Order>)holds andnew (Class.of(box))()keeps them.typeof(order)on a local is a binding error that namesClass.of(order). A class value reaches plain PHP that takes a class name, such as amake(string $class)factory, with no conversion written.A class value is decided by its type. Any expression whose analyzed type is a class value reaches the statics of the class it holds:
Class.of(order).defaultTag(),this.kept.defaultTag()through a field,this.maybe?.defaultTag(), and static field reads and writes through them.typeoftakes any one type, as C#'s does.typeof(int),typeof(int?),typeof(int|string),typeof(List<Order>),typeof(Map<string, int>)andtypeof(Set<int>)give the class value of that type, which the engine spells as it spellstypeof(TItem).typeof(Self)is the class a static method is called on, PHP'sstatic::class.A class value holds any one type.
typeof(int|string)is oneClass<int|string>, and a field, parameter or local may be writtenClass<int>,Class<int?>orClass<int|string>.Class<X>fitsClass<Y>whenXfitsY, soClass<int>fitsClass<int|string>and not the reverse, and aClass<T>parameter given aClass<int|string>infersTasint|string. Only a class'sClasscreates objects and has statics, sonew (t)()of aClass<int>is "tis aClass<int>, and only a class'sClasscreates objects.", andt.MAX,t.make()ort.count = 1is "tis aClass<int>, and only a class'sClasshas statics.", once. A value entering PHP# is checked where it enters, as the checker checks it, so aClass<int|string>parameter takes from plain PHP the class value of any type that fitsint|string,"int","string"or"int|string", and plain PHP passing"Classes\Badge"or"float"there gets the engine's type error. PHP'sclass-string<A|B>keeps one class string per class. An external analyzer extension receives a class value of several types as theclass-stringit is while the code runs, because the SDK's class-like string holds one type.Class's own member.attributes<TAttribute : Object>()is a standard library extension,Sharp.ClassMembers, on every class value. It returns the attributes the class itself declares, subclasses ofTAttributeincluded, andattributes<int>()is a compile error.Objectis a bound, as C#'swhere T : classand TypeScript'sT extends objectare. Through a class valueClass's member wins over a static of the held class and over any other extension of the name. A PHP# static method, static property, constant or enum case namedattributesis refused, as TypeScript's error 2699, and only the standard library extendsClass.Extension blocks with type parameters.
Class's member needsextension<T>(Class<T> type), so an extension block now declares its own type parameters, as C# 14 does:extension<TItem>(List<TItem> items). A call infers them from its receiver. A member's own type parameters come after them, and a call writes only those. A block type parameter the receiver doesn't use is a compile error. A receiver outside a bound gets "stringis outsideTEntity's boundDatabaseEntity, soList<string>has nosaved." Spec section 26 states the rule with two new examples.Rules in section 25's words.
new (type)(…)needs arequiredconstructor whatever the value holds,typeof(Loose)included.requiredone is compared with the nearest ancestor whose own constructor is writtenrequired, and gets "must start withRow row, asDatabaseEntity's does" or "givesclockno default, sonew Self(row)cannot call it".Self copy = …gets "Selfis only a return type in PHP#."Order::class,Demo.Order::classandSelf::classget "PHP# writestypeof(Order)" ortypeof(Self).Int,Float,BoolorStringtype as the class of that name, as it reads(Int).Spec text. The
self-returnerratum declaresRow row = …;, with a hidden setupOrder, andrequired-constructors' first marker is a template with its ownDatabaseEntity. Decision 041 now recordsClass.of.The design note is
docs/architecture/slices/25-class-values.md.Harness changes
sharp/harness/app/Element.sharp: the constructor isrequired.sharp/harness/app/Order.sharp: gainspublic required Order(int id = 1) { }, with an empty body, sonew (type)(id)compiles and everynew Order()still does.sharp/harness/app/PaginatedList.sharp: new,PaginatedList<TItem : DatabaseEntity>with arequiredconstructor whose rows default to[].No harness class makes an example pass by a stub. Each one declares what its example names.
Verification
sharp/bin/spec: "Checked 185 examples, ignored 1, and 59 fail", and the failures matchsharp/baseline/spec.sharp/baseline/spec/§25/is empty, and all nine entries are removed. Section 11'sraw-generic-objectsnow passes the checker and fails only when it runs, on its elided bodies, so it stays listed.cargo fmtandclippy -D warningsare clean on the changed crates, and the whole workspace builds.sharp/bin/test --differentialpasses.class_attributes.phpt,class_of.phpt,class_value_to_plain_php.phptandself_return.phptpass in all 22 modes ofsharp/bin/test --opcache --repeat --passes.class_of.phptruns a static call throughClass.of(badge), through a field and throughtypeof(Self), and gives the class values ofint,List<Badge>,Map<string, int>andSet<int>, and ofint?,int|stringand(Badge|int)?, andClass<int|string>,Class<int>andClass<(Badge|int)?>parameters that plain PHP calls with class values that fit and ones that don't. All 266 tests inZend/tests/sharppass.mago analyzeover feat: PHP# generics, checked and carried at runtime (spec section 11, R1 to R5) #102's plain PHP corpus (the analyzer's case files, phpunit with its vendor tree, a@templateandclass-string<T>file) plus a file ofget_class,new static,class-string<T>factories andgetAttributesprints 17,818 lines from master753cb0120cand from this head. The sorted outputs are identical, with no panic.Completes: §25