Skip to content

feat: declare effects as foreign classes, and ship Environment as one - #118

Merged
heyJordanParker merged 20 commits into
masterfrom
feat/foreign-classes
Oct 14, 2026
Merged

heyJordanParker merged 20 commits into
masterfrom
feat/foreign-classes

Conversation

@heyJordanParker

@heyJordanParker heyJordanParker commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner

A project can declare its own effect as a foreign class, an interface or abstract method can declare the effects its implementations may have, and Environment ships as the standard library's foreign class (spec §29, mago-sharp issue #124). This PR holds the checker work of heyJordanParker/mago-sharp#180, moved into sharp/mago by subtree merge, and the engine and library work that was this PR.

Declare a project effect

  • public foreign class Payments makes Payments an effect name. uses takes a foreign class and refuses any other class with invalid-effect. The message lists the named standard effects, the foreign classes the file can name (the standard library's, its namespace's and its imports'), Events, and "or a foreign class". The file depends on each class it could name, so a warm compile gives the same message as a clean one.
  • A class that holds a foreign object, directly, through a field or through a constructor parameter, has its effect.
  • Each member of a foreign class has its class's effect. A pure interface or base-class method refuses a foreign implementation with incompatible-effects, "QuietStore.size is a member of the foreign class QuietStore". A call through the interface or base class reaches that effect, and a subclass of a foreign class has it too.
  • A foreign object in a static is the compile error foreign-in-static: in its declared type, in a value assigned to any static (Any?, List<Any> or an interface included), and in an argument .add and the other changing methods store in a static collection.
  • One source names the effects: Events, the nine named standard effects and every class flagged FOREIGN. STANDARD_EFFECTS is gone, and the uses check moved from semantics to the analyzer, because it reads the codebase.

Declare effects on a method without a body

  • uses parses on interface and abstract methods and lands in their metadata.
  • Every implementation is held to its declaration with incompatible-effects: a pure interface method whose implementation reaches Http is refused naming Http, and one declared uses Http accepts it.
  • A call of such a method has the effects its uses lists.
  • A function parameter in uses is no effect, with a body or without: apply(Function<int(int)> f) uses f; compiles, and a getter that calls it with a pure lambda stays pure. MethodParts::uses_effects gives the scanner, the semantics check and the analyzer the same list.
  • A method with a body names only its function parameters in uses, as the spec's charge(…) uses prepare => … does. Any other name there is refused at that name.
  • A law that reaches an interface method is refused with "Mago does not translate interface methods to Lean, because the implementation that runs is chosen at run time." The old reason, that an implementation can have effects, stopped being true once implementations are held to their declaration.

Read the process environment from the standard library

  • sharp/composer/library/Sharp/Environment.sharp declares public foreign class Environment. variable calls getenv, and the instance method require throws ValueError with "Environment.require: the environment variable "NAME" is not set". A static call Environment.require(…) is refused, so the environment reaches code only through an Environment object.
  • currentDirectory() reads the directory on every call, so it follows changeDirectory(path), which wraps chdir. Both throw RuntimeException with the message shape "Environment.method: …" when the environment fails.
  • arguments reads a private native body, commandLine, whose C copies the arguments the engine saves when the request starts. They match PHP's $argv. The CLI restores argv[0] after startup, so a read at call time would give -- or the -r code instead of the script name.
  • The C class, its stub, its arginfo and Mago's prelude stub of Sharp\Environment are gone. An extern method may sit in a static or a foreign class.
  • docs/decisions/056-modules.md calls require on the binding's Environment, as spec §32 does.

Warm compiles

The fingerprint of a method's uses and of the foreign modifier is now under test. A warm compile after int rate(int id); becomes … uses Http;, after a class becomes foreign, and after a base class becomes foreign matches a clean compile, and each row fails with its fingerprint line removed.

Native bodies for a foreign class

sharp/bin/native reads public foreign class, private static extern and a List<string> return, which C fills through PHP's return value.

Plan for the other effect classes

docs/architecture/slices/29-effect-classes.md plans the other nine effect classes, which ship in their own PR after structs and generic methods. It lists each member, the PHP functions the bare-call message maps to it, and how it fails.

Spec examples and harness

  • foreign-class, effectful-declarations, extern-implementations, emit-effect and pure-interface leave sharp/baseline/spec/§29/. pure-interface passes once feat: run extension members and give string its trim(), spec section 26 #115 gives string its trim(). environment and foreign-constructor pass too.
  • §29 still lists function-effects, which fails to parse Function<…> in that position. It is not this feature's.
  • Harness files changed: sharp/harness/app/PaymentGateway.sharp declares charge with uses Http, as the spec does. sharp/harness/app/Elided.sharp declares extern LogicException;, so the … placeholder fits pure code.

Left to §32

Creating a foreign object outside a module is §32's rule, so it lands with modules. This PR checks the static rule only.

Merged with master

This branch merges origin/master through #126. ext/sharp/sharp_arginfo.h is regenerated from ext/sharp/sharp.stub.php, which keeps master's insert, removeAt, put, clear, Container, ContainerError and Sharp\Internal functions, and no C Environment class.

#115's extension blocks merge with both sides' behaviour kept. Its shadowing of a default class by one of the file's namespace keeps working over one default-class list that names the effect classes directly, since STANDARD_EFFECTS is gone. An extension method carries its uses. #115's tests read Environment as the library's foreign class, and its absent-input engine test names Position, which Mago's prelude still declares.

#121's modules merge the same way. #121 added require to the C Environment, its stub and Mago's prelude stub. All three stay deleted, because the library's Environment.require already throws the same ValueError. The container keeps the C helper that reads SHARP_ENV. The library's Module.sharp binds Environment, so every fixture that compiles that module also compiles Environment.sharp: the analyzer and bridge module tests, Container.inc, and library_autoload.inc.

Checks run locally

  • cargo clippy --workspace --all-targets -- -D warnings and cargo fmt --all -- --check are clean in sharp/mago.
  • After the merge with fix: a compile after a warm pass types every class the pass skipped #126: the analyzer's PHP# tests (629), the root sharp (70), compile (75) and server_engine tests, and the orchestrator, fingerprint, names, codex, semantics, syntax, sharp-bridge, sharp-lean, formatter, hir and prelude crates pass.
  • mago compile accepts every fixture in Zend/tests/sharp, and mago analyze --minimum-fail-level note on sharp/composer reports nothing.
  • sharp/bin/test --opcache --repeat --passes: 186 of 186 tests pass in each of the 22 modes. sharp/bin/test --phpunit passes in one process and with process isolation.
  • sharp/bin/spec --self-test gives 17 of 17, and sharp/bin/spec matches sharp/baseline/spec.

…rfaces

A project could not declare its own effect: `uses` took only the standard
names, so `uses Payments` was refused. An interface or abstract method could
not say `uses` at all, so a pure interface method accepted an implementation
that reached Http. Environment lived twice, as a C class and a prelude stub.

Declare a project effect:
- `public foreign class Payments` makes Payments an effect name, and `uses`
  takes a foreign class and refuses any other class
- a class that holds a foreign object, directly, through a field or through a
  constructor parameter, has its effect
- a foreign object stored in a static is the compile error foreign-in-static
- one source names the effects: Events, the nine standard names and every
  class flagged FOREIGN

Declare effects on a method without a body:
- `uses` parses on interface and abstract methods and lands in metadata
- every implementation is held to its declaration, with incompatible-effects
- a call of such a method has the effects its `uses` lists
- a method with a body takes no `uses`: its effects come from its code

Read Environment from the standard library:
- the prelude stub is gone, and Environment.sharp in php-sharp's library is
  the one declaration
- an `extern` method may sit in a static or a foreign class

crates/
├── syntax/
│   ├── src/cst/cst/modifier.rs                    <- the `foreign` modifier
│   ├── src/cst/cst/class_like/method.rs           <- a method carries an optional `uses`
│   ├── src/parser/internal/modifier.rs            <- parses `foreign`
│   ├── src/parser/internal/class_like/method.rs   <- parses `uses` after a method's signature
│   ├── src/parser/internal/statement.rs           <- a `foreign class` starts a class statement
│   ├── src/cst/node.rs, src/walker/mod.rs         <- visit a method's `uses`
│   └── tests/sharp.rs                             <- rows for `foreign` and method `uses`
├── names/src/{binding,lib,internal/walker}.rs     <- bind the names a method's `uses` lists, the standard names in one match
├── codex/
│   ├── src/metadata/flags.rs                      <- the FOREIGN flag, 1 << 51
│   ├── src/metadata/function_like.rs              <- FunctionLikeMetadata.uses
│   ├── src/scanner/{class_like,function_like}.rs  <- record FOREIGN and a method's `uses`
│   └── src/populator/signatures.rs                <- a method's `uses` references the classes it names
├── fingerprint/src/{class_like/mod,modifier,type_hint}.rs <- a method's `uses` and `foreign` change the fingerprint
├── formatter/src/internal/format/{mod,alignment}.rs <- print `foreign`
├── hir/src/{ir,lower}/item/modifier.rs            <- carry `foreign`
├── semantics/
│   ├── src/internal/checker/sharp.rs              <- `uses` only without a body; extern in a static or foreign class
│   ├── src/internal/checker/class_like/*.rs       <- `foreign` only on a class
│   ├── src/internal/checker/function_like/parameter.rs <- the parameter check lists `foreign` with the modifiers others check
│   └── tests/sharp.rs                             <- one row per rule
├── analyzer/
│   ├── src/effects/mod.rs                         <- is_effect is the one source; unfit_implementations
│   ├── src/effects/check.rs                       <- implementations_must_fit_their_declarations, the uses check
│   ├── src/effects/summary.rs                     <- a foreign object's effect; a bodiless call has its `uses`
│   ├── src/statement/class_like/mod.rs            <- foreign-in-static
│   ├── src/code.rs                                <- invalid-effect, foreign-in-static, incompatible-effects
│   ├── src/lib.rs                                 <- runs the uses check on every PHP# file
│   └── tests/sharp.rs                             <- rows for every form, each failing without its code
├── prelude/assets/extensions/sharp.php            <- the Environment stub is deleted
└── sharp-bridge/
    ├── src/lower.rs                               <- `foreign` adds no PHP class flag
    └── tests/{common/mod,lower}.rs                <- Environment from the library fixture
scripts/regen-analyzer-issue-codes.php             <- lists incompatible-effects
tests/sharp.rs                                     <- compiles the library Environment.sharp
Environment lived twice: a C class in ext/sharp with hand-written property
handlers, and a stub in Mago. The spec makes it a `foreign` class in the
standard library, declared once in .sharp, whose methods call plain PHP.

Read the process environment from the standard library:
- Environment.sharp declares `public foreign class Environment`: `variable`
  calls getenv, `currentDirectory` reads getcwd, and static `require` throws
  ValueError "Environment.require: the environment variable "NAME" is not set"
- `arguments` reads a private native body, `commandLine`, whose C copies the
  arguments the engine saved when the request started, as PHP's $argv holds
  them; the CLI restores argv[0] after startup, so a later read is wrong
- the C class, its stub and its arginfo are gone

Write a native body for a foreign class:
- sharp/bin/native reads `public foreign class`, `private static extern` and a
  `List<string>` return, which C fills through PHP's return value

Measure the effects examples against the spec:
- the harness PaymentGateway declares `charge` with `uses Http`, as the spec
- the harness Elided declares LogicException pure, so `…` fits pure code

ext/sharp/
├── sharp.c                         <- the Environment class is deleted, and sharp_native_Environment_commandLine is added
├── sharp.stub.php                  <- the Environment declaration is deleted
├── sharp_arginfo.h                 <- regenerated without Environment
└── sharp_native.h                  <- regenerated with Environment.commandLine
sharp/
├── bin/native                      <- reads foreign classes, private externs and List<string> returns
├── composer/
│   ├── library/Sharp/Environment.sharp* <- added, the foreign class Environment
│   └── native.php                  <- regenerated with Environment.commandLine
└── harness/app/
    ├── PaymentGateway.sharp        <- `charge` uses Http, as the spec declares it
    └── Elided.sharp                <- `extern LogicException;`, so `…` has no effect
Zend/tests/sharp/
├── environment.phpt                <- the library class: arguments, variable, require, target, readonly writes
├── php_forms.phpt                  <- requires the library Environment
└── native_generator_refusal.phpt   <- the generator's new message
#177 lets a file that imports or declares a class named like a standard
effect still write the effect in `uses`, and names a standard effect in
messages by the name the file's import gives it. This branch keeps that rule
and reads it from the one effect source instead of STANDARD_EFFECTS:

- the binder's `uses` resolves through standard_class, the same match every
  default name of the `Sharp` namespace goes through
- sharp_effect_name names any effect of the `Sharp` namespace by its import's
  name or its own, and any other effect as a class
- the uses check lives in the analyzer, so #177's semantics row moves there as
  a_uses_takes_a_standard_effect_in_a_file_that_declares_a_class_of_its_name
- #177's message row declares App.Effects.Payments as a foreign class, since a
  `uses` now takes a project class only when it is foreign

crates/
├── analyzer/src/utils/names.rs   <- sharp_effect_name reads the `Sharp` namespace, not a list
├── analyzer/src/effects/check.rs <- an implementation's refusal names effects as `uses` writes them
├── analyzer/tests/sharp.rs       <- #177's rows, with the declared-class form moved from semantics
├── names/src/internal/walker.rs  <- `uses` resolves through standard_class
└── semantics/                    <- check_uses and its rows stay removed
A method with a body refused every `uses`, so the spec's
`charge(…) uses prepare => …` did not compile. Only a method without a
body states effects in `uses`, because the checker works a body's
effects out from its code. A body now names its function parameters
there, which belong to function effects. Any other name in a body's
`uses` is refused at that name, and the effect check reads no name of a
body's `uses`.

Name a function parameter in a body's uses:
- A function-typed parameter, nullable or not, passes in a body's uses
- An effect or any other name is refused at that name

Read the current directory through Environment methods:
- The Environment fixtures match the library: currentDirectory() reads
  the directory on every call, changeDirectory() wraps chdir, and both
  throw RuntimeException

crates/
├── semantics/
│   ├── src/internal/checker/sharp.rs  <- refuses a body's uses names that are no function parameter
│   └── tests/sharp.rs                 <- rows for parameters, nullable parameters, effects and other names
└── analyzer/
    ├── src/effects/check.rs           <- the effect check skips a body's uses
    └── tests/sharp.rs                 <- a body's uses prepare compiles, and the Environment fixture matches the library
tests/sharp.rs                         <- the Environment fixture matches the library
Environment.currentDirectory held the directory from when the object
was created, so it went stale after a chdir. It is now a method that
reads the directory on every call, as Go's os.Getwd and Rust's
env::current_dir do. changeDirectory() changes it. A failure of the
environment throws RuntimeException with the message shape
"Environment.method: …".

Follow and change the current directory:
- currentDirectory() reads the directory on every call
- changeDirectory(path) wraps chdir, and throws RuntimeException
  "Environment.changeDirectory: the directory "…" cannot be entered"
- currentDirectory() throws RuntimeException when the directory can't be read

Plan the effect classes:
- The plan for the other nine effect classes lists each member, the PHP
  functions the bare-call message maps to it, and how it fails

sharp/composer/library/Sharp/Environment.sharp  <- currentDirectory() and changeDirectory(), RuntimeException
docs/architecture/slices/
└── 29-effect-classes.md                        <- added, the plan for the ten effect classes
Zend/tests/sharp/
├── environment.phpt                            <- currentDirectory() follows changeDirectory(), and a missing directory throws
├── Deploy.sharp                                <- reads currentDirectory()
├── Deploy.inc                                  <- reads currentDirectory()
├── PhpForms.sharp                              <- reads currentDirectory()
└── PhpForms.inc                                <- reads currentDirectory()
A getter that read a `foreign` object's member through a name chosen at run
time, as `this.payments.{"fee"}`, had no effect, so a getter could reach a
foreign object and still count as pure. Every read of a foreign object now
has the class's effect, whatever the member selector is.

Patch coverage found the gap. The new rows also run each line of the foreign
classes change that no test ran: a method value of a method without a body,
a method value of a prelude method, the help an implementation gets when it
calls plain PHP with no `extern`, and a static field written without its type.

A call or a method value is a prelude stub call when the class that declares
the method is a prelude stub. The second check, on the class the call names,
was left over from when `Sharp\Environment` was a prelude stub. Foreign classes
now answer for it first, so the check is deleted.

crates/analyzer/
├── src/effects/summary.rs   <- a foreign read has its effect for any member selector; one prelude stub check
└── tests/sharp.rs           <- rows for a run-time member read, method values of abstract and prelude
                                methods, an implementation's extern help, and an untyped static field
… accepts

Master's law test gave `Card.amount` a call of `random_int` with no `extern`
under the pure `Payment.amount`. Section 29 now refuses that implementation
with incompatible-effects, so the compile stopped before the law check the
test is about. `Card.amount` now returns its own `cents`, and the test still
shows a law that reaches an interface method refused.

tests/compile.rs   <- Card.amount is pure, so the law refusal is what the test sees
The refusal said Mago skips interface methods "because an implementation
can have effects". Section 29 now holds every implementation to what the
declaration allows, so that reason is false. The real reason is that the
implementation a call runs is chosen at run time, which a law cannot see.

crates/sharp-lean/src/issues.rs                <- INTERFACE_METHOD gives the run-time choice as its reason
crates/sharp-lean/src/translate/mod.rs         <- the interface doc comment gives the same reason
crates/sharp-lean/lean/Sharp/Lean/Interface.lean <- the module doc gives the same reason
tests/compile.rs                               <- the law test expects the new text
# Conflicts:
#	sharp/mago/.github/actions/setup-lean/action.yml
#	sharp/mago/.github/workflows/ci.yml
With sharp/mago carrying foreign classes and uses on interface methods,
foreign-class, effectful-declarations, extern-implementations and
emit-effect compile, refuse or run as annotated.

sharp/baseline/spec/§29/
├── effectful-declarations   <- removed: uses on interface methods and function types
├── emit-effect              <- removed: an implementation of a uses Events method may emit
├── extern-implementations   <- removed: an implementation is held to its declaration's uses
└── foreign-class            <- removed: foreign parses as a class modifier
@heyJordanParker heyJordanParker changed the title feat: ship Environment as the standard library's foreign class feat: declare effects as foreign classes, and ship Environment as one Oct 13, 2026
heyJordanParker added a commit that referenced this pull request Oct 13, 2026
Problem:
Master gained #118, which makes a `Set`'s changing methods need a place and write back, as
`List`'s and `Map`'s do. Two files conflicted. #118 edits the doc of
`InvocationTarget::get_sharp_collection_receiver` to name `Set`, and this branch had folded
that method into `guess_name`, its only caller, in 6521e6b. `method_call.rs` gained an
import on both sides.

Solution:
- `crates/analyzer/src/invocation/mod.rs`: the method stays folded into `guess_name`. After
  the merge nothing calls `get_sharp_collection_receiver`, and `guess_name` already names a
  `Set` through `display_sharp_collection`.
- `crates/analyzer/src/expression/call/method_call.rs`: both imports, `PropertyAccess` and
  `TypeArgumentList`.

crates/analyzer/src/
├── invocation/mod.rs              <- conflict: the helper stays folded into guess_name
└── expression/call/method_call.rs <- conflict: both imports
heyJordanParker added a commit that referenced this pull request Oct 13, 2026
Problem:
Master gained #129, which refuses an `int` where a `float` is expected in PHP# code. Both
sides had renamed upstream's `strict_nonnull` switch to `sharp_rules`, and sixteen files
conflicted where each side built a comparison result its own way. This branch has
`ComparisonResult::for_dialect` and `ComparisonResult::nested`, and #129 has
`ComparisonResult::with_sharp_rules(bool)` at each call. Composed, three faults appeared:
- A PHP# type parameter whose bound is `string|int` passed into a `float` was named as an
  int-for-float refusal. This branch's opaque type-parameter path in
  `atomic_comparator::is_contained_by` folded the bound's parts with `all()` into one shared
  result, so the first refused part, the `int`, left `int_for_float` set. #129 fixed that
  fold for templates with `are_parts_contained_by`, and its codex test caught the gap.
- Master itself does not compile. #129 added `assigned_value` to
  `static_property_assignment::analyze`, and #118's `check_changed_collection` in
  `method_call.rs` still calls it with six arguments. Master CI at 82593a4 failed.
- Local assignments lost this branch's `explain_blocked_substitution` in #129's rewrite of
  the ordinary message.

Solution:
- One constructor path. `for_dialect` and `nested` stay, `with_sharp_rules` goes, and
  `int_for_float` joins the struct. The `sharp_rules` doc names both PHP# rules: the
  `float` that refuses an `int`, and the opaque type parameter.
- `are_parts_contained_by` is `pub(super)`, and the PHP# type-parameter input folds its
  bound through it, so a bound names its `int` only when the `int` is the one reason.
- `check_changed_collection` passes `None` as `assigned_value`, as the
  `property_assignment::analyze` call beside it does. A changed collection has no
  assigned expression.
- Every #129 report stays, and the ordinary message in each place keeps
  `explain_blocked_substitution`.

crates/
├── codex/src/ttype/comparator/
│   ├── mod.rs                   <- conflict: for_dialect, nested, int_for_float
│   ├── atomic_comparator.rs     <- conflict; a type parameter's bound folds through are_parts_contained_by
│   ├── union_comparator.rs      <- conflict; are_parts_contained_by is pub(super)
│   └── array_, callable_, generic_, iterable_comparator.rs   <- conflict: nested()
└── analyzer/src/
    ├── expression/assignment/{mod,array_assignment,property_assignment,static_property_assignment}.rs
    │                            <- conflict: #129's reports with for_dialect and explain_blocked_substitution
    ├── expression/call/method_call.rs  <- master's arity break fixed
    ├── invocation/arguments.rs  <- conflict: both imports, for_dialect
    └── statement/{return,function_like/mod,class_like/property,class_like/constant}.rs
                                 <- conflict: for_dialect
@heyJordanParker

Copy link
Copy Markdown
Owner Author

Review verdict: CHANGES NEEDED

Head: 3d1af0bd4b (php-sharp #118, feat/foreign-classes). I built mago from this head's sharp/mago and the engine with sharp/bin/build, both in a scratch worktree. I built a second mago from master (f670be8f1e) for the .php comparison.

The largest problem: a foreign class's effect disappears when the class sits behind an interface or a plain base class. Code the checker calls pure runs the foreign object's method. Four smaller changes follow, then three test gaps.

What holds

Section 29's rules, one by one

Rule #118 claims State
uses takes a foreign class and refuses any other class (invalid-effect, listing every effect) Holds
A class that holds a foreign object through a field or a constructor parameter has its effect Holds
A foreign object in a static is foreign-in-static Holds only for the static's declared type. See change 2
uses on interface and abstract methods. Every implementation is held to it (incompatible-effects) Holds for plain classes. Fails for a foreign implementation. See change 1
A call of a method without a body has the effects its uses lists Holds
A method with a body names only its function parameters in uses Holds. The bodiless form uses f is refused. See change 4
A law that reaches an interface method is refused with the approved message Holds: Law alwaysSame reaches the interface method Payment.amount in Card.same. Mago does not translate interface methods to Lean, because the implementation that runs is chosen at run time.
extern is allowed in a static or foreign class, and only in the library Holds. A project's private static extern in a foreign class gives native-body-outside-library
foreign on a method, a field, an interface or an enum Refused with "This modifier is not supported yet in PHP#". No crash
Environment members as section 29 lists them require is static. See change 3
A foreign object is created only in a module binding Not enforced. #118 leaves it to #121. new RedisStore() compiles in any method. Not counted

Edge probes

These probes use a foreign class RedisStore (get calls plain PHP Kv.get, size() returns 3):

  • Returned from a method: public RedisStore handOut() => this.store; compiles. A getter calling this.cache.handOut().get("k") is refused: impure-getter: Getter viaReturned calls RedisStore.get, which has the effect RedisStore. Holds.
  • Passed to a closure: Function<string?(string)> pure() => key => this.store.get(key); is refused with invalid-return-statement. The same lambda with uses RedisStore compiles. Holds.
  • Through a property of a non-foreign class: this.holder.store.get("k") in a getter is refused with impure-getter ... RedisStore. Holds.
  • Through a generic collection: this.stores[0].get(…), this.named["a"]?.get(…), this.stores.first(…).get(…) and this.stores.map(store => store.size()) in getters are each refused, naming RedisStore. Holds. Generic classes (class Box<T>) do not parse on this engine yet.
  • Called from a law: law sizeIsThree(Laws laws) => laws.size() == 3;, where size() calls the store, is refused: impure-law: Law sizeIsThree reaches Laws.size, which calls RedisStore.size with the effect RedisStore. Holds.
  • Through a subclass of a foreign class: a plain KvStore : BaseStore, where BaseStore is abstract foreign, gives Getter viaSubclass calls KvStore.size, which has the effect BaseStore. Holds.
  • Exact effects: a call into RedisStore.get names only RedisStore, never the undeclared Kv.get inside it. Holds.

Engine

  • environment.phpt, php_forms.phpt and native_generator_refusal.phpt pass in all four modes: without opcache, priming the file cache, using the file cache, and shared memory with --repeat 2. Each run shows Tests passed: 3 (100.0%).
  • The whole of Zend/tests/sharp without opcache gives 160 passed and 12 failed. All 12 .out files say isn't compiled for CollectionMethods, EnumKeys, Lambdas, Roster or StaticCollections. opcodes.diff loses only the EnumKeys, Lambdas and Roster lines. mago compile refuses exactly those five fixtures. So no failure is this PR's.
  • I ran plain PHP against Sharp\Environment and a project foreign class, without opcache and through the file cache. It stores both in a static, calls variable, arguments, require statically and through the object, and reflects. Every result matches plain PHP: variable("HOME") matches getenv, arguments === $argv, no attributes or interfaces are added, and the probe classes are not final. Plain PHP sees no PHP#-only behaviour.

.php is unchanged

  • I analyzed a 31,519-issue plain PHP plugin corpus with mago analyze --reporting-format emacs, once with this head's mago and once with master's. The two reports have the same line count, and the sorted reports are byte-identical (cmp prints nothing).
  • The unsorted reports differ only in the order of docblock issues inside a file. Two runs of master's mago differ the same way, so that order was already unstable before this PR.

Spec examples

sharp/bin/spec checks 179 examples. In section 29 only pure-interface (name.trim()) and function-effects (Function<…> as a statement) fail, and both are out of scope. No example newly fails. The 19 "passes and is still in sharp/baseline/spec" lines are the mago-sharp examples the PR body names.

Changes

1. A foreign object's effect is lost behind an interface or a plain base class

Program compiled wrong. The analyzer adds a foreign class's effect only when the call's static receiver type is that class or one of its subclasses (foreign_class in sharp/mago/crates/analyzer/src/effects/summary.rs). The bodies of the foreign class's own methods carry no effect. So a pure-bodied implementation passes the pure declaration, and a call through the interface or the base sees no effect.

Each file below starts with namespace App.Cache;.

// app/Cache/Store.sharp
public interface Store { int size(); }

// app/Cache/QuietStore.sharp
public foreign class QuietStore : Store { public int size() => 3; }

// app/Cache/QuietReader.sharp
public class QuietReader
{
    public QuietReader(private Store store) { }
    public Function<int()> counter() => () => this.store.size();
}

// app/Cache/Plain.sharp
public abstract class Plain { public virtual int size() => 1; }

// app/Cache/Sneaky.sharp
public foreign class Sneaky : Plain { public override int size() => 2; }

// app/Cache/PlainReader.sharp
public class PlainReader
{
    public PlainReader(private Plain plain) { }
    public int count { get => this.plain.size(); }
    public Function<int()> counter() => () => this.plain.size();
}

// app/Cache/Wiring.sharp
public class Wiring { public int viaPlain() => new PlainReader(new Sneaky()).count; }

Today mago compile accepts all of these: INFO Compiled 31 PHP# files into .sharp/.. A getter through the interface is accepted too: in a second project, public int count { get => this.store.size(); } on a class holding a Store gets no effect error. The engine then runs the foreign method from the getter the checker accepted as pure:

$ php run.php
PlainReader.count, a getter the checker accepted as pure, ran Sneaky.size: 2

A plain override is caught. When Loud : Plain overrides size with a call of Kv.get, the same getter gives impure-getter: Getter count reaches Loud.size, which calls Kv.get with no extern declaration. So the solve follows overrides. Only a foreign override's effect is missing.

What it must do:

  • QuietStore.size is refused with incompatible-effects, because the pure Store.size cannot accept the effect QuietStore. int size() uses QuietStore; on the interface accepts it, and then the getter through Store and QuietReader.counter are refused naming QuietStore.
  • PlainReader.count and PlainReader.counter are refused naming Sneaky.

Fix: give every method body of a class that foreign_class resolves the effect Effect::Foreign(<that class>) among its own effects. Do this where the summary is built. The PR's doc comment on foreign_class already states this rule: "Code that reaches such an object has that class's effect, whatever its members do." The two existing checks then see the effect. implementations_must_fit_their_declarations refuses QuietStore.size, and the override union refuses PlainReader. An accessor with no body, such as Environment.arguments { get; }, has no summary, so it stays pure.

Rows to add:

  • Interface: a pure declaration with a foreign implementation is refused. The same declaration with uses QuietStore is accepted.
  • Virtual base: a getter through the base is refused when the override is foreign.
  • Pure Function<…>: the counter lambda is refused.

2. A foreign object can be stored in a static whose type is wider than the foreign class

Program compiled wrong. Section 29 says "storing one in a static, is a compile error". check_foreign_statics in sharp/mago/crates/analyzer/src/effects/check.rs reads only the static's declared type. It never checks a write.

// app/Cache/Statics.sharp
public class Statics
{
    private static Any? loose = null;
    private static List<Any> listedAny = [];

    public Statics(private RedisStore store) { }

    public void keep() { Statics.loose = this.store; }
    public void keepInList() { Statics.listedAny = [this.store]; }
}

Today both writes compile. The same file's RedisStore?, List<RedisStore> and RedisStore? { get; set; } statics are each refused with foreign-in-static, but lines 15 and 17 get no issue.

What it must do: both writes are refused with foreign-in-static at the stored value.

Fix: in a .sharp file, check each write to a static property. That covers an assignment, and a changing collection method on a static, as Statics.all.add(this.store). When the stored value's type has an object atomic whose class foreign_class resolves, report foreign-in-static naming that class. Keep the declared-type check, which reports at the declaration.

Rows to add: an Any? static, a List<Any> static, a static typed with an interface that a foreign class implements, and .add on a static list.

3. Environment.require is static, and the settled design makes it an instance method

Program compiled wrong. Section 29 lists string require(string name) among Environment's instance members. Section 32 calls it as environment.require("REDIS_URL"). Settled item 3 says it is an instance method. sharp/composer/library/Sharp/Environment.sharp declares it public static string require(string name), and the PR body says "static require". So a call reads the environment with no Environment object, outside the constructor-only path:

// app/EnvSettings.sharp
public class EnvSettings : Settings
{
    public EnvSettings(private Environment environment) { }
    public string staticLabel { get => Environment.require("APP_KEY"); }
}

// app/Deploy.sharp
public string staticKey() => Environment.require("APP_KEY");   // in a class that also holds an Environment

Today Deploy.staticKey compiles, and staticLabel is refused only because getters must be pure. Plain PHP reflection on the engine prints require is static: true.

What it must do: Environment.require("APP_KEY") is refused, because require is an instance method. this.environment.require("APP_KEY") compiles, as it does today.

Fix:

  • Drop static from require in sharp/composer/library/Sharp/Environment.sharp.
  • In Zend/tests/sharp/environment.phpt, call $environment->require('SHARP_REGION') and $environment->require('SHARP_UNSET_REGION') in place of Sharp\Environment::require(…).
  • Update the three copies of the library source in the tests: the ENVIRONMENT constants in sharp/mago/crates/analyzer/tests/sharp.rs, sharp/mago/tests/sharp.rs and sharp/mago/crates/sharp-bridge/tests/common/mod.rs, where the bridge copy declares only variable.
  • Fix the PR body line.

4. uses f on a method without a body is refused, and its callers are refused with a made-up effect f

Valid program refused, and the message is false. Section 29 says: "Its declaration writes uses f, where f is one of its function-typed parameters, with or without a body." #118 accepts the form with a body. In the form without a body, the scanner (sharp/mago/crates/codex/src/scanner/function_like.rs, metadata.uses) and UsesWalker in effects/check.rs read every name as an effect.

// app/Mapper.sharp
public interface Mapper { int apply(Function<int(int)> f) uses f; }

// app/Doubler.sharp
public class Doubler
{
    public Doubler(private Mapper mapper) { }
    public int twice { get => this.mapper.apply(x => x * 2); }
}
app/Doubler.sharp:7:31: error[impure-getter]: Getter `twice` calls `Mapper.apply`, which has the effect `f`. Getters must be pure.
app/Mapper.sharp:5:42: error[invalid-effect]: `f` is not an effect: `uses` takes Database, Http, Files, Console, Process, Clock, Random, Cache, Mail, Environment or Events.

What it must do: both files compile, as charge(int cents, Function<int(int)> prepare) uses prepare => prepare(cents) does today.

Fix: skip a name that is one of the method's function-typed parameters in both places, using the test is_function_parameter already applies in semantics. This is safe before the function-effects work: a lambda passed to a pure Function<…> parameter is already held to that type.

Rows to add: the interface form and the abstract form in a_method_with_a_body_names_a_function_parameter_in_uses (or a sibling test), and the Doubler caller.

5. Three rules have no row that fails when their code is removed

Test that proves nothing. For each gap I removed the code and ran the suite. The suite stayed green.

  • The static rule has no accepted row. I removed .filter(|held| held.flags.is_foreign()) from check_foreign_statics, so every static holding any class object is refused. cargo test -p mago-analyzer --test sharp then gives 606 passed; 0 failed. Add a row with a static of a plain class, as public static Money? cache = null;, that expects no issue.

  • The subclass of a foreign class has no row. I removed .chain(metadata.all_parent_classes…) from foreign_class. The analyzer suite gives 606 passed; 0 failed. Today the subclass works: my probe gives Getter viaSubclass calls KvStore.size, which has the effect BaseStore. Add that probe as a row in a_getter_reaching_through_a_foreign_object_has_the_effect_of_its_class.

  • The two fingerprint lines have no row. These are self.uses.fingerprint_with_hasher(…) on Method in fingerprint/src/class_like/mod.rs, and Modifier::Foreign in fingerprint/src/modifier.rs. With either removed, cargo test -p mago-fingerprint gives 525 passed and -p mago-orchestrator --lib gives 135 passed. I ran a warm compile after an edit (analyze_incremental, the path mago analyze --watch runs) against a clean compile. It goes stale:

    • Without the uses line, editing int rate(int id); to int rate(int id) uses Http; leaves Quote.price accepted warm. The clean compile refuses it with Getter price calls Rates.rate, which has the effect Http.
    • Without the foreign line, editing public class Payments to public foreign class Payments leaves Checkout.total accepted warm. The clean compile refuses it. The same happens to a plain subclass's caller when its base becomes foreign.
    • With both lines present, the Payments and Rates edits match the clean compile. The Base edit differs only in change 6's message.

    Add these three edits as rows to a_compile_after_an_edit_to_a_header_or_an_extern_matches_a_clean_compile in orchestrator/src/service/incremental_analysis/compile.rs. Also add a method-uses row and a foreign row to fingerprint/tests/signature_changes.rs.

6. The warm path's invalid-effect message misses a class that became foreign in another file

False message, on the warm path mago analyze --watch runs. The message lists every foreign class in the project, but the file depends only on the names it writes. With uses Payments refused in Gateway.sharp, editing an unrelated Base.sharp to abstract foreign class Base gives two different lists:

clean: `Payments` is not an effect: `uses` takes Database, Http, Files, Console, Process, Clock, Random, Cache, Mail, Base or Events.
warm:  `Payments` is not an effect: `uses` takes Database, Http, Files, Console, Process, Clock, Random, Cache, Mail or Events.

What it must do: the warm message matches the clean one.

Fix: list the standard effects and say "or a foreign class", naming only the foreign classes the file imports or its namespace declares. Or drop the project list. Either way the message depends only on what the file reads. Then update a_uses_that_names_no_effect_lists_every_effect.

Outside this PR, not counted

A warm compile in diff mode panics in sharp/mago/crates/sharp-bridge/src/lower/types.rs:93: internal error: entered unreachable code: the analysis types every expression of a file the checker accepted. It panics for a body-only control edit (=> cents; to => cents + 1;) with no foreign and no uses. The diff warm-compile test helper analyzed_with came with 6e2090f4f8 (structure rule names), not with #180. I did not check whether master's code has the same panic, because master has no diff warm-compile test helper.

…found

A `foreign` class's effect leaked in six ways. A pure interface method
accepted a foreign implementation. A static typed `Any?` or `List<Any>`
took a foreign object by assignment or `.add`. `Environment.require` was
static, so any code read the environment with no constructor parameter.
`uses f` on a method without a body made `f` an effect. A warm compile
missed a changed method `uses` or `foreign` modifier with no test to
catch it. The `invalid-effect` message listed every foreign class in the
project, so it changed with files the refused file never reads.

Each member of a foreign class now has its class's effect. A write into
a static checks the stored value's type. `require` is an instance
method. `MethodParts::uses_effects` drops function parameters for the
scanner, the semantics check and the analyzer alike. The message names
the standard effects, the foreign classes the file can name, and "or a
`foreign` class", and the file depends on each class it could name.

sharp/composer/library/Sharp/Environment.sharp  <- `require` is an instance method
Zend/tests/sharp/environment.phpt               <- calls `require` on the object
docs/architecture/slices/29-effect-classes.md   <- the plan's `require` is an instance method
docs/decisions/056-modules.md                   <- the binding calls `require` on its `Environment`, as the spec does
sharp/mago/crates/
  analyzer/src/effects/summary.rs               <- a foreign class's member has its effect
  analyzer/src/effects/mod.rs                   <- "is a member of the `foreign` class `X`"
  analyzer/src/effects/check.rs                 <- static writes, `uses` walker, the shorter effect list
  analyzer/src/expression/assignment/static_property_assignment.rs <- checks the assigned value
  analyzer/src/expression/call/method_call.rs   <- checks what `.add` stores in a static
  names/src/binding.rs                          <- `MethodParts::uses_effects`
  codex/src/scanner/function_like.rs            <- method metadata keeps only effects
  semantics/src/internal/checker/sharp.rs       <- uses `uses_effects`, drops its own copy
  analyzer/tests/sharp.rs                       <- rows for each path
  orchestrator/src/service/incremental_analysis/compile.rs <- warm compiles after `uses` and `foreign` edits
  fingerprint/tests/signature_changes.rs        <- method `uses` and `foreign` change the fingerprint
  syntax/tests/sharp.rs                         <- the module row needs no `Environment`
  sharp-bridge/tests/common/mod.rs              <- the bridge's `Environment` copy has `require`
  tests/sharp.rs                                <- the root `Environment` copy drops `static`
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.
…ich every test runs

check_stored_in_static skipped an argument the analysis gave no type with a branch no program reaches, so patch-coverage refused its closing line. It filters those arguments out instead.
Brings #121's modules and container. Both sides keep their behaviour:

- Environment stays the standard library's `foreign` class. #121 added
  `require` to the C class, its stub and Mago's prelude stub, which this
  branch deletes; the library's `require` already throws the same
  ValueError. The container keeps sharp_environment_variable, which reads
  SHARP_ENV as getenv() does.
- sharp_arginfo.h is regenerated from the merged stub: Container,
  ContainerError and Sharp\Internal, and no Environment.
- decision 56 and docs/architecture/modules.md call `require` on the
  binding's `Environment` object, and the note no longer lists a C or
  prelude `Environment.require`.
- The library's Module.sharp binds `Environment`, so every fixture that
  compiles it compiles Environment.sharp too: the analyzer and bridge
  module tests, Container.inc, whose autoloader loads a Sharp class from
  the library folder, and library_autoload.inc, whose package gets the
  library's composer.json so its native body and `@` stay the library's.
- issue codes: invalid-effect, foreign-in-static and incompatible-effects
  beside invalid-binding, missing-service, service-cycle and
  captive-service.
@heyJordanParker
heyJordanParker merged commit c6a673c into master Oct 14, 2026
22 checks passed
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
…compile fix (#126)

Problem

Master moved `Sharp\Environment` out of C into the standard library as a
`foreign` class, and added `foreign` classes, `uses` on methods without a
body, and the rule that no static holds a `foreign` object. Generics changed
the same parser, binder, checker, bridge and extension files. Joined, four
things broke:

- `Method` grew by both sides' arena fields, and clippy's
  large_enum_variant refused `ClassLikeMember`.
- A method value of a plain PHP `@template` method, as `List.wrap`, kept its
  unfixed `T`. Generics hold an unfixed type parameter to itself, so
  `Shelf.make(List.wrap)` into a `Function<List<Any?>(Any?)>` was refused.
- Two generics fixtures implement a pure interface method with `sprintf`,
  which has no `extern`, so the effects check refused them.
- The opcodes test pinned its `Generics` difference against the old `link`
  body.

Solution

- Keep both sides in every conflict. `ext/sharp/sharp.c` keeps the type
  texts and takes master's native `Environment.commandLine`, and
  `sharp_arginfo.h` is regenerated from the merged stub. sharp/bin/native
  writes the same `sharp_native.h` and `native.php`.
- A method's `on` clause moves into the arena, as `type_parameters` and
  `uses` already sit there, so `Method` fits clippy's limit again.
- `fix_type_arguments` infers a plain PHP method value's `@template` types
  from the function type it goes into, as it does a PHP# method's. A plain
  PHP method's type arguments never reach the engine, so it records none and
  refuses none, and the value stays PHP's first-class callable.
- The fixtures build their strings with template strings, in the `.sharp`
  and its `.inc` twin alike, and the opcodes test pins the three `.php`
  lines the old `link` body hid.
- A new analyzer test holds the join of the two features: a value whose type
  parameter has a `foreign` bound, and a generic class's `foreign` type
  argument, are refused in a static, and a bound that is no `foreign` class
  is not.

ext/sharp/
  sharp.c                      type texts kept, Environment from master
  sharp_arginfo.h              regenerated from the merged stub
sharp/mago/crates/
  syntax/src/cst/cst/class_like/method.rs     `on` lives in the arena
  syntax/src/parser/internal/class_like/method.rs   allocates it
  syntax/src/parser/internal/statement.rs     internal or foreign, one return path
  names/src/binding.rs         both imports, `on` read as it is
  analyzer/src/resolver/property.rs           plain PHP method values infer
  analyzer/src/statement/class_like/listener.rs     `on` read as it is
  analyzer/src/expression/call/method_call.rs       both imports
  semantics/src/internal/checker/sharp.rs     an enum's `ClassLike` has both fields
  sharp-bridge/src/lower.rs    static_type_text kept, master's class_flags doc
  orchestrator/src/service/incremental_analysis/compile.rs   both tests kept whole
  analyzer/tests/sharp.rs      foreign behind a type parameter or argument
  syntax/tests/sharp.rs        `on` read as it is
Zend/tests/sharp/
  Generics.sharp, Generics.inc, TypeArguments.sharp   template strings
  opcodes.phpt                 three pinned `.php` lines
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
…d Set objects

Problem

master gained spec section 29's foreign classes after the last merge, so
#123 conflicted again in five files, and a struct had no answer to the
checker's new question of whether a class-like is `foreign`.

Solution

Each side's behaviour stays:

- `FOREIGN` keeps master's flag bit 51, and `STRUCT` and `REQUIRED` move to
  52 and 53.
- `Sharp\Key` joins the default class names master now lists in full.
- The issue-code list holds both sides' codes, and `code.rs` matches what
  the script generates.
- `method_call.rs` keeps master's `StaticPropertyName` for its static-store
  check and drops the key read-back reports our side deleted with the key
  text.
- A struct is never `foreign`, since it takes only `public`.
- `sharp_arginfo.h` is regenerated from the merged stub.

php-sharp
├── ext/sharp/sharp_arginfo.h                <- regenerated from the merged sharp.stub.php
└── sharp/mago/
    ├── scripts/regen-analyzer-issue-codes.php
    │                                        <- both sides' issue codes
    └── crates/
        ├── codex/src/metadata/flags.rs      <- FOREIGN 1 << 51, STRUCT 1 << 52, REQUIRED 1 << 53
        ├── names/src/lib.rs                 <- Sharp\Key among the default class names
        ├── analyzer/src/expression/call/method_call.rs
        │                                    <- StaticPropertyName kept, the key reports' imports gone
        └── semantics/src/internal/checker/sharp.rs
                                             <- a struct's ClassLike is not foreign
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/foreign-classes branch November 3, 2026 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant