ToolingThe type checker

Tooling

The type checker

What phn check reads, how it relates to PHPStan, the diagnostic codes, its output formats for people and CI, and how to adopt it on code with findings.

phn check is the type checker behind every Phaenon command: phn build runs it before it writes anything, and the editors show its findings as you type. It knows PHP and Phaenon's syntax (generics, list<T> and map<K, V>, tuples, bytes, throws), reads PHPStan's docblock vocabulary, and reports at least what PHPStan reports at level max.

What the checker reads

It needs no configuration beyond phaenon.json:

  • The project: the .phn under the roots, minus exclude, and any plain .php there, read as PHP.
  • Vendor code, through the nearest vendor/composer autoload maps, loaded as it is used. An installed package that is written in Phaenon is read from its .phn, so its generics and its bytes reach your code as written. Without a vendor/composer directory the checker warns, P4005, and knows PHP's own library alone.
  • PHP's library: php-src's stubs, embedded in the binary, refined where a stub says less than PHPStan knows (array_map() keeping its keys, ReflectionClass<T>, PHPUnit's assertions). The extensions outside php-src come from the local php.
  • Docblocks: @param, @return, @var, @template, @extends, @implements, @phpstan-assert and PHPStan's type grammar, in .phn and in vendor PHP.

Compared with PHPStan

The checker reports what PHPStan reports at level max on the same code, and may report more; it is never more lenient. The compiler's tests hold it to that by running PHPStan over the checker's own test corpus. Where PHPStan has a choice, the checker takes the one many projects configure rather than PHPStan's default:

  • Docblock types are not certain, as with treatPhpDocTypesAsCertain: false. A docblock or a generic refines what PHP declares, and drives inference, but a check that would only be redundant if the docblock were true is not reported: generics are erased, so the runtime may hold what the docblock rules out.
  • No phpstan-strict-rules. Refinement types such as non-empty-string are inferred and narrowed, never required where you declare a type.

PHPStan on the outputs

Running PHPStan on the compiled code is still worth it: it sees your project with its own extensions and rules. Give it treatPhpDocTypesAsCertain: false, the checker's reading, or it reports the runtime checks that erased generics need:

you write
namespace App;

interface Handler<T of object>
{
    handle(T $message): void;
}

final class Greet {}

final class GreetHandler implements Handler<Greet>
{
    handle(object $message): void {
        if (!$message instanceof Greet) {
            throw new \InvalidArgumentException('not a Greet');
        }
        echo 'hello';
    }
}
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

/**
 * @template T of object
 */
interface Handler
{
    /**
     * @param T $message
     */
    public function handle(object $message): void;
}

final class Greet {}

/**
 * @implements Handler<Greet>
 */
final class GreetHandler implements Handler
{
    public function handle(object $message): void
    {
        if (!$message instanceof Greet) {
            throw new \InvalidArgumentException('not a Greet');
        }
        echo 'hello';
    }
}

phn check reports nothing here, and neither does PHPStan at level max with the setting off. With treatPhpDocTypesAsCertain: true, PHPStan takes the @implements for a guarantee:

.src/Example.php:29:Instanceof between App\Greet and App\Greet will always evaluate to true.

The codes

Every finding has a code, stable once published: a code is never reused for another meaning.

FamilyCovers
P1xxxSyntax: what Phaenon removed or forbids, constructs newer than the target; P11xx, constructs PHP deprecates
P2xxxTypes and flow: names, calls, assignments, expressions, unreachable code, exceptions, classes
P3xxxGenerics: type arguments, bounds, variance
P4xxxInterop: docblocks, vendor code, the PHP target

The ones you meet most:

CodeSeverityMeaning
P1001errorA construct Phaenon removed: var, the old fun, is and as; phn fmt rewrites most of them
P1005errorA tab where Phaenon wants spaces; phn fmt replaces it
P1006errorOne of Phaenon's words written in another case than lower case, THROWS; phn fmt rewrites it
P2001errorUnknown class
P2006errorUnknown method
P2103errorAn argument of the wrong type
P2202errorA returned value that does not match the return type
P2402errorA condition that always has the same result
P2502errorAn override incompatible with the method it overrides
P2516errorA declaration without a type, or an array without its element type
P2530errorbytes used as text
P3002errorA type argument outside its bound
P4011errorA function or class the target PHP lacks, clamp() needs PHP 8.6 (target 8.5)

The full list, with each code's title, is internal/checker/codes.go in the compiler's repository. What each language feature reports is on its page, such as throws and nothrow and Generics.

Errors and warnings

An error fails phn check and withholds the file's output from phn build. A warning does neither. The warnings are:

  • dead code: a private member never used (P2406), a private property never read (P2407) or never written (P2408), unreachable code (P2401), a foreach over an empty array (P2409);
  • exceptions: a catch nothing in its try can reach (P2403), a throws member the body never throws (P2404);
  • an unused import (P2013), a type argument that cannot be inferred (P3010);
  • deprecations (P1101, P4006);
  • docblocks the checker cannot use (P4001 to P4004) and the environment: no Composer maps (P4005), extensions that could not be read (P4007), the target (P4008, P4010, P4012).
you write
namespace App;

final class Basket
{
    private list<int> $prices = [];

    add(int $cents): void {
        $this->prices[] = $cents;
    }

    total(): int => array_sum($this->prices);

    private label(): string => 'basket';
}

function checkout(Basket $basket): string => $basket->total();
$ phn checkexit 1
src/Example.phn:13:13: warning P2406: private method App\Basket::label() is never used
   13 |     private label(): string => 'basket';
      |             ^^^^^
src/Example.phn:16:46: error P2202: function App\checkout() should return string but returns int
   16 | function checkout(Basket $basket): string => $basket->total();
      |                                              ^^^^^^^^^^^^^^^^
1 files checked: 1 errors, 1 warnings

Whether a private property counts as used when a framework reaches it through an attribute is a setting of phaenon.json, unused.

Output formats

--format picks how the findings are written; the exit status is the same in every format, 1 when there is an error.

text, the default, is the one above: each finding with its line and a caret, on standard error, and a summary on standard output.

json (also --json) writes one object per line, columns counted in bytes, for editors and scripts:

{"file":"src/Example.phn","line":13,"col":13,"endLine":13,"endCol":18,"severity":"warning","code":"P2406","message":"private method App\\Basket::label() is never used"}
{"file":"src/Example.phn","line":16,"col":46,"endLine":16,"endCol":62,"severity":"error","code":"P2202","message":"function App\\checkout() should return string but returns int"}

github writes GitHub Actions workflow commands, which show as annotations on the .phn lines of a pull request, and the summary:

::warning file=src/Example.phn,line=13,endLine=13,col=13,endColumn=17,title=P2406::private method App\Basket::label() is never used
::error file=src/Example.phn,line=16,endLine=16,col=46,endColumn=61,title=P2202::function App\checkout() should return string but returns int
1 files checked: 1 errors, 1 warnings

checkstyle writes Checkstyle XML, which other CI systems and code review tools read:

<?xml version="1.0" encoding="UTF-8"?>
<checkstyle>
  <file name="src/Example.phn">
    <error line="13" column="13" severity="warning" message="private method App\Basket::label() is never used" source="P2406"/>
    <error line="16" column="46" severity="error" message="function App\checkout() should return string but returns int" source="P2202"/>
  </file>
</checkstyle>

Deprecations

What PHP deprecates is reported as a warning whatever the target, since code compiled for 8.5 runs on 8.6 too: a function, class or constant marked #[\Deprecated] in PHP's stubs (P4006), and a construct PHP 8.6 deprecates, such as return inside finally (P1101).

src/Example.phn:5:46: warning P4006: function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0
    5 | function close(\CurlHandle $handle): void => curl_close($handle);
      |                                              ^^^^^^^^^^
1 files checked: 0 errors, 1 warnings

phn check --no-deprecations leaves both out.

The build withholds what does not check

phn build checks the project first and writes no output for a file with an error; the output a previous build wrote for it stays. Composer's autoloader, PHPUnit and the rest keep running the last code that checked:

src/Example.phn:16:46: error P2202: function App\checkout() should return string but returns int
   16 | function checkout(Basket $basket): string => $basket->total();
      |                                              ^^^^^^^^^^^^^^^^
1 of 1 files failed to compile

phn build --emit-on-error writes the file all the same and still exits with 1. phn build --check --emit-on-error passes when such a file's output is what that build writes:

1 files up to date, 1 of them built with their errors (--emit-on-error)

The Composer plugin builds as phn build does, so composer install fails while the project has an error, after it has printed the findings.

Silencing a line

A comment with @phpstan-ignore or @phaenon-ignore silences a line: at the end of a line, that line; on a line of its own, the next one. @phpstan-ignore-line and @phpstan-ignore-next-line work as in PHPStan, so the suppressions of a migrated project keep working.

namespace App;

function total(list<int> $amounts): int => array_sum($amounts);

/** @param list<mixed> $rows */
function legacy(array $rows): int {
    // @phaenon-ignore P2103
    return total($rows);
}

The comment silences every finding on its line, whatever identifier follows it; the checker does not compare P2103 or PHPStan's argument.type with what it found, and does not report a comment that silences nothing.

Adopting the checker

On a code base that already has findings, exclude in phaenon.json is the baseline. List the files that have findings; phn check skips them, and phn build and the Composer plugin compile them without reporting their findings, so the project installs and builds:

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

Then fix one file at a time, and take it off the list. A finding you decide to keep gets an ignore comment on its line instead. phn build --emit-on-error writes a file that has errors while you work on it, for a test run, without excluding it.

A project migrated from PHP keeps the suppressions PHPStan honoured, and phn migrate lifts its docblock generics into syntax. In CI, phn check --format=github puts the findings on the pull request (Continuous integration).