Skip to content

feat: call plain PHP through its namespace, and refuse bare calls and statements that never run - #124

Merged
heyJordanParker merged 15 commits into
masterfrom
feat/plain-php-calls
Oct 14, 2026
Merged

heyJordanParker merged 15 commits into
masterfrom
feat/plain-php-calls

Conversation

@heyJordanParker

@heyJordanParker heyJordanParker commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner

PHP# code calls a plain PHP function and reads a plain PHP constant through its namespace, every bare call and bare PHP constant is a compile error that names what to write, every PHP built-in carries its effect, and a statement that can never run is a compile error (spec sections 7, 8, 23 and 29, decision 76). This PR holds the checker work of mago-sharp branch feat/plain-php-calls, moved into sharp/mago by subtree merge, with the library, engine fixtures and spec.

Call plain PHP through its namespace

  • global.now() calls a function of PHP's root namespace, and Pdf.render(html) after import Vendor.Pdf; calls a library's function. Each is checked as its PHP twin's call is, and lowers to the same call node.
  • An extern names a function the same way: extern global.now uses Clock; and extern Pdf.render uses Files;. A bare extern trim; is refused with extern global.trim.
  • An imported namespace that names no class holds functions, so Pdf.missing("x") and extern Pdf.no_such_function; give "Function Pdf.missing does not exist.", as global.missing does.
  • Every message names a function as the file writes it: global.strlen in an argument message, global.date in an effect message, and Pdf.render.
  • global.exit takes an int status. global.exit("…") and global.die(…) are refused, because they print the message and exit with status 0.

Read a plain PHP constant through its namespace

Jordan's ruling: a constant is read through its namespace, as a function is called.

  • global.PHP_EOL, global.PHP_INT_MAX and global.STDERR read PHP's root constants with their types, and Pdf.DEFAULT_DPI reads a library's after import Vendor.Pdf;. Each lowers to the constant's full name, as \PHP_EOL, and works in a parameter default, an attribute argument, a class constant and an enum case.
  • A bare uppercase name is always the code's own constant, of the file's namespace. A bare PHP_EOL is refused: "PHP_EOL is PHP's constant, and a bare name reads only this code's own: write global.PHP_EOL."
  • A read that reaches no constant is refused with a true message, never a panic. global.NOPE gives "Undefined constant: global.NOPE." global.strlen read without a call gives "global.strlen is a plain PHP function, not a constant: call it, as in global.strlen(…)." Nope.render gives "Nope names no class, and no namespace this file imports."
  • The standard library, the engine fixtures, spec sections 8, 23 and 24, and decisions 34, 63 and 76 write every PHP constant this way. Interop reads a harness library's constant and global.PHP_INT_MAX, and PhpForms writes global.fwrite(global.STDERR, message + global.PHP_EOL).

A compiled file is out of date once a constant it reads changes

  • A read of a constant now references it, as a call references its function. A namespaced constant's signature node carried only its short name, so it now carries its full name, keyed as the codebase keys constants.
  • So a read of Pdf.DEFAULT_DPI or global.APP_VERSION lists the plain PHP file that declares the constant as an input of the compiled file, and the warm path analyzes the reading file again when that file changes.
  • Before the fix, deleting the constant or changing its value's type left the compiled file current. The engine ran it while a clean compile refused it, and a warm compile crashed in the bridge.
  • The orchestrator rows cover deleting each constant and changing its value's type, comparing a warm compile with a clean one, plus the inputs. refusal_constant_input.phpt covers the engine's stale check against a clean compile. Each failed on the code before the fix. Without the full node name, only the namespaced constant fails.

A call has the effects of the functions it runs

  • A plain PHP function or method has the effects its extern lists, plus those of each lambda, method value and function value passed to it. So a getter that passes () => global.time() to global.array_map, global.usort, global.call_user_func or a plain PHP method is refused for Clock.
  • A call of a local that holds a lambda, const f = …; f(), has the lambda's effects.
  • Spec section 29 states the rule.

Refuse every bare call, with the call to write

  • A bare call is refused with bare-function-call, naming the standard library member that replaces it, its PHP# syntax, or the call through its namespace. Mago's exit construct is a bare call too.
  • The member table lives in the checker and absorbs the syntax table. A row names a member only once the library declares it, and a unit test fails when a row names a member sharp/composer/library lacks.
  • import Vendor.Pdf.render; and import strlen; are refused with function-import, naming Pdf.render(…) and global.strlen(…).
  • echo, print and die name global.printf, global.fwrite and global.exit(1) until Console and Process ship.

Every PHP built-in carries its effect

  • sharp/composer/library/Sharp/Builtins.sharp declares 2,215 functions, such as extern global.fopen uses Files; and extern global.strlen;. So global.date("Y") in a getter is refused for Clock, and global.strlen stays pure.
  • sharp/bin/builtins writes it from php-8-stubs 0.4.43 (MIT), pinned by SHA-256, with one rule per extension and name family. --self-test checks one row per rule and that removing each rule changes its row. The Linux job runs both and diffs the file. On a fresh checkout it creates sharp/build before the download.
  • A function on a handle that reads or writes through it, such as fwrite, fgets, fread, fgetcsv and fscanf, has both Console and Files, because a handle can be a terminal or a file. A function that prints, such as readfile, highlight_file, system, debug_print_backtrace and the gd writers called without a file, has Console.

Delete [Replaces]

PHP# has no built-in attributes. Sharp/Replaces.sharp, its 57 attribute lines, wrapped_functions, its scanner code, its duplicate and outside-library checks, and the incremental input that made every library file an input of every compiled file are gone. Decision 76 supersedes decision 40, and decisions 34, 40, 43 and 63 are marked superseded in part by it.

A statement that can never run is a compile error

  • Mago's analysis skips every statement after one that ends its block, and PHP# compiled such a statement anyway. The bridge then lowered code the checker never read, and mago compile panicked on global.exit(1); followed by any call.
  • In a .sharp file, the checker now refuses the first statement of a block that the analysis skips, once per block as Java does, with unevaluated-code: "This statement never runs, because line 9 ends the block." with the help "Delete it, or move it above line 9." That covers a statement after return, throw, global.exit(…), break or continue, one after an if whose every branch ends the block, and one after a loop that never ends, such as a do whose body ends the block. A .php file keeps Mago's help.
  • A condition of an if, a for … of, a while or a for that never finishes is refused at the condition: "This condition never finishes, so its block never runs." with the help "Write global.exit(1); as its own statement, and delete the while." A statement after such a loop is refused too, as after such an if. A compile test follows the help for if and for … of and compiles the result.
  • Inside a loop, Mago ended no block at a call it inferred as never, because a loop's first pass can infer never for a call that returns. A call of a function declared never, as global.exit is, now ends its block in a loop too, so global.exit(1); global.printf("x"); in a loop body is refused, as throw there already was.
  • a_statement_that_can_never_run_is_refused has one row per form, valid rows for finally after return, a catch after a returning try, code after a loop with break and after an if with no else, and checks the .php twin's message. compile_refuses_a_file_with_a_statement_that_never_runs reproduces the panic on master (status 101) and passes with the rule (status 1).
  • Decision 77 records the rule and the alternative Jordan rejected: dead code that compiles and is still checked, as in C# and Rust.
  • Spec section 7 states the rule with one example. output-and-exit puts exit(1) and die(…) in methods of their own, so each shows its own refusal. int-power and decision 75 show each power as its own value instead of three return lines in a row. Three bridge tests lost the dead lines they lowered.

Spec examples and harness

  • output-and-exit joins sharp/baseline/spec until Console and Process ship, and library-functions leaves it. unreachable-statements and library-constants pass. No example newly fails.
  • §29's pure-interface stays listed until Files ships. foreign-class, effectful-declarations, extern-implementations and emit-effect pass on feat: declare effects as foreign classes, and ship Environment as one #118.
  • Harness files changed: sharp/harness/Illuminate/Foundation/helpers.php is added, Laravel's root now() for extern global.now. sharp/harness/app/functions.php is deleted, because no example calls a function by a bare name.

Merged with master

This branch merges origin/master through #118 (c6a673c), which holds #110, #113, #115, #121 and #126. Both sides' behaviour is kept:

Checks run locally

  • In sharp/mago, after the merge: the analyzer's PHP# tests (636), every test target of every other workspace crate, and every test target of the root mago crate pass. Those include sharp (67) and compile (75). cargo clippy --workspace --all-targets -- -D warnings and cargo fmt --all -- --check are clean.
  • Each new row was watched failing on the code before its fix: the loop rows with each of the two fixes removed, and the constant rows on the compiler before the change, which read global.PHP_EOL as null, compiled a bare PHP_EOL, and accepted global.STDERR, global.NOPE, global.strlen and Nope.render.
  • sharp/bin/builtins --self-test checks 116 rules with 116 rows, and sharp/bin/builtins changes Builtins.sharp on 24 functions only.
  • mago compile of the engine fixtures and the library succeeds, and analyze --minimum-fail-level note on sharp/composer is clean.
  • On the built engine, sharp/bin/test --opcache --repeat --passes passes 187 of 187 tests in Zend/tests/sharp in each of its 22 modes. sharp/bin/test --spec matches sharp/baseline/spec, and sharp/bin/test --phpunit passes in one process and with process isolation.

PHP# called a plain PHP function by its bare name, so a .sharp file read
like PHP and the standard library decided through its `[Replaces]`
attribute which calls compiled. Jordan ruled that PHP# has no bare calls
and no built-in attributes: a root function is `global.now()`, a
library's function is `Pdf.render(html)` after `import Vendor.Pdf;`, and
its effects are declared with `extern global.now uses Clock;` or
`extern Pdf.render uses Files;`.

Call plain PHP through its namespace:
- `global.x(…)` and `Alias.fn(…)` resolve to the plain PHP function, are
  checked as its PHP twin's call is, and lower to the same call node
- an `extern` names the function the same way, and a bare `extern trim;`
  is refused with `extern global.trim`
- an effect message names the function as the file writes it, as in
  `Pdf.render`

Refuse every bare call, with the call to write:
- a bare call is refused with the standard library member that replaces
  it, its PHP# syntax, or the call through its namespace, and Mago's
  `exit` construct is a bare call too
- the member table lives in the checker, absorbs the syntax table, and
  names a member only once the library declares it; a unit test fails
  when a row names a member `sharp/composer/library` lacks
- `import Vendor.Pdf.render;` is refused with `function-import`
- echo, print and die name `global.printf`, `global.fwrite` and
  `global.exit(1)`

Delete `[Replaces]`:
- the attribute's scanner, its `wrapped_functions` metadata, its
  duplicate and outside-library checks, and the incremental input that
  made every library file an input of every compiled file are gone
- the exit status and die rules are gone: `exit` is a plain PHP function

A plain PHP project's analysis is unchanged: 13730 identical lines on
the vendor corpus against master 9339e1f.

crates/
├── analyzer/src/
│   ├── code.rs                          <- bare-function-call and function-import replace replaces-outside-library
│   ├── effects/check.rs                 <- an extern names a root function as global.x
│   ├── effects/mod.rs                   <- an effect cause renders as Pdf.render
│   ├── effects/summary.rs               <- a call's cause is the PHP function's name
│   ├── expression/call/function_call.rs <- namespace calls, the replacement table, bare-call refusal
│   ├── expression/call/mod.rs           <- dispatches Name.fn(…) to the plain PHP function
│   ├── expression/construct/exit.rs     <- a bare exit is a bare call
│   ├── expression/mod.rs                <- PHP shapes of patterns skip the bare-call refusal
│   ├── statement/class_like/method.rs   <- the Replaces checks are gone
│   ├── statement/mod.rs                 <- checks each PHP# import
│   ├── statement/use_statement.rs       <- refuses an import of one function
│   ├── utils/names.rs                   <- namespace_function finds Alias.fn
│   └── tests/sharp.rs                   <- one test per rule, forms as rows
├── codex/src/
│   ├── metadata/function_like.rs        <- wrapped_functions is gone
│   ├── metadata/mod.rs                  <- wrapped_functions is gone
│   └── scanner/mod.rs                   <- the Replaces scan is gone
├── names/src/internal/walker.rs         <- binds extern global.x; Replaces is no default name
├── orchestrator/src/service/
│   ├── incremental_analysis.rs          <- a library member edit reaches a bare caller
│   └── incremental_analysis/compile.rs  <- library files are no longer every file's input
├── semantics/src/internal/checker/sharp.rs <- exit rules gone; echo, print, die name global calls
└── sharp-bridge/src/
    ├── lower.rs                         <- lowers global.x and Alias.fn calls
    ├── lower/inline.rs                  <- a form may call plain PHP through its namespace
    └── lower/types.rs                   <- namespace_function reads the analyzed callee
tests/sharp.rs                           <- the Replaces tests are gone or rewritten
… global.

A bare call to a plain PHP function is now a compile error, and the
checker's own table names the library member that replaces each PHP
function. So `[Replaces]` has nothing left to do: the attribute class
and its 57 lines go, and every bare call in the standard library and
the engine fixtures is written through its namespace.

Call plain PHP through its namespace:
- Every standard library body calls `global.trim(…)`, `global.preg_match(…)`
  and the rest, as any project file must
- Text.sharp declares `extern global.strtolower`, `global.strtoupper` and
  `global.ucfirst`, the three built-ins its pure members call
- The engine fixtures call `global.count(…)`, `global.exit(…)` and the rest
- The compile_command test expects the echo advice to name `global.printf`
  and `global.fwrite`

Zend/tests/sharp/
├── Accessors.sharp, Cashier.sharp, CollectionMethods.sharp,
│   Collections.sharp, Exits.sharp, Expressions.sharp, Interop.sharp,
│   Lambdas.sharp, Library.sharp, Page.sharp, PhpForms.sharp, Plus.sharp,
│   Roster.sharp, Sets.sharp, Shipment.sharp, Signatures.sharp, Suit.sharp,
│   Template.sharp                <- call plain PHP through global.
└── compile_command.phpt          <- the echo advice names global.printf
sharp/composer/library/Sharp/
├── Replaces.sharp                <- deleted, the checker's table names each member
├── Bool.sharp, Float.sharp, Int.sharp
├── Data/                         <- Base64, Binary, Compression, Hash, Hex,
│                                    Password, PhpSerializer call through global.
├── IO/Path.sharp, Json/Json.sharp, Math/Math.sharp
├── Net/                          <- Email, Ip, Url call through global.
├── Text/                         <- Html, Regex call through global.
│   └── Text.sharp                <- declares the three built-ins its members call
└── Time/                         <- Date, TimeZone call through global.
…s plain PHP through its namespace

Every built-in call had an unknown effect, because PHP#'s package
declared none of PHP's functions, and the spec still showed bare
calls such as printf and file_put_contents. The package now ships one
extern global. line per PHP 8.5 built-in, generated from php-8-stubs by
rules on extension and name, and the spec states and shows Jordan's
ruling on plain PHP calls.

Give every PHP built-in its effect:
- Builtins.sharp declares 2,215 functions, such as `extern global.fopen
  uses Files;` and `extern global.strlen;`, so `global.date("Y")` in a
  getter is refused for Clock and `global.strlen` stays pure
- sharp/bin/builtins writes it from php-8-stubs 0.4.43, pinned by
  SHA-256, for every function Mago's prelude declares, and fails on a
  function no rule covers
- `--self-test` checks one row per rule and that each rule's removal
  changes its row. The Linux job runs both and diffs the file
- Text.sharp drops its three hand-written externs, which the file covers

Call plain PHP through its namespace in the spec:
- Section 8 says the standard library calls PHP through global. too,
  and the output example uses Console and Process from a constructor,
  with echo, print, printf, exit and die as compile errors
- Section 29 says the package ships built-in declarations, shows
  `extern Pdf.render uses Files;` and `extern global.now uses Clock;`,
  and the pure-interface example writes through Files
- Decision 76 records the ruling and replaces decision 40's
  wrap-then-refuse rule and the [Replaces] attribute

Keep the spec list exact:
- output-and-exit joins sharp/baseline/spec until Console and Process
  ship, and library-functions leaves it
- The harness drops charge, deliver and render, which no example can
  call by a bare name now, and stubs Laravel's root now() for
  extern global.now

.github/workflows/sharp.yml          <- runs sharp/bin/builtins and its self-test, diffs Builtins.sharp
docs/
├── architecture/spec-examples.md    <- drops the bare-call harness functions
├── decisions/
│   ├── 040-standard-library-shape.md <- marked superseded in part by decision 76
│   └── 076-plain-php-functions.md   <- added, the ruling on calling plain PHP functions
└── spec.md                          <- sections 8 and 29 state the rule, examples call through Console, Process, Files and global.
sharp/
├── README.md                        <- documents sharp/bin/builtins
├── baseline/spec                    <- output-and-exit joins, library-functions leaves
├── bin/builtins                     <- added, writes Builtins.sharp from php-8-stubs by RULES
├── composer/library/Sharp/
│   ├── Builtins.sharp               <- added, the effect of each PHP built-in
│   └── Text/Text.sharp              <- drops the externs Builtins.sharp covers
└── harness/
    ├── Illuminate/Foundation/helpers.php <- added, Laravel's root now() for the extern example
    └── app/functions.php            <- deleted, no example calls a function by a bare name
…ons point to decision 76

`fwrite`, `fputs`, `fprintf`, `vfprintf` and `fgets` had only Console, so
a function value declared `uses Console` accepted a lambda that writes
to a file. A handle can be a terminal or a file, so these five now carry
both effects, and a `uses Console` function type refuses `global.fwrite`
for Files.

Decisions 43 and 63 show bare calls such as `printf(…)` and
`file_put_contents(…)`, which are now compile errors. Each now says it is
superseded in part by decision 76, as decision 40 does.

docs/decisions/
├── 043-built-in-effects.md          <- superseded in part by decision 76
└── 063-console-and-process-effects.md <- superseded in part by decision 76, fwrite has Console and Files
sharp/
├── README.md                        <- RULES gives a function its effects
├── bin/builtins                     <- one rule and row give the five handle functions Console and Files
└── composer/library/Sharp/Builtins.sharp <- fwrite, fputs, fprintf, vfprintf and fgets use Console, Files
# Conflicts:
#	.github/workflows/sharp.yml
#	sharp/baseline/spec~HEAD
# Conflicts:
#	sharp/mago/.github/actions/setup-lean/action.yml
#	sharp/mago/.github/workflows/ci.yml
Mago's analysis skips every statement after one that ends its block,
and PHP# compiled such a statement anyway. The bridge then lowered code
the checker never read, and `mago compile` panicked in Types::call_target
on `global.exit(1);` followed by any call. Jordan ruled that a statement
that can never run is a compile error, as Java's "unreachable statement"
and Zig's "unreachable code" are.

The checker now refuses, in a .sharp file, every statement the analysis
skips: one after `return`, `throw`, `global.exit(…)`, `break` or
`continue` in its block, one after an `if` whose every branch ends the
block, and a block after a condition that never finishes. The refusal
names the line that ends the block, and says to delete the statement or
move it above that line. The bridge never meets a statement the analysis
did not read. A .php file keeps Mago's help.

Spec section 7 gains the rule and an example. The output-and-exit
example puts `exit(1)` and `die(…)` in methods of their own, so each
shows its own refusal. int-power and decision 75 show each power as its
own value instead of three returns in a row, and decision 34 points to
decision 76 and this rule.

sharp/mago/
├── crates/analyzer/src/statement/mod.rs   <- report_statement_that_never_runs refuses what analyze_statements skips
├── crates/analyzer/tests/sharp.rs         <- one row per form that ends a block, and the .php twin
├── crates/sharp-bridge/tests/lower.rs     <- three sources lose the dead lines they lowered
└── tests/sharp.rs                         <- mago compile refuses the file that panicked
docs/
├── spec.md                                <- section 7 rule and example, output-and-exit, int-power
├── architecture/spec-examples.md          <- the top-level return example is section 20's
├── decisions/034-output-and-exit.md       <- superseded in part by decision 76
└── decisions/075-int-power.md             <- each power is its own value
Each statement after the end of a block was refused, and each refusal
named the line before it. So in `return 1; first(); second();`, the
refusal of `second()` said line 2 ends the block, and line 2 is
`first()`, which never runs either. Now the first statement that never
runs is refused, naming the statement that ended the block, and the
rest of the block is skipped, as Java reports an unreachable statement
once.

Decision 77 records the rule, the rejected alternative that dead code
compiles and is still checked, as in C# and Rust, and why: the compiler
emits only code the checker read.

sharp/mago/crates/analyzer/
├── src/statement/mod.rs                <- analyze_statements stops at the first statement that never runs
└── tests/sharp.rs                      <- three statements after return give one refusal, naming the return's line
docs/decisions/
├── 077-unreachable-statements.md       <- added, the rule and the alternative Jordan rejected
└── 034-output-and-exit.md              <- points to decision 77
@heyJordanParker

Copy link
Copy Markdown
Owner Author

Review verdict: CHANGES NEEDED

Head: 28f27fa380 (php-sharp #124). I built mago from this head and from origin/master f670be8f1e (release, LTO off), and ran each probe below through it. I did not build the engine. Where runtime behaviour matters, the probe runs the plain PHP twin on PHP 8.5.1.

Eleven changes, in the review order: calls, the built-ins table, unreachable code, .php, tests.


Calls

1. Crash: mago compile panics on global.NAME or Pdf.fn read without a call

// app/Demo/GlobalConst.sharp
namespace App.Demo;

public class GlobalConst
{
    public static Any? handle() => global.STDERR;
}

Today mago analyze reports nothing. mago compile aborts with exit 134:

thread 'main' panicked at crates/sharp-bridge/src/lower/types.rs:143:13:
internal error: entered unreachable code: the checker refuses `App\Demo\global.STDERR`, which names no member

public static Any? render() => Pdf.render; after import Acme.Pdf; panics the same way: the checker refuses `Acme\Pdf.render`, which names no member. If the type isn't Any?, the user gets a false message instead. "a" + global.PHP_EOL gives + cannot join "a" and null, and const f = global.strlen; f("abc") gives Expression of type `null` cannot be called.

The root cause is older than this PR. On master, Nope.render for an unknown class Nope passes the checker and panics at types.rs:135. This PR makes global and imported namespaces valid prefixes, so global.STDERR now looks like correct code.

Must: the checker refuses a Name.member read that is not a call when Name names no class. For global and for an imported namespace, the message names the form to write: "A plain PHP function is called through its namespace, as in global.strlen(…). A constant is written by its name, as in STDERR."

Fix: add that refusal where the analyzer resolves a PHP# Class.y read. Add one row each for global.STDERR, global.strlen as a value, Pdf.render as a value and Nope.render. Add a tests/sharp.rs compile test that expects status 1, not a panic.

2. global.exit("…") and global.die("…") compile, and they exit with status 0

// app/Demo/Shutdown.sharp
public class Shutdown
{
    public static void fail(string reason) { global.exit(reason); }
    public static void failLiteral() { global.exit("Prune failed"); }
    public static void viaDie() { global.die("Prune failed"); }
}

Today: INFO No issues found. On master, exit(reason) was refused: PHP# has no `die`: write the message to STDERR, then `exit(1)`. This PR deleted that check from expression/construct/exit.rs, along with its four tests. php -r '\exit("Prune failed");' prints Prune failed and exits 0, so the failure reports success.

Spec section 8 removes die for exactly this reason. Decision 76 supersedes decision 34 only for the bare spelling, not for this rule.

Must: in a .sharp file, refuse global.exit or global.die with an argument that can hold a string, with the message rewritten to global.exit(1). Refuse a status that is not an int with global.exit` takes an `int` status.

Fix: run the deleted check on the namespace-call path, analyze_namespace_function_call for the function exit or die. Restore the four tests, written with global.exit.

3. A function value's effects are lost when plain PHP runs it, so a getter that reads the clock compiles

// app/Demo/Effects2.sharp
public class Effects2
{
    public int viaLambda => this.run(() => global.time());                                   // line 5
    public int viaLocalLambda { get { const f = () => global.time(); return f(); } }         // lines 7-13
    public int viaArrayMap => global.count(global.array_map(x => global.time() + x, [1, 2])); // line 15
    public int viaCallUserFunc => global.call_user_func(() => global.time());               // line 17
    public int viaUsort { get { List<int> xs = [2, 1]; global.usort(xs, (a, b) => global.time() + a - b); return xs[0]; } } // lines 19-26
    public int run(Function<int()> f) => f();
}

The bodies above are condensed onto one line each. The line numbers are the probe file's.

Today only line 5 is refused: This lambda calls `time`, which has the effect `Clock`, so a `Function<int()>` cannot hold it. Nothing is reported for lines 7 to 26, so four getters that read the clock compile as pure.

Builtins.sharp declares array_map, usort and call_user_func pure, so a callback's effect disappears at the call. On master, the same array_map getter (written with Timer.now() behind extern Timer uses Clock;) was refused, because count had no extern. This PR introduced that hole. The local-lambda form (const f = …; f()) also compiles on master.

Must: a call that runs a function value has that value's effects.

Fix: in effects/summary.rs, add to a call of a plain PHP function or method the effects of each argument that is a lambda, a method value or a value of a Function<… uses …> type. Give a call of a local the effects of the lambda it holds. Add one getter row for each of the four forms above.

4. False messages for a function reached through a namespace

Code Today Must say
Pdf.missing("x") after import Acme.Pdf; non-existent-method: Method `Pdf.missing` does not exist. Function `Pdf.missing` does not exist.. Pdf is a namespace, not a class.
extern Pdf.no_such_function; Cannot find class, interface, enum, or type alias `Pdf.no_such_function`. the same missing-function message
public string year => global.date("Y"); Getter `year` calls `date`, which has the effect `Clock`. calls `global.date` …. The PR says an effect message names the function as the file writes it, and it does so for Pdf.render only.
global.strlen(5) argument #1 of `strlen` argument #1 of `global.strlen`

Fix: when the name resolves to an imported namespace with no class, namespace_function_name returns the function's name even if the function is missing. The call then reports non-existent-function. check_extern does the same. In a .sharp file, effects::written and display_function_like_identifier write a root function as global.x.

5. import strlen; compiles

// app/Stubs/Imports.sharp
namespace App.Stubs;

import Acme.Pdf;
import Acme.Pdf.render;   // line 4
import strlen;            // line 5

Today line 4 is refused with function-import. Line 5 gets nothing. Decision 76 makes importing a single function a compile error. check_sharp_import returns early at use_statement.rs:92 when the name has no namespace separator. patch-coverage also flags that line as never run.

Must: An import names a class or a namespace, not a function: call `global.strlen(…)`.

Fix: handle the one-segment case in check_sharp_import and add a row to an_import_of_one_function_is_refused_with_the_namespace_to_import.


The built-ins table

php sharp/bin/builtins --self-test returns Checked 111 rules with 111 rows. sharp/bin/builtins regenerates Builtins.sharp byte for byte (git diff --exit-code is clean). CI never ran that step on this head, because LINUX stopped at "Test PHP#".

I spot-checked these functions on PHP 8.5.1, and each matches its row: strlen, trim, str_pad, sprintf, json_encode, checkdate, array_map, date, mktime, uniqid, random_int, getenv, gethostbyname, fgets, fwrite. These did not match:

6. Functions that print have no Console, and debug_print_backtrace is pure

The probe captures each function's output with ob_start:

readfile         (Files)      prints to output: "file-bytes\n"
fpassthru        (Files)      prints to output: "file-bytes\n"
readgzfile       (Files)      prints to output: "file-bytes\n"
gzpassthru       (Files)      prints to output: "file-bytes\n"
highlight_file   (Files)      prints to output: yes
debug_print_backtrace (pure)  prints to output: "#0 …spot.php(9): {closure:…}()\n#1 …"
system           (Process)    prints to output: "from-system\n"
passthru         (Process)    prints to output: "from-passthru\n"
imagepng(img)    (Files)      prints 138 bytes to output
fread(STDIN)     (Files)      reads the terminal: "hello"
fgetc(STDIN)     (Files)      reads the terminal: "X"
fputcsv(STDOUT)  (Files)      writes the terminal: a,b

So this getter compiles as pure and prints:

public string backtrace { get { global.debug_print_backtrace(); return ""; } }

Must:

  • Give Console to every function above that prints: readfile, fpassthru, readgzfile, gzpassthru, highlight_file, show_source, system, passthru, debug_print_backtrace, and the gd writers whose file argument may be left out (imagepng, imagejpeg, imagegif, imagewebp, imageavif, imagebmp, imagewbmp, imagexbm, imagegd, imagegd2). The script's own rule says a function has an effect when it has it with an argument left out.
  • Give Console, Files to the handle functions fread, fgetc and fputcsv, for the reason the settled fwrite family has both.
  • fgetcsv, fscanf and fflush take the same handle. I did not run them.
  • Of the gd writers I ran only imagepng. The others take the same nullable file argument. show_source is an alias of highlight_file.

Fix: add these rules to RULES in sharp/bin/builtins, each with its row in ROWS, and regenerate.

7. sharp/bin/builtins fails on a fresh checkout with a message that doesn't name the cause

$ php sharp/bin/builtins
curl: (56) Failure writing output to destination, passed 806 returned 4294967295
sharp/bin/builtins: curl -sSfL -o …/sharp/build/php-8-stubs-0.4.43.tar.gz https://… failed.

The cause is that sharp/build/ does not exist. The script runs once the folder exists.

Fix: in stubs(), create dirname($folder) before the download.


Unreachable code

Every form in the review list refuses once, naming the right line:

  • return, throw, global.exit
  • break and continue, nested loops included
  • if/else if/else where every branch ends
  • while (true), for (;;) and do … while (true)
  • a nested {} block
  • match arms that all return, and a statement inside a match arm
  • try/catch where both end, and finally that returns
  • a statement after a never method
  • inside a lambda

None of these valid forms is refused:

  • finally after return
  • a catch after a try that returns
  • code after a loop with break, including for (;;) and do … while (true)
  • code after if without else
  • a match where only some arms return
  • break inside a match arm in a loop
  • a caught throw

mago compile refuses every dead form and never panics.

8. A do loop whose body always ends lets the next statement compile

// app/Demo/DoReturn.sharp
public class DoReturn
{
    public static int run(bool again)
    {
        do {
            return 4;
        } while (again);
        return "never";        // line 10
    }
}

Today: 10:16 invalid-return-statement … expected `int`, but found `string`.. The checker reads the line as live, and there is no unevaluated-code error. Java refuses this as an unreachable statement. Decision 77 covers "one after a loop that never ends" and every form that ends a block.

Must: This statement never runs, because line 7 ends the block.

Fix: in statement/loop/do.rs, for a .sharp file, treat a do as a loop that never ends when its body ends the block and has no break or continue. Add a row to a_statement_that_can_never_run_is_refused.

9. The help for a block after a condition that never finishes cannot be followed

// app/Demo/Cond.sharp
public static void asWritten() { if (global.exit(1)) { global.printf("never"); } }
public static void statementsDeleted() { if (global.exit(1)) { } }

Today both are refused at the block: This block never runs, because the code before it never finishes. = Help: Delete it.

Following the help doesn't work. Deleting the block leaves if (global.exit(1)) with no body, which is a parse error. Deleting the statements inside it is refused again, because the empty block itself is the statement.

Must: name what to change. For example: "This condition never finishes, so its block never runs. Help: write global.exit(1); as its own statement, and delete the if."

Fix: in report_statement_that_never_runs, the None branch annotates the enclosing condition and gives that help. Test the help by compiling it.


.php is unchanged

I installed a 74-package corpus with Laravel 13, Symfony 8, Guzzle, Carbon and Twig, and ran mago analyze on it with both builds. Both give 44,627 issue lines at every level, and the two sorted outputs are identical (cmp is clean). The unsorted order differs inside two files, and two runs of master differ the same way.


Tests

10. The .php row of a_statement_that_can_never_run_is_refused proves nothing

The test checks the .php twin with issues(), which prints only line:column code. I changed if context.dialect.is_sharp() to if true in analyze_statements. That applies the PHP# error to .php files, where Mago reports a help today. The test still passed:

test a_statement_that_can_never_run_is_refused ... ok

The .sharp source has no valid rows either. A rule that refused finally after return, or code after a loop with break, would pass this test.

Fix:

  • Check the twin with refusals() and expect "10:9 unevaluated-code Unreachable code detected. | Consider removing this unreachable code.".
  • Add valid rows to the same .sharp source: finally after return, code after while (true) with break, code after if with no else, and a catch after a try that returns.
  • Add rows for while (true) with no break and for the do form in change 8.

compile_refuses_a_file_with_a_statement_that_never_runs does prove its rule. With the rule removed, it fails with left: Some(101) right: Some(1) on the panic at types.rs:166.

11. CI patch-coverage is red, and it is not one of the expected failures

diff-cover --fail-under 100 reports 12 uncovered lines.

Five are this feature's own lines:

  • function_call.rs 131: namespace_function_name's non-identifier member selector.
  • function_call.rs 688 and 705: the library test's loop and its failure path.
  • use_statement.rs 92: change 5.
  • utils/names.rs 732: the empty-namespace branch of namespace_function. No caller passes an empty namespace, so delete the branch.

The other seven came in with the mago-sharp master merge, not with this feature:

  • class_like/mod.rs 894-906 (from b4b4191b and a9df421f)
  • semantics/.../sharp.rs 3503 (from b4b4191b)
  • invocation/analyzer.rs 1844 (from 4a016b13)

They still fail this PR's gate.

Fix: cover or delete the five lines above. Mark line 131 as an impossible arm with its reason. Put the library test's walk behind #[cfg_attr(coverage_nightly, coverage(off))]. Cover the seven merged lines with a test wherever that code first lands on php-sharp master.


What passed

  • Every call form is checked as its PHP twin, with the right message: a root function, a namespace function, a static method, an instance method, a constructor, a by-reference out-type, a variadic, a named argument, a nullable return and a mixed return.
  • Effects reach a getter through a method that wraps the call.
  • A function type holding global.fwrite(…) needs both Console and Files.
  • extern Pdf.render uses Files; gives Pdf.render the effect Files.
  • Every bare-call help's fix compiles.
  • Editing Builtins.sharp recompiles the caller, and the old .sharpc is removed.
  • mago analyze --minimum-fail-level note on sharp/composer is clean.
  • The LINUX log's 16 errors all sit in CollectionMethods, EnumKeys, Lambdas, Roster and StaticCollections.

Not exercised: the engine (ext/sharp) was not built, so no .phpt ran.

# Conflicts:
#	Zend/tests/sharp/CollectionMethods.sharp
#	Zend/tests/sharp/Lambdas.sharp
… messages

The review of 28f27fa found holes in calling plain PHP from PHP#:
- global.exit("…") and global.die(…) compiled and exited 0.
- A getter that passed a clock-reading lambda to array_map, usort or
  call_user_func, or called a local lambda, compiled as pure.
- Pdf.missing(…) and extern Pdf.no_such_function named a method or a
  class, and messages named global.date and global.strlen bare.
- import strlen; compiled.
- Builtins.sharp gave no Console to functions that print or read the
  terminal, and sharp/bin/builtins failed on a fresh checkout.
- A do loop whose body ends the block let the next statement compile,
  and the help for a condition that never finishes could not be followed.

- global.exit takes an int status and global.die is refused, as before.
- A plain PHP call has the effects of each lambda, method value and
  function value passed to it, and a local's lambda runs where it is
  called.
- An imported namespace that names no class holds functions, so a missing
  member is a missing function. Every message names a root function
  global.name.
- An import of a root function names global.name(…) to call.
- RULES give Console to the printing and terminal functions, and
  stubs() creates sharp/build first.
- A do whose body ends the block never ends. A condition of an if or a
  for … of that never finishes is refused at the condition, with the
  statement to write instead.
- The library walk test is left out of coverage, and the empty-namespace
  branch of namespace_function is deleted.

sharp/
├── bin/builtins
├── composer/library/Sharp/Builtins.sharp
└── mago/crates/analyzer/src/
    ├── effects/{check,mod,summary}.rs
    ├── expression/call/{function_call,mod}.rs
    ├── statement/{if,mod,use_statement}.rs
    ├── statement/loop/{do,foreach}.rs
    └── utils/names.rs
docs/
├── spec.md
└── decisions/077-unreachable-statements.md
… refuse code that never runs

Jordan's ruling: a plain PHP constant is read through its namespace, as
a function is called. `global.PHP_EOL`, `global.PHP_INT_MAX` and
`global.STDERR` read PHP's root constants, and `Pdf.DEFAULT_DPI` reads a
library's after `import Vendor.Pdf;`. A bare uppercase name is always
the code's own constant, so a bare `PHP_EOL` is refused with "write
`global.PHP_EOL`". Before, `global.STDERR` passed the checker and the
compile panicked, and `global.PHP_EOL` read as `null`. A read that
reaches no constant is now refused with a true message: `global.NOPE`,
`global.strlen` read without a call, and `Nope.render`.

The analyzer finds a read's namespace with the helper the namespace call
uses, types the constant, and records its full name for the bridge,
which lowers it to `\PHP_EOL`. The standard library, the fixtures, the
spec and decisions 34, 63 and 76 write every PHP constant this way.

`while (global.exit(1))` and a `for` whose condition never finishes are
refused as `if`'s condition is, and so is the code after such a loop. A
call of a function declared `never` ends its block inside a loop too, so
a statement after `global.exit(1)` in a loop body is refused.

sharp/mago/crates/
  analyzer/src/utils/names.rs                   <- `member_namespace`, `namespace_member`
  analyzer/src/expression/access/mod.rs         <- namespace constant reads, a read through no class
  analyzer/src/expression/constant_access.rs    <- bare names read only their own namespace
  analyzer/src/expression/call/function_call.rs <- the namespace call uses `member_namespace`
  analyzer/src/artifacts.rs                     <- `namespace_constants`
  analyzer/src/statement/function_like/mod.rs   <- a body passes them to its parent
  analyzer/src/expression/call/mod.rs           <- a declared `never` call ends a loop's block
  analyzer/src/statement/loop/                  <- the condition refusal at every body analysis
  analyzer/src/context/scope/loop_scope.rs      <- `condition_never_finishes`
  sharp-bridge/src/lower.rs                     <- a namespace constant is a full-name `CONST`
  sharp-bridge/src/lower/inline.rs              <- forms read only full-name constants
  sharp-bridge/src/lower/types.rs               <- `namespace_constant`, no `constant_target`
  analyzer/tests/sharp.rs, tests/sharp.rs, sharp-bridge/tests/lower.rs <- rows for each
sharp/composer/library/Sharp/                   <- `global.` before each PHP constant
Zend/tests/sharp/                               <- `Interop` and `PhpForms` read constants through namespaces
docs/spec.md, docs/decisions/                   <- the rule, with the four lines
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.
Problem: a read of a constant, as `Pdf.DEFAULT_DPI` or
`global.APP_VERSION`, recorded no reference, and a namespaced constant's
signature node carried its short name, so no read reached the file that
declares it. Deleting the constant or changing its value's type left the
reading file's compiled file current: the engine ran it while a clean
compile refused it, and a warm compile crashed in the bridge on the
analysis it kept.

Solution: each read references the constant, as a call references its
function, and a constant's signature node is named as the codebase keys
it, with its namespace lowercased. The warm path re-analyzes the reading
file, and the compiled file lists the declaring file as an input.

crates/
  analyzer/src/expression/constant_access.rs  read_constant references the constant
  codex/src/signature_builder.rs              a constant's node takes its full name
  orchestrator/.../compile.rs                  inputs, and warm against clean compiles
Zend/tests/sharp/refusal_constant_input.phpt  the engine's stale check against a clean compile
patch-coverage refused four lines on the merge with master. A function value's effects read an argument with no type through one path, a condition that never finishes marks the loop scope each pass sets, namespace_function drops a class check its one caller already makes, and a read of Pdf.NOPE names the namespace that lacks the constant, now under test.
@heyJordanParker
heyJordanParker merged commit 660ad5a into master Oct 14, 2026
20 checks passed
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
Brings #124: plain PHP is called and read through its namespace, and a
statement that never runs is refused.

Problem

#124 refuses every bare call of a plain PHP function and lowers
`global.x(…)` and `Alias.fn(…)` through the method-call path. This branch
crosses each Map and Set into a plain PHP `array` parameter where the bare
call lowered. So after a plain merge `global.implode(",", tags)` would pass
the Set object to PHP, and Crossings.sharp, which calls the harness's
functions bare, would not compile.

Solution

- A call through a namespace crosses its arguments by `call_parameters`, as
  a static call does. A bare call is now only a pattern's PHP shape, such
  as `is_string`, and takes the object.
- Crossings.sharp and Roster.sharp call plain PHP through `global.`, and
  the spec's crossing rule writes `global.count(counts)`.
- `Sharp\Replaces` leaves the default names with #124's attribute, and
  `Sharp\Key` stays.
- The analyzer and semantics tests keep this branch's expectations with
  #124's `global.` calls. A test of a Map keyed by an object names
  `global.count`, and `Set.from` stays a missing method, because
  `Sharp\Set` is the engine class each Set is.
- opcodes.phpt keeps this branch's rows with #124's Interop count.

php-sharp
├── Zend/tests/sharp/
│   ├── Crossings.sharp               <- each harness function through global.
│   ├── Roster.sharp                  <- global.implode around kept.map(n => n)
│   └── opcodes.phpt                  <- Interop: 5 op arrays
├── docs/spec.md                      <- global.count(counts) in the crossing rule
└── sharp/mago/crates/
    ├── names/src/lib.rs              <- Sharp\Key without Sharp\Replaces
    ├── sharp-bridge/
    │   ├── src/lower.rs              <- the namespace call crosses by call_parameters;
    │   │                                exit is unreachable, as on master
    │   ├── src/lower/types.rs        <- namespace_function and namespace_constant beside
    │   │                                call_parameters and closure_parameters
    │   └── tests/lower.rs            <- a global.implode row; master's throw doc
    ├── analyzer/tests/sharp.rs       <- this branch's rows with global. calls
    └── semantics/tests/sharp.rs      <- this branch's key message, master's echo advice
heyJordanParker added a commit that referenced this pull request Oct 14, 2026
Problem

Master's #124 calls a plain PHP function or constant only through its
namespace, as `global.sprintf(…)`, and refuses a statement that never runs.
Seven files conflicted with generics, and the joined branch broke in four
places:

- Three engine fixtures and three bridge tests called plain PHP functions
  bare, which `mago compile` now refuses.
- The branch analyzed a `.sharp` file's code after `throw` through
  `Context::analyze_dead_code`. Master now refuses that code and stops the
  block there, so the branch's method could no longer change anything, and
  its test expected the old error.
- The Set row for `array_key_exists` called the function bare. Through
  `global.array_key_exists` the call reaches no assertion, so the row lost
  the narrowing it pinned.
- An analyzer row expected the old message for an unknown function.

Solution

- Keep both sides in every conflict. `AnalysisArtifacts` holds the tested
  types and the namespace constants. A property read takes master's
  namespace constant and unknown class arms first, then this PR's class
  constant arm, which reads a generic class too. The staleness tests keep
  this PR's type parameter test and master's constant tests whole. The throw
  test is master's. opcodes.phpt keeps this PR's checks and master's five
  `Interop` op arrays.
- Fixtures and tests call `global.sprintf`, `global.max`,
  `global.get_defined_vars`, `global.count`, `global.str_split` and
  `global.orders`.
- `Context::analyze_dead_code` and its test are deleted. The loop reads
  `settings.analyze_dead_code` again, as master does.
- The Set row moves to plain PHP, which still calls `array_key_exists`
  bare, on the `Set` a PHP# method returns. It fails without the narrowing.

Zend/tests/sharp/
  Generics.sharp, TypeArgumentsCalls.sharp, TypeArgumentsChecks.sharp   global calls
  opcodes.phpt                 both sides' lines
sharp/mago/crates/analyzer/
  src/artifacts.rs             tested types and namespace constants
  src/expression/access/mod.rs master's arms, then the generic class constant arm
  src/statement/function_like/mod.rs   both artifact maps merged up
  src/context/mod.rs           analyze_dead_code deleted
  src/statement/mod.rs         reads the setting again
  tests/sharp.rs               Set row in plain PHP, unknown function message
sharp/mago/crates/orchestrator/src/service/incremental_analysis/compile.rs   both tests whole
sharp/mago/crates/sharp-bridge/tests/lower.rs   master's throw test, global calls
sharp/mago/tests/sharp.rs      the dead code test deleted
@heyJordanParker
heyJordanParker deleted the feat/plain-php-calls 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