Search by

phaenon / phn

tequila

The Phaenon compiler for Composer projects: brings the phn binary as vendor/bin/phn and compiles every installed package that has a phaenon.json, and the project itself, when Composer writes the autoloader

Package info

github.com/phaenonlang/phaenon

Homepage

Documentation

Language:Go

Type:composer-plugin

pkg:composer/phaenon/phn

Statistics

Installs: 175

Dependents: 1

Suggesters: 0

Stars: 4

Open Issues: 14


README

A typed dialect of PHP 8.5+ that compiles to idiomatic PHP — "TypeScript for PHP". The compiled output depends on nothing but PHP (design/roadmap.md D24): the compiler adds the header, declare(strict_types=1), docblocks, and PHP's own functions and classes where the source used a construct it lowers, and never a call into a package. Phaenon adds types and the spelling of declarations, never an operation PHP lacks (D26): a PHP developer reads a .phn and knows what every line does.

  • phn — the compiler (this repository, Go)
  • phaenon/debug — opt-in source positions in production: the line map read for Monolog and Sentry
  • phaenonlang/design — the language design documents, a repository of their own: a path such as design/checker.md below is a file there

Status: alpha. The language and the CLI still change, in minor releases only: a change that breaks existing programs is marked in the changelog and has a way across (phn fmt, phn migrate, or a diagnostic that says what to write). A patch release may add checker findings (design/roadmap.md D31). What works today:

  • phn check, the type checker: PHP plus Phaenon's syntax (generics, list<T> and map<K, V>, tuples, bytes, methods without a keyword, throws and nothrow) and the PHPStan docblock vocabulary; it reports what PHPStan reports at level max and never less, and its extra checks above that, which are on by default and which one switch turns off.
  • phn build, the emitter: the PHP you would have written, with PHPStan docblocks, laid out as PER Coding Style 3.0, each file ending with a line map back to its .phn.
  • The phaenon/phn Composer plugin: the pinned compiler, and the builds at every autoload dump.
  • phn fix, phn fmt, phn lsp, phn trace and phn migrate, which turns .php into .phn and lifts PHPStan's docblock generics into syntax.
  • The PhpStorm plugin and the VS Code extension, and the playground on phaenon.dev, the compiler built for WebAssembly.

The lexer, parser and printer are conformance-tested against php-src's .phpt corpus with php itself as the oracle. The language is developed against a production PHP codebase, the Tequila Platform's, from its libraries to its services, whose own suites run on the compiled output.

Type checking

phn check src tests            # diagnostics with codes, source lines and carets; exit 1 on errors
phn check --json src           # one JSON object per diagnostic, for editors, with its kind
phn check --no-extra-checks    # this run without the extra checks: the findings PHPStan does not make
phn check --format=github      # workflow commands: the findings as annotations on the .phn lines
phn check --format=checkstyle  # Checkstyle XML, for other CI systems
phn build src                  # type-checks first; a file with errors is not written
phn build --emit-on-error src  # …unless asked to: a codebase adopting the checker builds while it fixes
phn build --check --emit-on-error  # in CI: the outputs are current; files with errors pass as that build writes them

The checker reads the rest of the program without configuration: project files, vendor code through the nearest vendor/composer autoload maps, and the php-src stubs embedded in the binary (refined by an overlay for what PHP cannot express: array_map returning array<K, R>, ReflectionClass<T>, PHPUnit's assertions). Docblocks are the interop contract: @param, @return, @var, @template, @extends, @phpstan-assert and the PHPStan type grammar are understood. A @phpstan-ignore comment is honoured as it was written for PHPStan, and silences every finding of its line; @phaenon-ignore P2103, P2202 silences the codes it names, on its line or the next, and is itself P4015 where it silences nothing, as is a @phaenon-ignore that names no code (@phaenon-ignore-line and -next-line silence a whole line). The line is the one phn reports the finding on: in a call written over several lines, the argument's, not the line the call starts on. A comment is held only to the codes the run reports: phn build and phn check --no-deprecations leave the deprecations out (P1101, P4006), and hold no comment to them, nor a whole-line form to what it silenced. P4015 itself is silenced by no comment, and neither are the codes about the run rather than a line of code (P4005, P4007 to P4010, P4012, P4016), which phn prints on the first line of the first file checked where they have no file of their own: a comment that names one is P4015. A .phn docblock may use Phaenon's own spellings, as an array shape often does (array{by: map<string, int>, pair: (int, int)}); the emitter writes them in PHPStan's. A declared array names its element type (array<V> for a list or keyed array of V, array<mixed> for any), unless the method it overrides documents one: a bare array is P2516, as PHPStan at level max reports it. Diagnostic codes are stable: P1xxx removed constructs, P2xxx types and flow, P4xxx interop (docblocks, vendor). Design: design/checker.md.

Extra checks

A finding is one of three kinds (design/roadmap.md D33):

  • A language rule is what Phaenon's syntax and types ask for: the removed constructs, text and bytes, throws, generics, declared types on every declaration. PHPStan never sees the source and has no say in them. They are always reported.
  • A parity finding is one the compiled output draws without Phaenon: PHP refuses the code, or PHPStan reports it at level max with treatPhpDocTypesAsCertain: false. It is always reported, and the checker is never more lenient than PHPStan there.
  • An extra check is a finding PHPStan does not make of the code at that level, kept because the code can fail when it runs or a declared type says less than the code relies on: ** on a string, a power of integers that is a float given for an int, a list shape given an array that may be no list, a longer tuple given for a shorter one, a static method whose documented types break its parent's where the native types fit. The checker calls a finding an extra check only where it can prove that PHPStan has nothing to say of it: the value is written out, or is a parameter that its function names nowhere else. In doubt the finding is reported in both modes.

Extra checks are on by default. "extra-checks": false in phaenon.json turns them off for a project, and --no-extra-checks does for one run of phn check, phn build or phn watch, whatever the file says. phn lsp, phn fix and phn fmt go by the project file and refuse the flag; phn migrate checks with the defaults, the extra checks on. An installed package is checked with its own project file's setting, whatever the project that installed it says, and its findings are warnings either way.

{"roots": {"src": ".src"}, "extra-checks": false}

With the extra checks off, the findings the checker knows as extra are not reported at all: no line, no count, no part in the exit status, and phn build writes a file whose only findings they were. Every other finding stays as it is, and a @phaenon-ignore comment that silences an extra check is still a comment with something to silence, no P4015: the finding comes back with the switch. That is not a promise to report exactly what PHPStan reports: some findings above PHPStan's bar cannot be told from parity findings yet and are reported in both modes (design/checker.md §10). A project that moves a large PHP tree over can reach PHPStan's level first and take the extra checks afterwards.

--format=json names each finding's kind in its last member, "kind": "language", "parity" or "extra". The language server gives each diagnostic the same word as data.kind, which an editor may show and need not read. The text, github and checkstyle formats are as they were.

{"file":"src/Power.phn","line":5,"col":12,"endLine":5,"endCol":19,"severity":"error","code":"P2301","message":"operator ** on string","kind":"extra"}

Dead code is reported as warnings, as PHPStan reports it at level max: a private method, property or constant nothing in its class uses (P2406), and a private property only written (P2407) or only read (P2408). A private property that carries a framework's attribute (a mapping, a serializer group) is left alone, since the framework reaches it through reflection: by default any attribute but PHP's own. For a stricter check, phaenon.json names the attributes that count, their subclasses and implementations included; [] lets none count:

{"roots": {"src": ".src"}, "unused": {"reflected-attributes": ["Doctrine\\ORM\\Mapping\\MappingAttribute"]}}

Design: design/tooling.md §9.2.

The keys of phaenon.json are lower-case words joined by dashes, as composer.json's are (design/roadmap.md D34). Until 0.8.0 this one was written reflectedAttributes. That spelling is still read, as the key above, until the first beta, and phn check, phn build, phn watch and phn lsp warn of it on the project file with the spelling to write (P4016); a file that writes both is refused. A library that commits its outputs and writes the key with its dash keeps out the releases from before 0.8.0, which refuse the file (below).

How it fits into a Composer project

A .phn file is PHP without the <?php tag. phn build compiles each source root into a sibling output directory with the same structure — src/ → .src/, tests/ → .tests/ — named in phaenon.json at the project root:

{"roots": {"src": ".src", "tests": ".tests"}, "exclude": ["tests/Fixture"]}

Composer's PSR-4 ("App\\": ".src/"), PHPUnit, PHPStan, php-cs-fixer and Xdebug point at the outputs, which are gitignored; the IDE and the repository hold the sources. The output is a sibling at the same depth, not a nested mirror, so that a compiled file's __DIR__ sits where its source's does: __DIR__.'/../config/services.yaml' and \dirname(__DIR__, 3) keep resolving. Every other file under a root (fixtures, YAML) is copied over, so __DIR__.'/Fixture' exists there too, and an output whose source is gone is removed. A plain .php among them is checked first, as PHP, by phn build as by phn check, and copied as it is only without errors (or under --emit-on-error); a .php beside a .phn of the same name is neither checked nor copied, since the .phn's output takes its path. Roots and their outputs are separate directories, none of them another or inside another, so that every file compiles into one place. exclude names the paths the checker leaves alone (fixtures another analyser owns); phn build compiles them all the same, and copies a plain .php among them without reading it. unused narrows which attributes spare a private property the dead-code warnings, and "extra-checks": false leaves out the checker's extra checks (both above).

The file is one JSON object, in UTF-8. A key phn does not know is an error of the project's own file, which catches a key misspelt; so are a known key in another letter case, a key written twice, and null where a list holds strings. The error says which phn read the file (unknown key "…" (this is phn 0.5.0; a newer release may know it)): an editor's phn lsp from PATH, or PHN_BINARY, may be older than the release the project pins, and takes a key of a newer one for a mistake. In the file of an installed package a key it does not know is passed over, in silence (composer dump-autoload -v names it): the project that installed the package cannot change its file, and a later compiler may have given the library a key this one has not heard of. That an older compiler does not meet a key it must not ignore is for the library's Composer conflict on phaenon/phn to see to. Everything else is refused in an installed package's file as in the project's own, a key under unused that is not known among it (unknown key "unused.…"), and such a package is warned of and left out.

committed lists the roots whose outputs the repository tracks, each a key of roots; an entry that is not one is an error of the project file:

{"roots": {"src": ".src", "tests": ".tests"}, "committed": ["src"]}

It is for a library published for PHP projects at large, which a project that has no phn then installs as the plain PHP it compiles to (roadmap.md D28). In the library's own project phn build, phn watch and the editor build a committed root as any other, which is how its outputs are made and kept current; the one difference is a stamp found there (below). The key speaks where the library is an installed package: phn build --vendor leaves such a root as installed, with no output written and no stamp, and builds the package's other roots as before. A committed root that came without its outputs (no output directory, or a .phn with no .php there) fails the command with an error naming the package, its version and the root, and nothing is built in its place: the same release is broken for every project without phn, and it is the package's to repair. The project that installed it can report it, or require a version that has its outputs. A project written in Phaenon still reads such a package from its .phn, as it reads any installed Phaenon package.

One thing is removed from a committed root: what a build of an earlier release left there. A library that shipped its sources alone was built where it is installed, and an upgrade that keeps the directory (a source install, which is a git checkout) leaves that build's stamp, .phn-build, and the outputs of the sources the new release dropped beside the committed files, where they still load. Where a committed root's output directory holds a stamp, phn build --vendor removes the files no source stands behind, by the rule of phn build itself, then the stamp. It prints a line that names the package and the stamp and a line for each file removed; the next run finds no stamp and says nothing.

  • It does so only where an earlier build can have survived: in a checkout of the package's repository ("installation-source": "source" in vendor/composer/installed.json) and in a path repository linked to a checkout. Composer installs an archive, and a path repository it copies, into an emptied directory, so a stamp there came with the files: it is left alone with everything beside it, and nothing is said.
  • It removes nothing it is not sure of. With a root or an output directory that is a symbolic link or lies behind one, a root the install lacks, a directory of the outputs it cannot read, or a source whose absence it cannot prove (a link among the sources that leads nowhere, a directory behind a link that it cannot read or search), it leaves the whole root as it is and warns, saying what can be done. A package that is no link is removed and installed again. In a linked checkout the library's own phn build removes the same files once what stands in the way is put right; where that build does not look at the directory either, for a root the checkout lacks or a directory that is a link, the stamp and what lies beside it are removed by hand. A directory of the root itself that cannot be read fails the command, as before.
  • It never clears the project's own directory, whatever installed.json says of a package's path.
  • A symbolic link in the output directory is neither followed nor removed, and only the directories a removal empties go with the files.
  • A file that cannot be removed is a warning, and the stamp then stays for the next run.
  • A package that came without its outputs is not touched, nor is any package beside it.
  • A package whose project file has a key phn does not know is read, checked and built all the same (above), but this clean-up removes nothing from it: it does not rest on a file its reader understands in part. The warning names the key. The ordinary build of a root such a package does not commit still removes the outputs that have no source, as any build does.

In the library's own project, phn build removes a .phn-build from the output directory of a root the project commits, as it removes a file with no source, and phn build --check reports it: no build writes a stamp there, so one found there was left by a build of the checkout as an installed package, before the root was committed. Were it to stay, a release could track it, and a project that installs that release as a checkout would have a tracked file removed: its checkout is then modified, and a composer update of the package made without interaction fails on "has uncommitted changes". With the stamp removed by the build, a tracked one shows in git status, and the gate of a library that commits its outputs, the state of the tree after a build, fails until the removal is committed. The stamp of a root the project does not commit stays, as the record of the build that wrote it.

phn migrate src tests          # once: Foo.php → Foo.phn, docblock types lifted into syntax, `public function title()` → `title()`, nested calls as |> pipelines, canonical layout
phn build                      # the roots of phaenon.json → their outputs
phn build --check              # CI: fail when an output is missing, stale or has no source
phn check                      # type-check the roots, minus "exclude"

Without a project file, phn build src tests writes Foo.php next to Foo.phn — the adoption case, a .phn at a time in a PHP tree — or under --out DIR.

The compilers a library keeps out

A library that commits its outputs requires phaenon/phn under require-dev alone, which binds none of the projects that install it, while a project written in Phaenon reads the library's phaenon.json with its own phn. A release from before a key the file uses cannot read it as written: it refuses the file, or reads it without the key. So the library's composer.json keeps those releases out with a conflict, which Composer applies wherever phaenon/phn is installed beside the library:

{"require-dev": {"phaenon/phn": "0.5.0"}, "conflict": {"phaenon/phn": "<0.5.0"}}

Nothing makes an author write that line, and one that is missing or too low shows only in somebody else's project. So phn build of a project that commits a root checks it, and phn build --check does. The floor is the newest first release among the keys the project file uses: 0.5.0 for committed, 0.8.0 for unused.reflected-attributes and for extra-checks. The build fails, with one line on stderr and status 1, while a release from before the floor can be installed beside the package:

composer.json: "conflict": {"phaenon/phn": "<0.4"} does not keep this package from being installed beside phaenon/phn 0.4.1 or 0.4.0, which cannot read its phaenon.json: the key "committed" is known from 0.5.0 on; write "phaenon/phn": "<0.5.0" under "conflict"
  • The outputs are written all the same, or compared under --check: the line and the status are all the check adds. The plugin builds the project when Composer writes the autoloader, so a composer install in the library's own checkout fails on it too, after building.
  • It asks about the releases that exist, each tried against the constraint as Composer tries it. <0.5, <0.5.0, <=0.4.99 and <0.5 || >=9 keep out the same releases and pass alike; <0.4, 0.3.* and no conflict on phaenon/phn at all do not. The package's name is read in any letter case, and of two spellings the last counts, as Composer takes them; the line to write names the entry as the file writes it. A project on the compiler's main branch is not kept out by the line the check asks for: Composer takes dev-main for its branch alias, which stands at the newest key's release line (0.8.x-dev).
  • A constraint phn cannot read fails the build as well, as one that "cannot be judged", with the reason: it is not known to keep anything out. phn reads the comparisons, ~, ^, wildcards, hyphen ranges, alternatives, stability suffixes and flags, and branches. It does not read an inline alias (as), a numeric branch (0.5.x-dev), a version made of a date, a space that is not the plain one, alternatives of which one is a range that ends before it begins (Composer joins such ranges into something else), or what Composer itself refuses (~>0.4). A composer.json that cannot be read fails the same way.
  • The reader is its own, and is held to Composer's. phn depends on no package, so it reads the constraint itself, aiming to read it as Composer does or not at all. That is measured, not proved: a table of constraints with Composer's answers is asked of a real Composer in CI, and the reader was compared with Composer 2.9.5 over generated constraints, each difference found becoming a row of the table. A constraint Composer reads another way than phn would be a bug to report.
  • It is asked of the project's whole build only: not by phn check, phn watch, the editor's build on save or a build of some paths; not of a project that commits no root or has no composer.json; and never of an installed package, whose release is its maintainers' to repair.

Design: design/tooling.md §3.7.

The PHP target

A project compiles for a target, the oldest PHP the output must run on: PHP 8.5 or 8.6. Phaenon follows PHP (design/php-versions.md), so every 8.6 construct parses whatever the target; the target decides what the output may contain.

{"roots": {"src": ".src", "tests": ".tests"}, "php": "8.6"}
  • "php" in phaenon.json states it; phn migrate --php 8.6 [path...] writes it there (creating the file when there is none, which may then state only the target). Until the file names roots, phn check and phn build take paths, and the Composer plugin builds nothing of the project and says so.
  • Without it, the target is the lowest version composer.json's require.php admits: >=8.5, ^8.5, ~8.5.0, 8.5.* and ^8.5 || ^9.0 all mean 8.5.
  • Neither: PHP 8.5, with a warning (P4010).

A target above what composer.json admits is a warning (P4008): an install on the older PHP would load code it cannot run, so raise require.php (phn never edits composer.json). A target phn does not compile for — older than 8.5, newer than 8.6 — is an error (P4009), and phn build writes nothing then. For an 8.5 target, what PHP 8.6 added is lowered to 8.5 code where the lowering is exact (partial application in most forms, #[\Override] on constants) and reported otherwise, as "… needs PHP 8.6 (target 8.5)" (P1002).

The library is PHP 8.6's whatever the target: a function, class, method, constant or parameter 8.6 added is reported where an 8.5 target uses it, "clamp() needs PHP 8.6 (target 8.5)" (P4011), unless a polyfill declares it or a guard tests for it (function_exists('clamp'), PHP_VERSION_ID >= 80600). What PHP deprecates is reported whatever the target, since code compiled for 8.5 runs on 8.6 too: library symbols (P4006, from the stubs' #[\Deprecated]) and language constructs (P1101); --no-deprecations hides both. Extensions outside php-src are read from the local php (PHN_PHP names another), which should be as new as the target (P4012 otherwise).

phn migrate strips <?php, declare(strict_types=1) and a trailing ?>, then lifts what PHPStan code says in comments into the signature: @template T of Foo → <T of Foo>, @extends Base<T> → extends Base<T>, @param list<T> $xs → list<T> $xs, @return T → : T, a property's @var array<K, V> → map<K, V>, @param array<array-key, V> $xs → array<V> $xs, and a declared array that has no element type and inherits none → array<mixed>. It also lifts function off every method, dropping the public that PHP implies (public function title() → title(), final public static function create() → final static create()), while a function and a method named after a modifier, var, const, Closure, function or fn keep function; it drops a constant's public (public const → const) and public before an asymmetric visibility (public private(set) → private(set)); --keep-public keeps all three. A tag is lifted only when its type has a Phaenon spelling and erases to the type PHP already saw — the generated .php keeps the same signatures — and every tag left in place is reported with the reason (--keep-docblocks skips the lift). "Erases" includes the override-erasure rule: a method that implements a generic signature compiles with its parameters widened to the implemented method's types, so @param T $aggregate over Aggregate $aggregate is lifted when the interface's method takes an Aggregate, whatever T's bound. For that, migrate reads the project's other files and its vendor code through Composer. Prose survives without its type: @param T $x prose becomes @param $x - prose (the dash, as in JSDoc, tells an IDE that expects a type that none follows) and a property's @var T prose becomes its docblock /** prose */; the emitter puts the types back and drops the dash. A @throws X without a description becomes throws X after the return type, several of them one union (throws A|B), and a @throws void that is the only @throws tag becomes nothrow; a @throws with prose stays, and so does every @throws tag of a docblock that holds @throws void beside another. It also runs on .phn files, so a project migrated earlier can be lifted later; a declaration already written in Phaenon keeps its type then.

Next it writes chains of nested calls as pipelines (design/tooling.md §8.1): PHP 8.5's |> with PHP 8.6's partial application, which the compiler lowers for an 8.5 target (design/php-versions.md §5.3). array_values(array_filter(array_map(fn ($u) => $u->email, $users), fn ($e) => $e !== null)) becomes $users |> array_map(fn ($u) => $u->email, ?) |> array_filter(?, fn ($e) => $e !== null) |> array_values(...), one stage per line from three stages (or past 120 columns). The head is the innermost call's one argument that is not a literal, a constant or a closure, else that call; a stage that takes only the piped value is f(...), any other f(a, ?) or f(name: ?). A chain of three calls or more is rewritten — --pipes=2 from two, --keep-calls none — and only where the pipeline is exact: the arguments before the nested call and a method's receiver are literals, constants, variables or closures the inner calls do not assign, the piped parameter is not by reference, nothing is spread, and the callee resolves through the program model. Chains in constant expressions and string interpolation, with a compact()-like call, a comment between the calls, another call beside the nested one, or a layout the pipeline would break (an operand, a stage past 120 columns, one stage per line in the middle of a line) stay calls. Migrate type-checks the files before and after the rewrite and gives a file its calls back when its findings, or the type of any expression in it, change; the summary counts the chains written as pipelines and those left as calls, by reason.

--list-types (opt-in, for code below PHPStan level 6) types a bare array declaration from the values it holds: a private property's writes, a private or final method's returns, a private method's arguments become list<T>, map<K, V>, array<V> or a tuple, in up to five rounds. A file whose findings grow gets its arrays back, and every candidate left is reported with the reason (design/tooling.md §8.2).

Then it lays the code out in the canonical style (design/functions.md §5): the opening brace of a function, method or closure moves up to the declaration's line, while a class, interface, trait or enum keeps its brace on a line of its own (moved back down where an earlier migrate moved it up), a docblock with one line of content that starts its line becomes one line, and a body that is exactly one return expr; — or one expression statement under void or never — becomes => expr;, wrapped after the arrow when the line would pass 120 columns. A body with a comment inside stays a block, as do constructors, destructors and generators. These and the pipelines are the only edits that change a file's line count (beside docblock lines whose tags were lifted); --keep-layout skips the layout. Re-running migrate on its own output changes nothing.

The generated file is laid out as PER Coding Style 3.0 wants it wherever the compiler writes or rewrites something: the open tag, a marker and declare(strict_types=1) on lines of their own (Phaenon is strict by default; a file that declares strict_types itself keeps its own), the imports it adds, the docblocks it writes, expression bodies as blocks, the opening brace of a function, method or class-like on the line after its signature, an empty body as {} on the declaration's line, and fn( in the arrow functions it writes. Plain PHP passes through as written. So php-cs-fixer runs on the outputs with a PER set (@PER-CS3x0) and no exceptions for them; @PSR12 would expand every {}, which is the source's text, and phn fix would carry that into the .phn (design D22). Every compiled file ends with a line map, a comment the tools that report positions read (design/line-map.md):

<?php

/* @generated by phaenon from Foo.phn */

declare(strict_types=1);

namespace App;
…
// phaenon-map v1 ../src/Foo.phn 1-6=1 7:1 15-17=9 18:9

__LINE__ compiles to the .phn's line. Everything else that reports a line — a stack trace, PHPUnit, PHPStan, a warning — reports the compiled file's, and phn trace turns it into the source's:

vendor/bin/phpunit | phn trace                    # .tests/FooTest.php:42 → tests/FooTest.phn:37
vendor/bin/phpstan analyse --error-format=raw | phn trace
vendor/bin/phpstan analyse --error-format=github | phn trace   # annotations GitHub can show
phn trace < clover.xml > clover.phn.xml           # coverage on the .phn lines
phn trace --root /app=. < production-trace.txt    # /app/.src/Foo.php(18) → src/Foo.phn(9)
phn trace -- vendor/bin/phpunit --colors=never    # runs it; exits with PHPUnit's status
phn trace -- php vendor/bin/phpunit               # the same on Windows, which runs no PHP script directly

Piped into phn trace, a command's exit status is lost unless the shell keeps it (set -o pipefail). phn trace -- command … runs the command itself instead: its standard output and error are rewritten the same way, a line at a time as it arrives, and phn exits with its status as a shell gives it (128 and the signal's number where a signal ended it, 127 where it was not found, 126 where it could not be run). The two streams come through two pipes: each keeps its order, but a line written to one just before a line written to the other may come out after it. Once the command has ended, phn reads what is left in the pipes for 200 ms and stops, so that a server the command left running in the background does not hold it (on Windows it waits for the pipes). What is sent to phn's process group, as Ctrl-C, Ctrl-\ and a terminal's hangup are, reaches the command too, and phn passes none of it on, so each reaches the command once. A termination sent to phn alone is passed on after a second if the command is still running; phn cannot tell it from one sent to the group, so a command that takes longer than that to end after a termination sent to the group is sent it a second time.

It rewrites file.php:42, file.php(42) and file.php on line 42 where the file carries a map, and leaves the rest of the text as it is. A GitHub workflow command (::error file=…,line=…::) gets the source's file and lines; its columns go, since the map holds lines. GitHub shows no annotation on a file the repository lacks, and the compiled outputs are gitignored, so PHPStan's annotations show only once traced. A report on stdin — Checkstyle, JUnit (PHPUnit's --log-junit, PHPStan's junit), Clover or Cobertura — is read whole and rewritten as that report, byte for byte where nothing points into a compiled file. In coverage, the compiled lines that come from one source line count as that line: covered when any of them is. In production, phaenon/debug's Monolog processor and Sentry integration do the same for logged exceptions, and the PhpStorm plugin reads the map for navigation and debugging (design/line-map.md §4).

PHP's rewriting tools run on the outputs too, where their configuration already points, and phn fix carries what they change back to the .phn:

phn fix -- tools/php-cs-fixer/vendor/bin/php-cs-fixer fix   # the fixer's changes, in the .phn
phn fix -- vendor/bin/rector process                        # Rector's
phn fix --check -- tools/php-cs-fixer/vendor/bin/php-cs-fixer fix   # each change at its .phn line; nothing written

A change of what the source wrote is applied to the source, and so is a deletion whose ends lie in it. A change of text the compiler wrote — the header, a docblock, the function of a method declared without it, an erased type — is not: the rebuild writes that text anew. phn fix then rebuilds and runs the tool again, carrying what has become the source's, for three rounds at most, and reports what the tool still changes; the exit status is 1 then (design/tooling.md §4). For php-cs-fixer and Rector, each reported change names its rule, php-cs-fixer (binary_operator_spaces) changes: …, from the tool's own JSON report, which phn fix asks for.

phn fmt formats the .phn in two layers. The first is Phaenon's layout, with no options: spaces for tabs (a tab outside a string or a comment's text doesn't compile, P1005), a function's brace on its declaration's line, a class-like's on its own, {} for an empty body, one-line docblocks, and the spacing of what only Phaenon has (class Box<T of Item>, map<string, list<int>>, Closure(int): bool, throws A|B, nothrow). The second is the project's own PHP style: its php-cs-fixer, run through phn fix.

The first layer also rewrites the spellings the language withdrew on 2026-11-09, so that a tree crosses the change with one command (design/tooling.md §5.6): fun goes before a method's name and becomes function before a function's, function is lifted off every method that does not need it (the modifiers stay as written), and a leftover is, as or as? becomes the PHP test it compiled to — $x is int → is_int($x), $b is string on bytes → mb_check_encoding($b, 'UTF-8'). Most of those depend on the operand's type, so phn fmt in a project checks the files that hold one first; phn fmt --stdin, with no program, rewrites of those only fun, function and $x is Foo with a class name, and reports the rest (P1001). With a program or without, it writes the long casts PHP removed or deprecates as the canonical ones, the only casts Phaenon has (P1001): (integer) → (int), (boolean) → (bool), (double) and (real) → (float), (binary) → (string); phn migrate writes them so too. (unset), which PHP 8.0 removed, is P1001 and left as written: null or a statement unset($x); replaces it, depending on what was meant. It writes Phaenon's words in lower case where the compiler reports another case (P1006: THROWS, TYPE, (BYTES)), and leaves Map and Bytes, which may be a class's.

phn fmt                 # the roots: Phaenon's layout, then the fixer (phaenon.json "fmt", or tools/php-cs-fixer)
phn fmt src/Foo.phn     # given files only; a directory stands for the .phn under it
phn fmt --check         # CI: fail when either layer would change a file; nothing written
                        # either form fails on a file that does not parse, and formats the others

In editors, phn lsp is the checker as a language server (LSP over stdio, design/tooling.md §6). It checks a file as it is typed, against the whole project with the open buffers as they are, and the whole project on each save, building the outputs after it as phn build does. It answers hover, go to definition, document symbols, completion (after |>, the functions that take the left side), signature help and formatting (the first layer). The PhpStorm plugin (../jetbrains) starts it for diagnostics and build on save only, since PhpStorm's own PHP support answers the rest. phn watch checks and builds after each change, for a terminal. Both read phaenon.json and composer.json again when either changes; a project file that has become invalid is reported, and until it is fixed the project is checked as last read and nothing is built.

phn lsp                 # the project around the working directory, on stdin and stdout
phn watch               # the same project: check and build its roots each time a file changes; --no-build checks only
phn fmt --stdin         # the first layer, standard input to standard output (the plugin's Reformat Code)

A library written for Phaenon projects ships its .phn sources and no compiled PHP (roadmap.md D13): with phn and the library pinned, the output is reproducible byte for byte, and the Composer plugin below builds it where it is installed. One published for PHP projects at large commits its outputs as well, the roots phaenon.json names under committed (D28, above).

Installing

A Composer project takes it as a plugin:

composer require phaenon/phn

phaenon/phn is a Composer plugin (design/tooling.md §3). It brings the phn binary for the platform, pinned by its SHA-256 in the package, so composer.lock pins the compiler too, and links it as vendor/bin/phn. The binary is kept under its platform's name (phn-linux-arm64), and vendor/bin/phn runs the one for the platform it runs on, fetching it when it is missing: one vendor/ shared between a macOS host and a Linux container serves both. A runtime image that leaves the compiler out removes the directory, rm -rf vendor/phaenon/phn/bin (earlier releases kept the one file vendor/phaenon/phn/bin/phn); vendor/bin/phn, if it is run there, fetches the binary again, or says that it cannot where the directory cannot be written. When Composer writes the autoloader, it compiles every installed package that has a phaenon.json (each for its own target, its findings shown as warnings, skipped while nothing changed: phn build --vendor), then the project itself (phn build), so that --classmap-authoritative finds the outputs. With no phaenon.json anywhere it does nothing. A root an installed package lists under committed (above) is left as installed, and a package whose installed roots are all committed is nothing to build: alone, it makes the plugin neither fetch the binary nor run it. A package that came without the outputs it commits fails the command before any binary is fetched, with the error phn build --vendor gives, under --quiet too. A committed root that holds the stamp of a build (.phn-build), in a checkout of the package's repository or a linked path repository, was built there by an earlier release, before its outputs were committed: what that build left is removed, the files no source stands behind and the stamp, as phn build --vendor does (above), each file named. The plugin does it itself at every dump, in PHP and before it looks for a compiler, so it does not depend on which phn the project has. When it then runs phn build --vendor for the packages that are built, it names in PHN_EARLIER_BUILDS_CLEARED the packages it has looked at, and phn leaves the committed roots of those alone, so that one dump says a thing once. A package the plugin could not read is not among them, and phn clears it, or warns of it, in the same dump. The variable is the plugin's word to phn, not a setting: a value that names no installed package leaves nothing out. Where the plugin is not sure, it removes nothing and warns at each dump, saying what to do; it is no less careful than phn, and removes nothing either when PHP runs under open_basedir, where the warning points at phn build --vendor, which is not bound by it. A package whose project file phn refuses is left out by the plugin as by phn, and one with nothing to build makes the dump fetch no compiler to say so (-v names the key). Under --quiet the removal is made and nothing is printed. composer dump-autoload --dry-run builds and clears as a dump does: Composer sends the plugin the same event and does not say that the run is a dry one. It requires no other package, since the compiled output needs none, and suggests phaenon/debug, which points production errors at .phn positions (design/line-map.md §4.3). It conflicts with phaenon/runtime below 0.4, that package's name until then, which declares the same classes.

  • PHN_BINARY=/path/to/phn uses another binary, such as one built from a checkout. A binary older than the plugin builds as it always did: what the plugin does itself (the check of committed outputs, the removal of an earlier build's leftovers) does not wait for it.
  • "extra": {"phaenon": {"binary-url": "https://mirror/{version}/{file}"}} fetches the binary from a mirror, with the credentials of auth.json.
  • "extra": {"phaenon": {"build": false}} leaves the project's own build to its workflow.
  • PHN_BUILD=0, for one run, installs the binary and writes the autoload maps and builds nothing, neither the project nor its packages. A CI job can then report the findings before it builds: PHN_BUILD=0 composer install, vendor/bin/phn check --format=github, then composer dump-autoload, which builds the packages and the project. A build that fails ends by saying that vendor/bin/phn is installed and vendor/bin/phn check shows the findings.
  • composer install --no-autoloader builds nothing; the dump-autoload that follows does (--no-scripts does not skip the plugin).
  • Without dev mode (composer install --no-dev, and a dump-autoload after it, which keeps that mode until it is given --dev) the plugin builds the project's roots but its development ones, those whose output composer.json maps under autoload-dev alone (tests/, which names PHPUnit), and says which it left out: phn build --no-dev does the same by hand.

Without Composer, phn is one static binary. Each release carries it for Linux and macOS (amd64, arm64) and Windows (amd64), with the playground's WebAssembly build and the source tree; their SHA-256 sums are in composer/checksums.json at the release's tag. From source, with the Go toolchain go.mod names:

go install github.com/phaenonlang/phaenon/cmd/phn@latest

A build from source calls itself dev in phn version.

Declarations

final class Account
{
    private int $balance = 0;

    balance(): int nothrow => $this->balance;

    /** Takes money out, never below zero. */
    withdraw(int $amount): void throws InsufficientFunds {
        if ($amount > $this->balance) {
            throw new InsufficientFunds($amount);
        }
        $this->balance -= $amount;
    }

    static open(): self => new self();
}

function opened(): Account => Account::open();

A method is declared without a keyword: after its modifiers, a name and its parameters, public unless a visibility is written. It compiles to public function balance(): int, PER's head. A function keeps PHP's function, and so does a method named after a modifier, var, const, Closure, function or fn (public function static()); function stays valid on any method. fun, the keyword before 2026-11-09, is P1001, which phn fmt rewrites. A named function may have one expression for its body, => expr;: returned, or only evaluated under void and never; not on constructors, destructors or generators (P1004). It compiles to the block it stands for. throws A|B after the return type names the exceptions the function lets escape; each must be a Throwable (P2319), and callers are not held to it (no checked exceptions). It compiles to a @throws tag on a line of the declaration's docblock, or of a new one above the declaration. The throw analysis reads it, as it reads @throws: a catch nothing in its try block can reach (P2403), a member the body never throws (P2404, on what no override can replace), and @throws void on a body that throws (P2405). nothrow in the clause's place says that nothing escapes: the clause spelling of @throws void, which it compiles to. The body is held to its explicit throw points (P2405), a call to a function that declares nothing does not break it, and a call to a nothrow function is no throw point, so a catch around such calls alone is dead (P2403); an override that declares nothing inherits it. Beside throws it is a syntax error; beside a @throws tag other than @throws void it is P2320, as is a throws clause or another @throws tag beside @throws void. Design: design/functions.md, design/tooling.md §9.1.

The words Phaenon adds to PHP are written in lower case: throws, nothrow, type, of, in, out, class<T>, list, map, bytes and the cast (bytes). Where only the word can stand, THROWS or TYPE Row = …; is read as the word and is an error, P1006, which phn fmt rewrites; a name of that spelling, a class Throws as a return type or a method type(), stays a name. Map and Bytes are class names like any other: the class of that name the file sees, or P2001, whose message says that Phaenon's type is written in lower case. PHP's own words keep PHP's rule, Int and FUNCTION included. Design: design/roadmap.md D30.

Generics

final class Repository<T of Model>
{
    __construct(private readonly class<T> $class, private EventStore $store) {}
    get(Uuid $id): ?T { … if ($root instanceof $this->class) { return $root; } … }
    fresh(Uuid $id): T { return new $this->class($id); }
}
final class UserRepository extends Repository<User>
{
    __construct(EventStore $store) { parent::__construct(User::class, $store); }
}

function first<T>(list<T> $items): ?T { return $items[0] ?? null; }

Type parameters are erased: first() compiles to function first(array $items): mixed with @template T, @param list<T> $items and @return ?T above it, so PHPStan, PhpStorm and a PHP caller see ordinary typed PHP. A type parameter has no runtime value; when a class needs its T at runtime it takes a class<T> — the type of User::class, a plain string — the way PHP projects already write it, and UserRepository is an ordinary autowirable service. The compiler never adds parameters or members: the output contains no identifier you did not write.

A type test is PHP's own — is_int($x), $x instanceof User, is_array($x) && array_is_list($x), $x === null, in_array($x, ['a', 'b'], true) — and the checker narrows through it as PHPStan does; a checked value is PHP 8's is_int($x) ? $x : throw new \TypeError(…). A guard of your own is a function or method with @phpstan-assert, @phpstan-assert-if-true or @phpstan-assert-if-false, which the checker honours. A tuple is a type only, with no runtime test. The operators is, as and as? that Phaenon had until 2026-11-09 are P1001, and phn fmt writes the PHP test each compiled to. Design: design/generics.md §11.5.

bytes is a PHP string at runtime, so PHP cannot tell it from text. The checked conversion to text is PHP's own test: mb_check_encoding($b, 'UTF-8'), with the encoding written as a literal, narrows a bytes operand to text, string&bytes, where it holds — mb_check_encoding($b, 'UTF-8') ? $b : throw new \ValueError('not valid UTF-8'). (bytes) $s retypes a string as binary data and (string) $b is the unchecked way back, both free. hex2bin() returns bytes|false, and bin2hex(), base64_encode() and mb_scrub() take bytes; base64_decode() keeps PHP's string, as base64 carries text as often as binary, and (bytes) base64_decode($s) retypes the binary case. The check needs ext-mbstring, or symfony/polyfill-mbstring where it is missing. Design: design/strings.md §6.

A generic declaration's docblock adds lines to the output (PHPStan reads one tag per line); every other edit keeps line numbers exact. Design: design/generics.md, decisions in §11.

CLI

phn build [--out DIR] [--check] [--emit-on-error] [--exclude PATH]... [path...] # type-check and compile .phn → .php; no paths: phaenon.json
phn check [--format=text|json|github|checkstyle] [--no-deprecations] [--exclude PATH]... path... # type-check .phn (and .php) files
phn fix [--check] -- command [arg...]                 # run php-cs-fixer, Rector… on the outputs; carry their changes back to the .phn
phn fmt [--check] [path...]                           # Phaenon's layout, then the project's fixer through phn fix; no paths: the roots
phn fmt --stdin                                       # Phaenon's layout of standard input, onto standard output
phn lsp                                               # the language server: diagnostics, hover, definition, completion, build on save
phn watch [--no-build] [--interval D]                 # check and build the project around the working directory each time a file changes
phn migrate [--keep-docblocks] [--keep-public] [--keep-layout] [--keep-calls] [--pipes=N] [--list-types] [--php X.Y] path... # rewrite .php as .phn (and re-lift .phn); --php writes the target
phn stdlib --out DIR [--check]                         # the compiled stdlib (Debug/…), as phaenon/debug ships it
phn build --vendor                        # the installed packages with a phaenon.json, as the plugin builds them, but for the roots they commit
phn trace [--root PREFIX=LOCAL]... [text...]  # positions in compiled files → .phn: text, workflow commands, XML reports on stdin
phn trace [--root PREFIX=LOCAL]... -- <command> [arg...]  # runs the command, its streams so rewritten; exits with its status
phn version                               # the version a release sets, dev otherwise
phn help                                  # the usage, on standard output (also -h, --help); phn <command> --help: its options
phn lex   [--php] file                    # token stream
phn print [--php] file                    # parse and pretty-print

--php reads plain PHP (with <?php tags); the default reads Phaenon (code from byte 0).

Repositories

The language's other parts live beside this repository in the phaenonlang organisation; phaenon.dev is its site.

  • design — the language design and every decision
  • debug — the Composer package phaenon/debug, source positions in production for Monolog and Sentry
  • jetbrains — the PhpStorm plugin
  • vscode — the VS Code extension
  • phaenon.dev — the landing page, the documentation, the playground and the release downloads

Development

CONTRIBUTING.md says what a pull request must satisfy; AGENTS.md maps the code, its tests and every test variable.

go test ./...                                   # unit tests
PHAENON_PHP_SRC=/abs/path/to/php-src go test ./internal/conformance/   # lexer, parser, printer round trip
PHAENON_EXEC=1 PHAENON_PHP_SRC=/abs/path/to/php-src go test ./internal/conformance/ -run Execution -timeout 30m
PHAENON_PHP_SRC=/abs/path/to/php-src-8.6 PHAENON_PHP=/path/to/php8.6 go test ./internal/conformance/   # a release's corpus under its php
PHAENON_PHP_SRC=/abs/path/to/php-src go generate ./stdlib              # refresh the stubs and the version table

stdlib/php-src holds the *.stub.php files of php-src's newest supported release branch, and stdlib/versions_gen.go the release each library symbol appeared in, both written by stdlib/gen from git archive of the release branches (the clone is never touched). go run ./stdlib/gen -php /path/to/php8.6 also rewrites stdlib/constants.php from that php; -check verifies instead.

The execution tests run every Zend/tests file through php twice — once as written and once after a transformation — and compare the output. TestPrinterExecution checks the pretty-printer (line numbers normalised away); TestEmitExecution checks migrate + build byte for byte, line numbers included. ≈2.5 min each. PHAENON_PHPT_FILTER=ext/standard/tests narrows any suite to a corpus subset; PHAENON_SHOW_DIFFS=n controls how many differences are listed.

internal/migrate/testdata/lift/*.php are migrated and compared with the .phn and .notes next to them (PHAENON_UPDATE=1 rewrites them); the output must parse, migrate to itself and compile to the signatures the input declared. With PHAENON_PHP86, the pipes* fixtures run as written and compiled for 8.5 and 8.6, and must print the same. testdata/lift/vendor/ (PSR-4 Acme\) holds the parents declared in other files, vendor PHP and project .phn.

internal/emit/testdata/*.phn are compiled through the checker and the emitter and compared with the .php next to them (PHAENON_UPDATE=1 rewrites them); the output must pass php -l, and PHPStan at level max when PHAENON_PHPSTAN is set.

The checker's golden corpus lives in internal/checker/testdata: each .phn carries the expected diagnostics as // want P2103 comments on the offending lines, an extra check marked after its code (// want P2301 extra), and is checked twice: with the extra checks, where each finding must be of the kind its line says, and without them, where the marked findings must be gone and every other one must stay. PHAENON_PHPSTAN=/path/to/phpstan additionally runs PHPStan at level max over the same corpus, compiled, and holds it both ways: it fails when PHPStan reports something the corpus does not expect (the checker is never more lenient than PHPStan), when the corpus expects a finding PHPStan does not have that is neither a language rule nor marked extra, and when PHPStan reports a line whose findings are all marked extra. PHAENON_COMPOSER_PROJECT=/path/to/a/composer/project exercises the vendor reader.

PHAENON_COMPOSER=$(which composer) go test ./internal/distribution runs the phaenon/phn plugin under a real Composer in temporary projects: the builds at the autoload dump, the download and its checksum, the launcher. go run ./tools/release -version X.Y.Z -out dist builds the release binaries and writes their checksums (-verify compares instead); two builds from the same sources and toolchain give the same bytes.

License: MIT.