ToolingLine maps and debugging

Tooling

Line maps and debugging

The line map every compiled file ends with, and how it puts stack traces, PHPUnit, PHPStan, coverage, Xdebug and production errors on .phn lines.

PHP runs the compiled file, so everything that reports a position (a stack trace, a PHPUnit failure, PHPStan, a coverage report, a log) reports a line of .src/Inventory.php, not of src/Inventory.phn. Every file phn build writes therefore ends with a line map, one comment that says which source line each compiled line came from. phn trace, the editor plugins and the phaenon/debug package read it, so that you read positions in your source.

The line map

src/Inventory.phn
namespace App;

final class Inventory
{
    private map<string, int> $stock = [];

    add(string $sku, int $quantity): void {
        $this->stock[$sku] = $this->count($sku) + $quantity;
    }

    take(string $sku, int $quantity): void throws OutOfStock {
        $left = $this->count($sku);
        if ($quantity > $left) {
            throw new OutOfStock($sku, $quantity, $left);
        }
        $this->stock[$sku] = $left - $quantity;
    }

    count(string $sku): int => $this->stock[$sku] ?? 0;
}
src/OutOfStock.phn
namespace App;

final class OutOfStock extends \RuntimeException
{
    __construct(public readonly string $sku, int $wanted, int $left) {
        parent::__construct(sprintf('%s: %d wanted, %d left', $sku, $wanted, $left));
    }
}

phn build writes .src/Inventory.php, whole:

<?php

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

declare(strict_types=1);

namespace App;

final class Inventory
{
    /**
     * @var array<string, int>
     */
    private array $stock = [];

    public function add(string $sku, int $quantity): void
    {
        $this->stock[$sku] = $this->count($sku) + $quantity;
    }

    /**
     * @throws OutOfStock
     */
    public function take(string $sku, int $quantity): void
    {
        $left = $this->count($sku);
        if ($quantity > $left) {
            throw new OutOfStock($sku, $quantity, $left);
        }
        $this->stock[$sku] = $left - $quantity;
    }

    public function count(string $sku): int
    {
        return $this->stock[$sku] ?? 0;
    }
}
// phaenon-map v1 ../src/Inventory.phn 1-6=1 7:1 11-13=5 14:5 17-17=7 18:8 21-23=11 24:11 25-25=11 26:12 34-36=19 37:20

The last line reads:

  • v1 is the format's version, and ../src/Inventory.phn the source, relative to the compiled file's directory, so the map holds wherever the two are deployed together.
  • 7:1 is a run: compiled line 7 is source line 1, and the lines after it follow one for one (8 is 2, 9 is 3) up to the next entry.
  • 11-13=5 is a hold: compiled lines 11 to 13, the docblock the compiler wrote for map<string, int>, all stand for source line 5.

So line 28 of the compiled file, the throw, falls in the run 26:12 and is line 14 of the .phn. The header, the docblocks, the braces and the return of an expression body are holds, which also keeps a breakpoint off them: a source line maps back to the first compiled line of a run. Code the compiler only copies keeps its lines; a generated docblock or an expanded body shifts what follows, which is why the map exists. A hand-written .php that a build copies has no map, and the tools leave its positions as they are.

__LINE__, __FILE__ and __DIR__

__LINE__ compiles to the source's line, as a number, so code that reads it sees the .phn line. __FILE__ and __DIR__ stay the compiled file's; that is why an output sits at the same depth as its source (phaenon.json).

you write
namespace App;

final class Probe
{
    /** The source line of this expression. */
    here(): int => __LINE__;
}
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

final class Probe
{
    /** The source line of this expression. */
    public function here(): int
    {
        return 6;
    }
}

Other code that observes lines, Throwable::getLine(), debug_backtrace(), ReflectionMethod::getStartLine(), reports compiled lines; translate them with phn trace or with phaenon/debug's LineMap (below).

Stack traces and PHPUnit

phn trace rewrites file.php:42, file.php(42) and file.php on line 42 wherever the file has a map, and passes everything else through. Pipe a command's output through it. A failing test, run in a container whose project lives at /app:

vendor/bin/phpunit
…
There was 1 error:

1) App\Tests\RestockTest::testTakesAfterRestocking
App\OutOfStock: pear: 2 wanted, 1 left

/app/.src/Inventory.php:28
/app/.tests/RestockTest.php:18
…
vendor/bin/phpunit 2>&1 | vendor/bin/phn trace
…
There was 1 error:

1) App\Tests\RestockTest::testTakesAfterRestocking
App\OutOfStock: pear: 2 wanted, 1 left

/app/src/Inventory.phn:14
/app/tests/RestockTest.phn:11
…

phn trace exits with 0, so a script that needs PHPUnit's status sets set -o pipefail first.

A trace from somewhere else, a production log or a container, names paths that do not exist on your machine. --root PREFIX=LOCAL reads the paths under the prefix from your checkout, which holds the same compiled files:

vendor/bin/phn trace --root /app=. < crash.txt
Fatal error: Uncaught App\OutOfStock: pear: 2 wanted, 1 left in src/Inventory.phn:14
Stack trace:
#0 /tmp/crash.php(5): App\Inventory->take('pear', 2)
#1 {main}
  thrown in src/Inventory.phn on line 14

The frame in /tmp/crash.php, a file without a map, is left as it was.

PHPStan

PHPStan analyses the outputs and reports their lines. Its raw format goes through phn trace:

/app/.src/Receipt.php:18:Method App\Receipt::total() should return string but returns int.
vendor/bin/phpstan analyse --no-progress --error-format=raw | vendor/bin/phn trace
/app/src/Receipt.phn:8:Method App\Receipt::total() should return string but returns int.

The github format becomes annotations GitHub can show: GitHub shows no annotation on a file the repository lacks, and the outputs are not in it. The map holds lines, so the column goes:

::error file=.src/Receipt.php,line=18,col=0::Method App\Receipt::total() should return string but returns int.
::error file=src/Receipt.phn,line=8::Method App\Receipt::total() should return string but returns int.

Reports and coverage

A report on standard input is read whole and written back as the same report, byte for byte except the positions that point into compiled files: Checkstyle (PHPStan's checkstyle format), JUnit (PHPUnit's --log-junit, PHPStan's junit), Clover and Cobertura.

vendor/bin/phn trace < junit.xml > junit.phn.xml
-      <testcase name="testTakesWhatIsThere" file="/app/.tests/InventoryTest.php" line="15" class="App\Tests\InventoryTest" classname="App.Tests.InventoryTest" assertions="1" time="0.001044"/>
+      <testcase name="testTakesWhatIsThere" file="/app/tests/InventoryTest.phn" line="9" class="App\Tests\InventoryTest" classname="App.Tests.InventoryTest" assertions="1" time="0.001044"/>

In coverage, the compiled lines that come from one source line count as that line, covered when any of them is, with the largest of their counts. An expression body's method line and its return both become line 19 here:

vendor/bin/phn trace < clover.xml > clover.phn.xml
-      <file name="/app/.src/Inventory.php">
+      <file name="/app/src/Inventory.phn">
 …
-        <line num="24" type="method" name="take" visibility="public" complexity="2" crap="2" count="2"/>
-        <line num="26" type="stmt" count="2"/>
-        <line num="27" type="stmt" count="2"/>
-        <line num="28" type="stmt" count="1"/>
-        <line num="30" type="stmt" count="1"/>
-        <line num="33" type="method" name="count" visibility="public" complexity="1" crap="1" count="2"/>
-        <line num="35" type="stmt" count="2"/>
+        <line num="11" type="method" name="take" visibility="public" complexity="2" crap="2" count="2"/>
+        <line num="12" type="stmt" count="2"/>
+        <line num="13" type="stmt" count="2"/>
+        <line num="14" type="stmt" count="1"/>
+        <line num="16" type="stmt" count="1"/>
+        <line num="19" type="method" name="count" visibility="public" complexity="1" crap="1" count="2"/>
+        <line num="19" type="stmt" count="2"/>

In Cobertura, <source> becomes the directory that holds both trees, and every filename is written from there (src/Inventory.phn), which is how GitLab matches a report to the repository's files.

Note: PCOV measures only the directory pcov.directory names, and by default it picks src when there is one. In a Phaenon project src/ holds the .phn, so the outputs go unmeasured and every count is 0. Run PHPUnit as php -d pcov.directory=. vendor/bin/phpunit, or set pcov.directory in php.ini.

Xdebug in PhpStorm

The PhpStorm plugin debugs .phn through the line map, with PhpStorm's own debugger and Xdebug 3. The plugin's README describes it as follows:

  • a breakpoint set in a .phn goes to Xdebug as one on the compiled file, at the first compiled line of that source line, never on a docblock or a brace the compiler wrote;
  • the execution point, the inline values and each frame show in the .phn, at the mapped line;
  • Step Over and Step Into step by source line: a stop on a line the compiler wrote for the line the step started from steps again;
  • variables, watches and Evaluate work unchanged, since the compiled code keeps every identifier;
  • path.php:42, path.php(42) and in path.php on line 42 in a Run, Debug or Test console, in the terminal and in Analyze Stack Trace link to the .phn line.

Nothing needs configuring beyond PHP debugging itself: the run configuration runs the compiled code (PHPUnit with .tests, bin/console, a web server), and a remote server's path mappings map the project root, which holds the sources and the outputs alike. The Frames list still labels a compiled frame with the compiled file's name and line, and coverage in PhpStorm reports compiled lines. VS Code has no Phaenon debugging yet (Editors).

In production: phaenon/debug

phaenon/debug points logged exceptions and Sentry events at .phn positions. It is opt-in and used on error paths only: compiled code never calls it, and a request that throws nothing never loads a map.

composer require phaenon/debug

It needs PHP 8.3 or later and reads version 1 of the map, whichever compiler release wrote it. Monolog 3 and the Sentry SDK 4 are suggested, not required.

Monolog

LineMapProcessor rewrites the record's context.exception, its previous exceptions and their traces, so every formatter and handler writes source positions:

$logger->pushProcessor(new \Phaenon\Debug\Monolog\LineMapProcessor());

The same error logged with Monolog's LineFormatter, without and with the processor:

[2026-11-15T17:35:59.076084+00:00] app.ERROR: Checkout failed {"exception":"[object] (DomainException(code: 0): pear: 2 wanted, 1 left at /app/.src/Checkout.php:21)
…
[2026-11-15T17:35:59.092167+00:00] app.ERROR: Checkout failed {"exception":"[object] (DomainException(code: 0): pear: 2 wanted, 1 left at /app/src/Checkout.phn:11)
…

The package's README adds that a record message quoting the exception's compiled position, as Symfony's Uncaught PHP Exception … at Foo.php line 57 does, quotes the source position instead.

Sentry

LineMapIntegration replaces each frame in a compiled file with one in the .phn: the path, the line and closure names. When the .phn is deployed beside the compiled tree, the context lines Sentry shows come from it:

\Sentry\init([
    'dsn' => '…',
    'integrations' => [new \Phaenon\Debug\Sentry\LineMapIntegration()],
]);

The frame of the same exception, as the event carries it without and with the integration:

/.src/Checkout.php:21 App\Checkout::take
/src/Checkout.phn:11 App\Checkout::take

With Sentry's code mappings, such a frame links to the .phn in your repository. Ship the .phn in the image beside .src/ to get its lines as context (Continuous integration).

Symfony

The package's README registers both as services:

# config/services.yaml
services:
    Phaenon\Debug\Monolog\LineMapProcessor:
        tags: [monolog.processor]

    Phaenon\Debug\Sentry\LineMapIntegration: ~

# config/packages/sentry.yaml (sentry/sentry-symfony)
sentry:
    options:
        integrations:
            - Phaenon\Debug\Sentry\LineMapIntegration

The tag without a channel or handler adds the processor to every logger.

Other error reporters

Phaenon\Debug\LineMap reads a compiled file's map, and ThrowableRewriter::rewrite($e) points a throwable, its trace and its previous ones at the source in place, which is what the two integrations are built on:

use Phaenon\Debug\LineMap;

LineMap::locate('/app/.src/Inventory.php', 28);   // ['/app/src/Inventory.phn', 14], or null without a map