LanguagePipes and partial application

Language

Pipes and partial application

PHP 8.5's pipe operator with PHP 8.6's partial application, compiled for an 8.5 target where the lowering is exact and refused where it is not.

The pipe operator |> is PHP 8.5's: $x |> f(...) calls f($x). Partial application is PHP 8.6's: str_replace(' ', '-', ?) is a closure that takes the ? argument. Together they write a chain of calls in the order it runs, without nested parentheses or arrow functions. Phaenon accepts both whatever the project's PHP target, and compiles them to what that target can run.

At a glance

For a project whose target is PHP 8.5, the default, the pipelines become nested calls:

you write
namespace App;

final class User
{
    __construct(public string $email, public bool $active) {}
}

function activeEmails(list<User> $users): list<string> {
    return $users
        |> array_filter(?, fn (User $u): bool => $u->active)
        |> array_map(fn (User $u): string => strtolower($u->email), ?)
        |> array_values(...);
}

function slug(string $title): string => $title
    |> trim(...)
    |> strtolower(...)
    |> str_replace(' ', '-', ?);
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

final class User
{
    public function __construct(public string $email, public bool $active) {}
}

/**
 * @param list<User> $users
 * @return list<string>
 */
function activeEmails(array $users): array
{
    return array_values(array_map(
        fn (User $u): string => strtolower($u->email),
        array_filter($users, fn (User $u): bool => $u->active),
    ));
}

function slug(string $title): string
{
    return str_replace(' ', '-', strtolower(trim($title)));
}

The target

A project compiles for a target, the oldest PHP its output must run on: 8.5 or 8.6, stated as "php" in phaenon.json or read from composer.json's require.php (see phaenon.json). Every construct of PHP 8.6 parses whatever the target. The target decides what the output may hold:

  • Target 8.6: pipes and partial application are PHP's own, and pass through as written.
  • Target 8.5: pipes are PHP's own too, but partial application is not. The compiler lowers it to PHP 8.5 code where the result does exactly what PHP 8.6 would, and refuses it where it cannot (P1002).

The same file compiled for 8.6:

you write
namespace App;

final class User
{
    __construct(public string $email, public bool $active) {}
}

function activeEmails(list<User> $users): list<string> {
    return $users
        |> array_filter(?, fn (User $u): bool => $u->active)
        |> array_map(fn (User $u): string => strtolower($u->email), ?)
        |> array_values(...);
}

function slug(string $title): string => $title
    |> trim(...)
    |> strtolower(...)
    |> str_replace(' ', '-', ?);
phn build writes, for PHP 8.6
<?php

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

declare(strict_types=1);

namespace App;

final class User
{
    public function __construct(public string $email, public bool $active) {}
}

/**
 * @param list<User> $users
 * @return list<string>
 */
function activeEmails(array $users): array
{
    return $users
        |> array_filter(?, fn (User $u): bool => $u->active)
        |> array_map(fn (User $u): string => strtolower($u->email), ?)
        |> array_values(...);
}

function slug(string $title): string
{
    return $title
        |> trim(...)
        |> strtolower(...)
        |> str_replace(' ', '-', ?);
}

Note: PHPStan 2.3 does not read partial application yet: on output compiled for 8.6 that holds a placeholder, it stops with an internal error. Output compiled for 8.5 holds none.

Partial application

A call with placeholders is a closure:

  • ? stands for one argument, and name: ? for a named one;
  • ... stands for every remaining argument;
  • positional placeholders come before named ones, and ... comes last.

The checker types the result as a Closure over the parameters the placeholders stand for, with their declared types: str_pad(?, 10, '-') is a Closure(string): string. A placeholder count that does not fit the function, or a bound argument of the wrong type, is reported where PHP 8.6 would throw at run time.

A placeholder in a built-in function's variadic parameter gives the closure PHP 8.6 creates, with the return type PHP declares for the function: sprintf('%s: %s', 'id', ?) returns a string, and max(1, ?) returns mixed, since that is max()'s declared type.

What "exact" means

PHP 8.6 evaluates the bound arguments of a partial application once, when the closure is made, and the left side of a pipe before the arguments of its stage. A lowering to PHP 8.5 must keep that order. The compiler writes, from the most to the least direct:

SourceLowered for 8.5 toWhen
$x |> f(...), $x |> f($a, ?)f($x), f($a, $x), a run of stages as nested callsthe callee is a named function, a static method, or a method of $this or of a variable; the arguments before the placeholder are literals, constants, closures, or variables the left side does not write
$x |> f(g(), ?)$x |> (fn(T $p) => f(g(), $p))otherwise: the arrow function is called at once, after $x
f($a, ?) outside a pipefn(T $p) => f($a, $p)every bound argument is a literal, a constant or a variable
f(g(), ?) outside a piperefused, P1002a bound argument is computed: a closure would compute it at every call

T is the parameter's declared type, so the closure rejects what the partial application would reject. A pipe that cannot fold:

you write
namespace App;

final class Output
{
    /** @var list<string> */
    public array $lines = [];

    write(string $line): void {
        $this->lines[] = $line;
    }
}

final class Rule
{
    __construct(private Output $out, private string $char) {}

    char(): string => $this->char;

    draw(int $width): void {
        $width
            |> str_repeat($this->char(), ?)
            |> $this->out->write(...);
    }
}
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

final class Output
{
    /** @var list<string> */
    public array $lines = [];

    public function write(string $line): void
    {
        $this->lines[] = $line;
    }
}

final class Rule
{
    public function __construct(private Output $out, private string $char) {}

    public function char(): string
    {
        return $this->char;
    }

    public function draw(int $width): void
    {
        $width
            |> (fn(int $times) => str_repeat($this->char(), $times))
            |> $this->out->write(...);
    }
}

$this->char() comes before the placeholder and is a call, so the stage becomes an arrow function that the pipe calls at once, after $width. $this->out->write(...) stays a stage: a method of a property does not fold, since PHP 8.6 reads the property after the left side has run.

A partial application outside a pipe whose bound argument is computed is refused for an 8.5 target, with the fix in the message:

you write
namespace App;

function prefix(): string => '> ';

function padder(): \Closure => str_pad(?, 10, prefix());
$ phn checkexit 1
src/Example.phn:5:32: error P1002: this partial application needs PHP 8.6 (target 8.5): a bound argument is computed (a call, a property, an operator), which a closure written for PHP 8.5 would compute at every call: assign it to a variable first, or target PHP 8.6
    5 | function padder(): \Closure => str_pad(?, 10, prefix());
      |                                ^^^^^^^^^^^^^^^^^^^^^^^^
1 files checked: 1 errors, 0 warnings

Pipes

The right side of |> is a callable that receives the left side, as in PHP: a first-class callable f(...), a partial application, a closure in parentheses, or a value holding a callable. Phaenon adds no topic variable and no first-argument insertion. The checker types a pipeline stage by stage, and reports what PHP would throw at run time: a stage whose piped parameter is by reference ($xs |> sort(...) is P2114), a stage that needs more than one argument (P2101), and a right side that is not callable (P2109).

you write
namespace App;

/** @param list<int> $xs */
function sorted(array $xs): void {
    $xs |> sort(...);
}
$ phn checkexit 1
src/Example.phn:5:5: error P2114: parameter $array of sort() is by reference, and |> passes its left side by value: PHP throws an Error
    5 |     $xs |> sort(...);
      |     ^^^
1 files checked: 1 errors, 0 warnings

What the checker reports

CodeWhen
P1002A construct of PHP 8.6 that cannot be lowered for an 8.5 target
P1003A placeholder where PHP forbids one, such as ... twice or after ?->
P2101, P2102Too few or too many placeholders and arguments for the function
P2010A named placeholder or argument that the function lacks, or that overwrites another
P2103A bound argument of the wrong type
P2109A right side of |> that is not callable
P2114A piped value passed to a by-reference parameter
P2205The result of a void stage piped into another stage

Migrating

phn migrate writes chains of three nested calls or more as pipelines, where the pipeline is exact (--pipes=2 from two calls, --keep-calls for none): array_values(array_filter(array_map($f, $users), $g)) becomes $users |> array_map($f, ?) |> array_filter(?, $g) |> array_values(...). Migrate checks the file before and after, and gives a file its calls back when the rewrite would change a type or a finding. For an 8.5 target, the compiled PHP is the nested calls you started from.

See also