Skip to content

Run section 9's constructors and init on the engine - #110

Merged
heyJordanParker merged 11 commits into
masterfrom
feat/slice-constructors
Oct 13, 2026
Merged

heyJordanParker merged 11 commits into
masterfrom
feat/slice-constructors

Conversation

@heyJordanParker

@heyJordanParker heyJordanParker commented Oct 12, 2026 •

Copy link
Copy Markdown
Owner

Completes: §9.1

Problem

The engine ran no test of section 9. mago-sharp compiles : super(…), named constructors (#161) and init (#169). Nothing showed the engine running them, a plain PHP caller using them, or reflection seeing them.

php-sharp still pinned Mago 625c278, which predates all three. So the four section 9.1 spec examples stayed in sharp/baseline/spec. The constructors note still listed open questions that the Architect has since ruled on.

Solution

Mago now lives in sharp/mago/, and #114 pulled it to mago-sharp 3cc39cc, which holds : super(…), named constructors and init. This branch merges master, so it runs on that Mago and needs no pin of its own.

constructors.phpt runs each row from plain PHP, three rounds so the JIT compiles each one, and passes in all four opcache modes:

  • new SalesReport(1) runs the plain PHP Report's constructor through : super(id).
  • Artifact::load() writes new Artifact.fromJson(json) in PHP#, and plain PHP calls Artifact::fromJson($json). Both create equal objects, and super.describe() inside the named constructor runs on the new object ("entity tea"). Artifact overrides describe(), so a super.m() dispatched as $this->m() prints "artifact tea" and fails the row.
  • LegacyArtifact::fromJson('x') returns a Demo\Artifact. new LegacyArtifact(…) returns a Demo\LegacyArtifact whose manifest->name and name are what Artifact's main constructor and its : super(…) set, so : super("") fails the row.
  • The braced guard clause in Gate's constructor throws InactiveTenant for an inactive tenant and passes an active one.
  • Label.shouting('hi') overwrites the init property text that the main constructor set, and HI is read back.
  • Reflection shows getConstructor() as __construct, with the promoted $manifest and a readonly manifest property. getMethod('fromJson') is public, static and not a constructor, takes string $json, returns Demo\Artifact and carries the Demo\Retry attribute.

A constructor without : super(…) has no engine row. The checker refuses it with missing-super-call, which mago-sharp's tests prove.

The init boundary

init lowers to protected(set). On the engine:

  • Plain PHP outside the class cannot write it: $label->text = 'b' throws Error: Cannot modify protected(set) property Demo\Label::$text from global scope.
  • A plain PHP subclass can write it after the object is created. LegacyLabel::rename('b') sets text to b, because PHP has no set visibility that ends when the object is created. This is the known boundary. The checker refuses the same write in a PHP# subclass.

Guard 1

#114 already moved the four §9.1 examples, constructor-call-this, named-constructors, set-once and super-call, out of sharp/baseline/spec/, with the Mago that runs them. So this pull request changes no list entry: sharp/bin/spec --base origin/master reports "0 entries join sharp/baseline/spec, 0 leave it." sharp/bin/spec --completes on this body reports "§9.1: all 4 checked examples pass."

Completes: names §9.1 only. §9 parameter-members still fails, because its example writes via Tracked, and via waits on section 6.4. sharp/bin/spec --completes with Completes: §9 prints §9 still has 1 entries in sharp/baseline/spec: parameter-members.

The note

The note's open questions become the "Rulings" section, with the Architect's answers:

Decisions 2, 6 and 7, the named-constructor lowering (now a closure bound with Closure::call), the PHP a plain caller sees, and the PR 1 and PR 4 lines change to match.

Files

docs/architecture/slices/09-constructors.md  the rulings replace the open questions; decisions 2, 6 and 7, the lowering and the PR 4 line match them
Zend/tests/sharp/
├── Constructors.sharp                       SalesReport, Artifact with fromJson and its own describe(), the braced guard clause, Label with an `init` property
├── constructors.inc                         the plain PHP subclasses LegacyArtifact and LegacyLabel; lowercase, as it is no opcode twin
├── constructors.phpt                        every row, run from plain PHP, plus reflection of Artifact
└── harness/Report.inc                       the plain PHP base class SalesReport extends

Verification

  • sharp/bin/test --opcache --repeat --passes Zend/tests/sharp/constructors.phpt passes in every mode, all 16 optimizer passes and both JITs included.
  • sharp/bin/test --opcache --repeat --census --differential --spec: 173 of 173 tests pass in each mode, the census and differential pass, and the spec results equal sharp/baseline/spec.
  • sharp/bin/test --passes: 173 of 173 under each optimizer pass alone and both JITs.
  • After merging master, with Mago at 3cc39cc, sharp/bin/test --census --differential --spec on macOS: 174 of 174 tests pass, the census and differential pass, 17 of 17 self-test examples, and the spec run matches sharp/baseline/spec/.

Problem:
Section 9 is the fourth most-hit gap to v1. A subclass cannot feed its
parent: `: super(row)` is four generic parse errors, and a subclass
constructor without it compiles and never runs the parent's constructor.
Named constructors are refused. The spec's own guard clause,
`if (!tenant.active) throw new InactiveTenant(tenant);`, is refused as a
statement without braces. `lazy`, a computed parameter and a second
constructor get generic parse errors or PHP's duplicate-method message.

Solution:
The note records every rule of section 9 with its observed state and its
mechanism, the public names the Slice adds, and the PR order: three
mago-sharp PRs and one php-sharp PR. Its Rulings section holds the interim
refusals for the four open questions, so the Slice refuses instead of
guessing until the Architect answers them.

docs/architecture/slices/
└── 09-constructors.md   <- added: section 9's design, rulings and PR order
Problem:
The section 9 design note said the Slice adds no parse error variant and
uses "the existing generic error with a message". No such error exists:
the generic parse error prints "Parse error encountered during parsing",
and every PHP# parse error with its own message has its own variant.
team-lead approved two variants, and PR 1 adds ModifierKind::Lazy to the
HIR, which the tree did not list.

Solution:
The public names tree lists ParseError::ComputedParameterInSharp (PR 1),
ParseError::ConstructorInitializerInSharp (PR 2) and ModifierKind::Lazy,
and the "Not added" line names both variants and their precedent.

docs/architecture/slices/
└── 09-constructors.md   <- the two parse error variants and ModifierKind::Lazy
Problem:
The note gave the computed-parameter and `lazy` errors as "A constructor
parameter cannot be …". The parser and check_slice raise both on every
PHP# parameter, method and lambda parameters included, so the text was
false where it fired. The note also did not say that `lazy` stays a name
before `(`, `)`, `,` or `=`.

Solution:
- The computed-parameter error reads "A parameter cannot be a computed
  property: a computed property has no incoming value to receive.", at the
  `=>`, team-lead's ruling on #155's review.
- The `lazy` error reads "A parameter cannot be `lazy`: …", as PR 1 builds
  it. A parameter with only `lazy` is no promoted property, and
  `(lazy) => lazy` keeps compiling.

docs/architecture/slices/
└── 09-constructors.md    <- the two parameter errors, under "`lazy`, computed properties and `static`"
Problem: decision 3 put the name of `new Artifact.fromJson(…)` on an
`Instantiation.constructor` field the parser fills. The parser cannot fill
it: `new Order.Paid(…)` (a nested event, section 15) and
`new Artifact.fromJson(…)` (a named constructor) read the same, and only the
class's declaration, possibly in another file, tells them apart.

Solution: both parse as a plain `Instantiation` of the dotted name, the
binder resolves it to `App\X\Y`, and the analyzer's `new` path creates the
type `App\X\Y` when one exists and calls the named constructor `Y` of `X`
otherwise, recording that static method as the call target. The bridge,
the effects check and the Lean translation read the record. The PR that
lands second adds the clash error with its test.

docs/architecture/slices/09-constructors.md
├── Decisions, 3        <- the dotted parse and the analyzer's decision
├── Rulings             <- team-lead's replacement of the field, the clash error
├── 9.1 mechanism       <- parser, names, analyzer and bridge bullets
├── public names tree   <- ConstructorName and Node::ConstructorName dropped,
│                          the dotted parse, Types::named_constructor added
└── PR 3                <- the dotted `new` parse instead of ConstructorName
Problem: fe209c4 moved decision 3's choice behind `new X.Y(…)` to the
analyzer, so that `new Order.Paid(…)` could create a nested type. The
Architect ruled that nothing nests, and section 23 makes `.` in code
always member access, so the parser can tell `new Artifact.fromJson(…)`
calls a named constructor.

Solution: decision 3 is back to the parser's `Instantiation.constructor`
field, with section 23 as its reason. The analyzer's type-first decision,
the clash error and `Types::named_constructor` leave the note.

docs/architecture/slices/09-constructors.md
├── Decisions, 3        <- `Instantiation.constructor`, and the section 23 reason
├── Rulings             <- the replacement and the clash error removed
├── 9.1 mechanism       <- parser, names, analyzer and bridge bullets as before
├── public names tree   <- ConstructorName and Node::ConstructorName back
└── PR 3                <- ConstructorName back
Problem: the note listed `init` among the accessors section 9 leaves
"not supported yet", so a named constructor could not set the
`init` properties section 9.1 names, and the note did not say where
the object initializer and `with` set them.

Solution: PR 5 builds `init` whole, with C#'s write rule and the
`protected(set)` lowering, and states the plain PHP subclass boundary.
The object initializer (section 16) and `with` (section 10) set
`init` properties in their own Slices.

docs/architecture/slices/09-constructors.md
  <- 9.1: the `init` write rule, the get-only help, sections 16 and 10
  <- public names: PropertyHookList::setter, MetadataFlags::INIT
  <- PRs: PR 5, `init`
  <- refused list: `init` leaves it
Problem: the engine ran no test of section 9. `: super(…)`, named
constructors and `init` compiled in mago-sharp, but nothing showed the
engine running them, a plain PHP caller using them, or reflection seeing
them. The pinned Mago commit predated all three, so the section 9.1
spec examples still sat in sharp/baseline/spec. The constructors note
still held the open questions the Architect has since ruled on.

Solution: pin Mago to master c3a2b5a, which holds `: super(…)`, named
constructors and `init`. constructors.phpt runs each section 9 rule
from PHP and checks what reflection shows. The four section 9.1
examples pass and leave the baseline, as do five examples from other
sections that the new pin fixes. The note records the Architect's
rulings: `: super(…)` always written, a get-only property set once,
braces always, and `this` refused in `: super(…)`.

docs/architecture/slices/09-constructors.md  the rulings replace the open questions; decisions 2, 6 and 7, the lowering and the PR 4 line match them
ext/sharp/sharp_unit.h                       SHARP_MAGO_COMMIT moves to c3a2b5a
sharp/baseline/spec                          §9.1 constructor-call-this, named-constructors, set-once and super-call pass; so do §12 collection-read-methods and index-rules, and §15 extern-event, extern-event-effects and standalone-event
Zend/tests/sharp/
├── Constructors.sharp                       SalesReport, Artifact with fromJson, the braced guard clause, Label with an `init` property
├── Constructors.inc                         the plain PHP subclasses LegacyArtifact and LegacyLabel
├── constructors.phpt                        every row, run from plain PHP, plus reflection of Artifact
└── harness/Report.inc                       the plain PHP base class SalesReport extends
Problem: in Zend/tests/sharp a capitalized Name.inc is the opcode twin
of Name.sharp, which opcodes.phpt compares. Constructors.inc is not a
twin: it holds the plain PHP subclasses constructors.phpt uses. Its name
claimed a role it doesn't have.

Solution: rename it constructors.inc, as property_override.inc names the
plain PHP side of its test.

Zend/tests/sharp/
├── constructors.inc                         renamed from Constructors.inc
└── constructors.phpt                        requires constructors.inc
docs/architecture/slices/09-constructors.md  the names tree and the PR 4 line use the new name
@heyJordanParker

heyJordanParker commented Oct 12, 2026 •

Copy link
Copy Markdown
Owner Author

Review verdict: CHANGES NEEDED

Head 8b9b4a29649ea7590bfe9b43fd9427bd4853bfec, Mago pinned at master c3a2b5af865c1661898b00de55130b5800c28411.

8b9b4a2964 adds one commit after a197f9cae41ba6a949e57b0fd2c4a174a8abe813, the head I built and probed. git diff -M --stat a197f9cae4 8b9b4a2964 shows only the rename Constructors.inc → constructors.inc (100% similar), the matching require line in constructors.phpt, and the note's file tree and PR 4 line. The Mago pin, Constructors.sharp and every --EXPECT-- line are unchanged, so each finding below holds at 8b9b4a2964. CI run 38276041505 passes on 8b9b4a2964 (LINUX and MACOS included).

I built the engine (sharp/bin/build) and the pinned mago (sharp/bin/test's cargo install) in a scratch worktree. Every probe below ran on that engine, plain (php -n) and under the tracing JIT (-d opcache.enable_cli=1 -d opcache.jit=tracing -d opcache.jit_buffer_size=32M -d opcache.jit_hot_func=1 -d opcache.jit_hot_loop=1 -d opcache.jit_hot_return=1 -d opcache.jit_hot_side_exit=1). The function JIT gave the same output too.

Changes needed

1. : super() skips a PHP# parent whose constructor PHP# generates (compiles, runs wrong)

A PHP# class with a non-constant initial value and no written constructor gets a __construct() from Lowering::class. A subclass that writes : super() never runs it. The parent's property stays uninitialized, and the first read throws. The checker accepts all three forms.

// probe/InitParent.sharp
namespace P;

class InitParent
{
    public string stamp { get; set; } = strtoupper("p");
}
// probe/Edges.sharp
class InitParentChild : InitParent
{
    public InitParentChild() : super() { }
}

class LocalInitParent                    // the same, with the parent in the same file
{
    public string stamp { get; set; } = strtoupper("q");
}

class LocalInitParentChild : LocalInitParent
{
    public LocalInitParentChild() : super() { }
}

class GeneratedGrandchild : InitParent   // no constructor, its own initial value
{
    private string extra = strtoupper("e");

    public string both() => this.stamp + this.extra;
}
// probe/NoSuperInitParent.sharp
class NoSuperInitParent : InitParent
{
    public NoSuperInitParent() { }
}

mago compile accepts every file: INFO Compiled 29 PHP# files into .sharp/. No missing-super-call for NoSuperInitParent.

Today's output, plain and tracing JIT alike:

(new P\InitParent())->stamp                → string(1) "P"
(new P\InitParentChild())->stamp           → Error: Typed property P\InitParent::$stamp must not be accessed before initialization
(new P\LocalInitParentChild())->stamp      → Error: Typed property P\LocalInitParent::$stamp must not be accessed before initialization
(new P\GeneratedGrandchild())->both()      → Error: Typed property P\InitParent::$stamp must not be accessed before initialization in Edges.sharp on line 31

Reflection shows the parent's constructor exists on the engine: (new ReflectionClass(P\InitParent::class))->getConstructor()->getDeclaringClass()->getName() is P\InitParent.

It must print "P", "Q" and "PE", and NoSuperInitParent must be refused with missing-super-call, because InitParent has a constructor on the engine.

Cause: Lowering::method and Lowering::class in crates/sharp-bridge/src/lower.rs emit parent::__construct(…) only when Types::parent_constructor finds one. That calls CodebaseMetadata::get_parent_constructor, and the codex never registers the __construct() the bridge makes for initial values.

// crates/sharp-bridge/src/lower.rs @ c3a2b5af8, Lowering::method
if let Some(initializer) = &method.initializer
    && self.types.parent_constructor(self.class).is_some()
{
    let arguments = self.arguments(&initializer.argument_list, &[]);
    statements.push(self.parent_construct(self.line(initializer), arguments));
}

Fix, in mago-sharp: the codex registers the constructor the bridge makes, a public __construct() without parameters, for a .sharp class with a non-constant initial value and no constructor, as walk_in_named_constructor registers the static method a named constructor lowers to. Then get_parent_constructor finds it from any file, : super() and the generated constructor call it, and missing-super-call covers NoSuperInitParent. php-sharp then re-pins and adds a row to constructors.phpt: a subclass with : super() of a class whose only constructor comes from a non-constant initial value, reading the parent's property.

2. The braceless body still compiles at the pinned Mago (missing refusal, false message)

The note's "Rulings" and "Braces" parts and the PR body say braces are always required, through mago-sharp #173. #173 is open and unmerged (gh pr view 173 --repo heyJordanParker/mago-sharp → "state":"OPEN","mergeCommit":null), and c3a2b5af8 is the head of mago-sharp master. So the pinned checker still carries PR 1's guard-clause exception.

// refuse/BracelessCtor.sharp
class BracelessCtor
{
    public BracelessCtor(public bool active { get; })
    {
        if (!active) throw new InvalidArgumentException("inactive");
    }
}

// refuse/BracelessNamed.sharp
class BracelessNamed
{
    public BracelessNamed(public int balance { get; }) { }

    public BracelessNamed.checked(int balance) : this(balance)
    {
        if (balance < 0) throw new InvalidArgumentException("negative");
    }
}

// refuse/BracelessForms.sharp, inside a static method
if (early) return -1;
while (total < limit) total++;

Today's mago compile reports nothing for either guard clause, and both run:

new P\BracelessCtor(false)        → InvalidArgumentException: inactive in BracelessCtor.sharp on line 9
P\BracelessNamed::checked(-1)     → InvalidArgumentException: negative in BracelessNamed.sharp on line 11

For the while, it prints a message that calls a ruled-out form "not supported yet", and it states the old exception:

refuse/BracelessForms.sharp:9:9: error[semantics]: This statement without braces is not supported yet in PHP#.
 = PHP# writes the body of `if`, `else` and each loop as a block in braces, except an `if` without `else` whose body is one `return` or `throw`.

if (early) return -1; on line 8 gets no error.

It must refuse every braceless body of if, else and each loop once, with "PHP# writes the body of if, else and each loop in braces." and the braced form as help, as ruling 3 and the note say.

Fix: merge mago-sharp #173, then re-pin SHARP_MAGO_COMMIT in ext/sharp/sharp_unit.h to that merge commit, together with the fix for change 1.

3. super.describe() in the named constructor passes as this.describe() (test proves nothing)

Constructors.sharp's Artifact.fromJson writes this.seen = super.describe();, and the test expects "entity tea". Artifact does not override describe(), so super.describe() and this.describe() return the same string. I changed line 34 to this.seen = this.describe(); and ran sharp/bin/test Zend/tests/sharp/constructors.phpt:

Tests passed    :     1 (100.0%) (100.0%)

The row cannot fail if the named constructor's super.m() dispatches as $this->m().

Fix: make Entity.describe() virtual and override it in Artifact. The row then expects "entity tea", and a $this->m() dispatch prints the override's string.

 class Entity
 {
     public Entity(public string name { get; }) { }

-    public string describe() => "entity " + this.name;
+    public virtual string describe() => "entity " + this.name;
 }

 class Artifact : Entity
 {
     public string seen { get; set; } = "";

     public Artifact(public Manifest manifest { get; }) : super(manifest.name) { }
+
+    public override string describe() => "artifact " + this.name;

The two added lines move the guard clause, so the --EXPECT-- line becomes Demo\InactiveTenant: The tenant is inactive. in Constructors.sharp on line 57. I applied this fix with change 4's fix in the scratch worktree. The test passes, and with super.describe() changed to this.describe() it fails:

-   string(10) "entity tea"
+   string(12) "artifact tea"

4. get_class(new LegacyArtifact(…)) passes whatever Artifact's constructor does (test proves nothing)

get_class(new X(…)) is X for any constructor that returns. I changed Artifact's : super(manifest.name) to : super(""). Only the Artifact::fromJson row failed ("entity tea" became "entity "). The LegacyArtifact row still printed string(19) "Demo\LegacyArtifact".

Fix: read what Artifact's main constructor and its : super(…) set, through the plain PHP subclass.

-    attempt(fn () => get_class(new Demo\LegacyArtifact(new Demo\Manifest('y'))));
+    attempt(function () {
+        $legacy = new Demo\LegacyArtifact(new Demo\Manifest('y'));
+
+        return [get_class($legacy), $legacy->manifest->name, $legacy->name];
+    });

The row expects ["Demo\LegacyArtifact", "y", "y"], and the outside-write row's --EXPECT-- line moves to constructors.php on line 38. With the fix applied, : super("") now fails this row too:

-   string(1) "y"
+   string(0) ""

Checked and correct

Every row of constructors.phpt, mutated

  • new SalesReport(1) fails if the bridge drops parent::__construct: built becomes '' and id is read before initialization.
  • Artifact::load against Artifact::fromJson fails if the named constructor's body does not run, because seen differs. The argument mutation in change 4 made it fail.
  • LegacyArtifact::fromJson('x') fails if the static method creates new static.
  • Gate fails if InactiveTenant's : super("The tenant is inactive.") into PHP's Exception is dropped, because the message is then empty.
  • Label::shouting('hi') fails if the body does not run ("hi") or if init lowers to readonly (the write throws).
  • The outside write fails if init lowers to a public set.
  • No row passes on master: master's Mago 625c278f8 cannot parse : super(…) or a named constructor, so Constructors.sharp is refused.

Runs

  • sharp/bin/test --opcache --repeat --differential: 173 of 173 in each of the four modes, and every fixture COMPILES under php -l.
  • sharp/bin/test --passes Zend/tests/sharp/constructors.phpt: passes in all 19 runs (plain, each of the 16 optimizer passes, both JITs).

.php unchanged

git diff --stat origin/master...a197f9cae4 changes no engine C file. ext/sharp/sharp_unit.h changes only SHARP_MAGO_COMMIT. SHARP_UNIT_ABI is the same. The suite's plain PHP drivers pass in every mode.

Refusals that fire once with a PHP# message

refuse/NoSuperPlain.sharp:5:12: error[missing-super-call]: `NoSuperPlain`'s constructor must call `PlainBase`'s with `: super(…)`.
refuse/NoSuperSharp.sharp:5:12: error[missing-super-call]: `NoSuperSharp`'s constructor must call `SharpBase`'s with `: super(…)`.
refuse/NoSuperException.sharp:7:12: error[missing-super-call]: `NoSuperException`'s constructor must call `Exception`'s with `: super(…)`.
refuse/ThisInSuper.sharp:5:40: error[semantics]: `this` is not available before the constructor runs: pass a parameter instead.
refuse/ThisInThis.sharp:7:38: error[semantics]: `this` is not available before the constructor runs: pass a parameter instead.
refuse/InitInMethod.sharp:9:14: error[invalid-property-write]: `text` is set only while the object is created.
refuse/InitInSubclassMethod.sharp:9:14: error[invalid-property-write]: `text` is set only while the object is created.
refuse/InitOtherObject.sharp:8:19: error[invalid-property-write]: `text` is set only while the object is created.
refuse/InitOutside.sharp:7:13: error[invalid-property-write]: `text` is set only while the object is created.
refuse/InitInLambda.sharp:7:36: error[invalid-property-write]: `text` is set only while the object is created.
refuse/GetOnlyAgain.sharp:9:14: error[invalid-property-write]: `amount` is get-only, and the main constructor already set it.
 = Help: Declare it `{ get; init; }` to let a named constructor set it again.
probe/Edges.sharp:65:18: error[semantics]: An abstract class has no objects of its own, so it declares no named constructor.

The last line is for abstract class Shape { public Shape(public int sides { get; }) { } public Shape.triangle() : this(3) { } }. Each refuse/ file holds one class whose name says what it does, in namespace P, beside the probe classes below. Examples: public NoSuperPlain(int id) { } under PlainBase, : super(this.double(id)), public ThisInThis.again() : this(this.count) { }, this.text = text; in a method, and tag.text = "outside"; in another class's static method.

Each init error carries the help "Set it on this in a constructor or a named constructor." else if with braces compiles.

Probe code and engine output: `: super(…)`, named constructors, guards, `init`, reflection (plain, tracing JIT and function JIT print the same)
// probe/PlainParents.php
namespace P;

class PlainBase
{
    public string $log = '';

    public function __construct(public int $id, public string $tag = 'default', public ?string $note = null)
    {
        $this->log = "PlainBase($id, $tag, " . var_export($note, true) . ")";
    }
}

class PlainNoCtor { public string $mark = 'plain-no-ctor'; }

class PlainOrderBase
{
    public string $seen = '';

    public function __construct() { $this->seen = $this->hook(); }

    public function hook(): string { return 'base'; }
}
// probe/Supers.sharp
namespace P;

class SharpBase
{
    public string log { get; set; } = "";
    public string tag { get; set; } = "";
    public string? note { get; set; }

    public SharpBase(public int id { get; }, string tag = "default", string? note = null)
    {
        this.tag = tag;
        this.note = note;
        this.log = "SharpBase " + tag;
    }
}

class ToPlainPositional : PlainBase { public ToPlainPositional(int id) : super(id) { } }
class ToPlainNamed : PlainBase { public ToPlainNamed(int id, string note) : super(id, note: note) { } }
class ToPlainReordered : PlainBase { public ToPlainReordered(string tag) : super(tag: tag, id: 7) { } }
class ToSharpPositional : SharpBase { public ToSharpPositional(int id) : super(id) { } }
class ToSharpNamed : SharpBase { public ToSharpNamed(int id, string note) : super(id, note: note) { } }
class ToSharpExpression : SharpBase { public ToSharpExpression(int id) : super(id * 2, "t" + "x") { } }

class OrderChild : PlainOrderBase
{
    private string label = strtoupper("child");

    public OrderChild() : super() { }

    public override string hook() => this.label;
}

class NoCtorBase { public int k { get; set; } = 1; }
class ChildOfNoCtor : NoCtorBase { public ChildOfNoCtor() : super() { } }
class ChildOfPlainNoCtor : PlainNoCtor { public ChildOfPlainNoCtor() : super() { } }
class Mid : SharpBase { public Mid(int id) : super(id, "mid") { } }
class Leaf : Mid { public Leaf() : super(9) { } }
class Pass : SharpBase { }
class ThroughPass : Pass { public ThroughPass() : super(3, "pass") { } }

class InitialValueChild : SharpBase
{
    private string extra = strtoupper("x");

    public InitialValueChild(int id) : super(id) { }

    public string shown() => this.extra + " " + this.tag;
}
// probe/Named.sharp
namespace P;

import InvalidArgumentException;

class Document
{
    public Document(public string name { get; }) { }

    public virtual string describe() => "document " + this.name;
}

class Doc : Document
{
    public string seen { get; set; } = "";

    public Doc(string name) : super(name) { }

    public override string describe() => "doc " + this.name;

    public Doc.titled(string title) : this(title) { this.seen = super.describe() + " | " + this.describe(); }

    public Doc.guarded(string title, bool ok) : this(title)
    {
        if (!ok) {
            throw new InvalidArgumentException("not ok: " + title);
        }
        this.seen = "guarded";
    }

    public Doc.early(string title, bool stop) : this(title)
    {
        if (stop) {
            return;
        }
        this.seen = "ran";
    }

    public Doc.lambda(string title) : this(title)
    {
        const shout = () => this.name + "!";
        this.seen = shout();
    }

    public Doc.withDefault(string title = "untitled") : this(title) { this.seen = "default " + title; }

    public Doc.variadic(string ...parts) : this("parts") { this.seen = parts[0] + parts[2]; }

    private Doc.hidden(string title) : this(title) { this.seen = "hidden"; }

    public static Doc makeHidden(string title) => new Doc.hidden(title);
}

class DocUser
{
    public static Doc titled(string title) => new Doc.titled(title);

    public static Doc named(string title) => new Doc.withDefault(title: title);

    public static Doc spread() => new Doc.variadic("a", "b", "c");
}
// probe/Guards.sharp
class Account
{
    public Account(public bool active { get; })
    {
        if (!active) {
            throw new InvalidArgumentException("inactive account");
        }
    }

    public Account.checked(int balance) : this(true)
    {
        if (balance < 0) {
            throw new InvalidArgumentException("negative balance");
        }
    }
}
// probe/Inits.sharp
class Tag
{
    public Tag(public string text { get; init; }) { }

    public Tag.shout(string text) : this(text) { this.text = strtoupper(text); }
}

class Email
{
    public string address { get; init { if (!str_contains(value, "@")) { throw new InvalidArgumentException("no @ in " + value); } field = value; } }

    public Email(string address) { this.address = address; }

    public Email.forUser(string user) : this(user + "@example.com") { this.address = user + "@example.org"; }

    public Email.broken(string user) : this(user + "@example.com") { this.address = user; }
}

class TrimmedTag
{
    public TrimmedTag(public string text { get; init => field = trim(value); }) { }
}

class SubTag : Tag
{
    public SubTag(string text) : super(text) { this.text = text + "!"; }
}
// probe-run/run.php: plain PHP subclasses, then three rounds of every call; the last round prints
class LegacyDoc extends P\Doc
{
    public function __construct(string $name, public string $extra = 'legacy') { parent::__construct($name); }
}

class LegacyTag extends P\Tag
{
    public function rename(string $text): void { $this->text = $text; }
}
-- super
(array) new P\ToPlainPositional(1)         → log "PlainBase(1, default, NULL)", id 1, tag "default", note NULL
(array) new P\ToPlainNamed(2, 'n')         → log "PlainBase(2, default, 'n')", id 2, tag "default", note "n"
(array) new P\ToPlainReordered('t')        → log "PlainBase(7, t, NULL)", id 7, tag "t", note NULL
new P\ToSharpPositional(3)                 → [3, "default", NULL, "SharpBase default"]
new P\ToSharpNamed(4, 'm')                 → [4, "default", "m"]
new P\ToSharpExpression(5)                 → [10, "tx"]
(new P\OrderChild())->seen                 → string(5) "CHILD"
(new P\ChildOfNoCtor())->k                 → int(1)
(new P\ChildOfPlainNoCtor())->mark         → string(13) "plain-no-ctor"
new P\Leaf()                               → [9, "mid"]
new P\ThroughPass()                        → [3, "pass"]
(new P\InitialValueChild(6))->shown()      → string(9) "X default"
-- named
P\Doc::titled('a')->seen                   → string(18) "document a | doc a"
P\DocUser::titled('a') == P\Doc::titled('a') → bool(true)
P\Doc::guarded('g', true)->seen            → string(7) "guarded"
P\Doc::guarded('g', false)                 → InvalidArgumentException: not ok: g in Named.sharp on line 28
P\Doc::early('e', true)->seen              → string(0) ""
P\Doc::early('e', false)->seen             → string(3) "ran"
P\Doc::lambda('l')->seen                   → string(2) "l!"
P\Doc::withDefault()->seen                 → string(16) "default untitled"
P\DocUser::named('n')->seen                → string(9) "default n"
P\DocUser::spread()->seen                  → string(2) "ac"
P\Doc::variadic('x', 'y', 'z')->seen       → string(2) "xz"
P\Doc::makeHidden('h')->seen               → string(6) "hidden"
P\Doc::hidden('h')                         → Error: Call to private method P\Doc::hidden() from global scope
LegacyDoc::titled('L')                     → ["P\Doc", "document L | doc L"]
new LegacyDoc('M')                         → ["LegacyDoc", "M", "legacy"]
-- guards
(new P\Account(true))->active              → bool(true)
new P\Account(false)                       → InvalidArgumentException: inactive account in Guards.sharp on line 10
P\Account::checked(5)->active              → bool(true)
P\Account::checked(-1)                     → InvalidArgumentException: negative balance in Guards.sharp on line 17
-- init
P\Tag::shout('hi')->text                   → string(2) "HI"
(new P\Email('a@b'))->address              → string(3) "a@b"
new P\Email('nope')                        → InvalidArgumentException: no @ in nope in Inits.sharp on line 17
P\Email::forUser('u')->address             → string(13) "[email protected]"
P\Email::broken('u')                       → InvalidArgumentException: no @ in u in Inits.sharp on line 17
(new P\TrimmedTag('  t  '))->text          → string(1) "t"
(new P\SubTag('s'))->text                  → string(2) "s!"
$t = new P\Tag('a'); $t->text = 'b';       → Error: Cannot modify protected(set) property P\Tag::$text from global scope
$e = new P\Email('a@b'); $e->address = 'c@d'; → Error: Cannot modify protected(set) property P\Email::$address from global scope
$t = new LegacyTag('a'); $t->rename('b');  → string(1) "b"   (the known boundary)
-- reflection
P\Doc constructor                          → __construct, declared in P\Doc, (string $name)
titled: public static not-ctor (string $title): P\Doc
variadic: public static not-ctor (string ...$parts): P\Doc
withDefault: public static not-ctor (string $title = 'untitled'): P\Doc
hidden: private static not-ctor (string $title): P\Doc
ToSharpNamed ctor: P\ToSharpNamed int $id, string $note
Tag::$text isReadOnly, isProtectedSet, isPublic → false, true, true
// probe/Edges.sharp, the rows that pass
class NamedException : Exception { public NamedException(string text) : super(code: 7, message: text) { } }
class SpreadChild : Sum { public SpreadChild(int ...values) : super(...values) { } }
class Secret
{
    private Secret(public string value { get; }) { }

    public Secret.make(string value) : this(value + "!") { }
}
class SubTag2 : Tag
{
    public SubTag2(string text) : super(text) { }

    public SubTag2.loud(string text) : this(text) { this.text = strtoupper(text) + "!"; }
}
class GeneratedChild : PlainOrderBase
{
    private string label = strtoupper("gen");

    public override string hook() => this.label;
}
new P\NamedException('boom')               → ["boom", 7]
(new P\SpreadChild(1, 2, 3))->total        → int(6)
P\Secret::make('s')->value                 → string(2) "s!"
new P\Secret('x')                          → Error: Call to private P\Secret::__construct() from global scope
P\SubTag2::loud('a')->text                 → string(2) "A!"
(new P\GeneratedChild())->seen             → string(3) "GEN"

Problem

Two rows of constructors.phpt passed whatever the code did. `Artifact` didn't
override `describe()`, so `super.describe()` in `Artifact.fromJson` printed the
same string as `this.describe()`, and a named constructor that dispatched
`super.m()` as `$this->m()` still passed. The `LegacyArtifact` row checked only
`get_class(new LegacyArtifact(…))`, which is `LegacyArtifact` for any
constructor that returns, so it passed when `Artifact`'s `: super(…)` passed the
wrong argument.

Solution

`Entity.describe` is virtual and `Artifact` overrides it, so `super.describe()`
must reach `Entity`'s. The `LegacyArtifact` row also reads `->manifest->name`
and `->name`, which `Artifact`'s main constructor and its `: super(…)` set.
Under `this.describe()`, the `fromJson` row prints "artifact tea". Under
`: super("")`, the `LegacyArtifact` row prints "".

Zend/tests/sharp/
├── Constructors.sharp     Entity.describe is virtual, Artifact overrides it
└── constructors.phpt      the LegacyArtifact row reads what the constructors set; line numbers follow
…tors

# Conflicts:
#	ext/sharp/sharp_unit.h
#	sharp/baseline/spec~HEAD
@heyJordanParker
heyJordanParker merged commit a9f723a into master Oct 13, 2026
22 checks passed
heyJordanParker added a commit that referenced this pull request Oct 13, 2026
Master brings #110 (constructors) and #113 (verification). Both add
engine tests, fixtures and slice notes, and neither changes the engine
or `sharp/mago/`. Nothing conflicted. Their three new tests and
`opcodes.phpt`, which reads #110's new fixture, pass on this slice.
heyJordanParker added a commit that referenced this pull request Oct 13, 2026
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
```
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
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.
@heyJordanParker
heyJordanParker deleted the feat/slice-constructors 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