LanguageLists, maps and tuples

Language

Lists, maps and tuples

list<T>, map<K, V>, tuples and array<V>, the collection types of Phaenon, and how they erase to PHP arrays with PHPStan docblocks.

A PHP array is a list and a dictionary at once, and its type says neither. Phaenon has a type for each: list<T> for values in order, map<K, V> for values under keys, and the tuple (A, B) for a fixed number of values of their own types. All three are PHP arrays at run time. They are the types PHPStan already knows from docblocks, written in the signature, and the compiled PHP keeps them in docblocks.

At a glance

you write
namespace App;

final class Line
{
    __construct(public string $sku, public int $quantity) {}
}

function parse(string $row): (string, int) {
    [$sku, $quantity] = explode(',', $row, 2);

    return [$sku, (int) $quantity];
}

function totals(list<Line> $lines): map<string, int> {
    $totals = [];
    foreach ($lines as $line) {
        $totals[$line->sku] = ($totals[$line->sku] ?? 0) + $line->quantity;
    }

    return $totals;
}
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

final class Line
{
    public function __construct(public string $sku, public int $quantity) {}
}

/**
 * @return array{string, int}
 */
function parse(string $row): array
{
    [$sku, $quantity] = explode(',', $row, 2);

    return [$sku, (int) $quantity];
}

/**
 * @param list<Line> $lines
 * @return array<string, int>
 */
function totals(array $lines): array
{
    $totals = [];
    foreach ($lines as $line) {
        $totals[$line->sku] = ($totals[$line->sku] ?? 0) + $line->quantity;
    }

    return $totals;
}

list<T>

A list<T> has the keys 0, 1, …, n-1 in that order, and values of type T: what array_is_list() returns true for. An array literal without keys is one, and so is what array_values(), explode(), array_keys() and str_split() return.

The checker follows the list through the code that changes it, as PHPStan does. $xs[] = $v keeps a list (a non-empty one). Writing at an index the checker cannot prove is in range turns it into a map<int, T>, since a gap may have appeared; array_values() makes it a list again.

you write
namespace App;

function sum(list<int> $xs): int => array_sum($xs);

function bump(list<int> $xs, int $at): int {
    $xs[$at] = 0;

    return sum($xs);
}
$ phn checkexit 1
src/Example.phn:8:16: error P2103: argument 1 ($xs) of App\sum() expects list<int>, non-empty-array<int, int> given
    8 |     return sum($xs);
      |                ^^^
1 files checked: 1 errors, 0 warnings

unset($xs[$i]) leaves a gap too: the list becomes a map<int, T>, no longer known to be non-empty, and passing it on as a list<int> is the same P2103. Call array_values() after an unset() on a list.

map<K, V>

A map<K, V> has keys of type K and values of type V, in any order. A key is an int or a string, as PHP allows; any other key type is P2518. A string that PHP would store as an integer key, such as '42', is typed as the integer key it becomes.

A list<T> is a map<int, T>, so a list goes wherever a map with integer keys is expected; the reverse is an error. Both are covariant: a list<Admin> is a list<User> when every Admin is a User, which is sound because PHP copies an array when it is changed.

array<V> and array<mixed>

array<V> is an array of V whose keys do not matter: a list or a map, PHPStan's one-argument form. array<mixed> is any array. A bare array with no element type is P2516 in a declaration, because the compiled PHP would then carry no element type for PHPStan; the one exception is a method that overrides one whose docblock gives the type.

you write
namespace App;

function count_rows(array $rows): int => count($rows);
$ phn checkexit 1
src/Example.phn:3:21: error P2516: parameter $rows of count_rows(): array with no element type (array<mixed> for any)
    3 | function count_rows(array $rows): int => count($rows);
      |                     ^^^^^^^^^^^
1 files checked: 1 errors, 0 warnings

An array from code that types it only array (a PHP library without docblocks, json_decode()) is array<mixed> or mixed, and does not go where a list<T> or a map<K, V> is expected until a test narrows it. See type tests and narrowing.

Tuples

(string, int) is a tuple: a list of exactly two values, a string then an int. It is built with an array literal, [$sku, 3], and read by destructuring, [$sku, $quantity] = $pair, or by index. A tuple is exact: a value with three entries is not a (string, int), and $pair[2] is P2313. Tuples nest in other types, as in list<(string, int)> or ?(int, int).

A tuple is a type only. Nothing checks at run time that an array has two entries of those types; the code that builds the value is what makes it one, as in PHP.

Literals

An array literal has the most precise type the checker can give it, and widens where it meets a declared type:

LiteralIts typeGoes where these are expected
[]the empty arrayany list<T>, map<K, V> or array<V>
[1, 2, 3]list{1, 2, 3}list<int>, (int, int, int)
['a' => 1, 'b' => 2]array{a: 1, b: 2}map<string, int>
[...$xs, ...$ys]a list<T> when both are lists

Because the literal keeps its keys, $options['limit'] is known to be an int after $options = ['limit' => 10], and a key it lacks is P2313.

PHP's array functions

PHP's functions are called as they are, and the checker types them as PHPStan does, from the stubs compiled into phn and a few refinements of its own:

CallResult
array_keys($map) with a map<string, int>list<string>
array_values($xs)list<T>
array_map($fn, $list)list<U>, keys kept
array_map($fn, $map)map<K, U>, keys kept
array_filter($list, $fn)map<int, T>: the keys survive, so it is no longer a list
explode(',', $s)a non-empty list<string>
json_decode($s, true)mixed

A list or a map is not an object: $xs->count() is P2105, as PHP would fail on it.

Refinements from docblocks

non-empty-list<T>, non-empty-array<K, V>, non-empty-string, positive-int and the rest of PHPStan's vocabulary are read from docblocks, in .php and .phn alike, and the checker infers some of them (count($xs) > 0 makes a list non-empty). They cannot be written in a signature, where list<T> and map<K, V> are the types: write the refinement in a @param or @return tag above it.

Variadic parameters

Inside its function, string ...$parts is an array<string>, not a list<string>: since PHP 8.0, a call with named arguments, glue(a: 'x'), collects them under their names. Call array_values($parts) where a list is needed. A caller passes strings, or spreads an iterable of strings with ....

What the checker reports

CodeWhen
P2103A collection where another is expected: a map for a list, a list of the wrong element type, a tuple of the wrong length
P2105A method call on a list, a map or a tuple
P2313A literal offset the array is known not to have
P2516A declaration typed array with no element type
P2518A map key type outside int|string
you write
namespace App;

function pairs(list<(string, int)> $pairs): int => count($pairs);

function flags(map<bool, string> $labels): void {}

function demo(): int => pairs([['a', 1], ['b', 2, true]]);
$ phn checkexit 1
src/Example.phn:5:20: error P2518: a map key is int|string, not bool
    5 | function flags(map<bool, string> $labels): void {}
      |                    ^^^^
src/Example.phn:7:31: error P2103: argument 1 ($pairs) of App\pairs() expects list<list{string, int}>, list{list{'a', 1}, list{'b', 2, true}} given
    7 | function demo(): int => pairs([['a', 1], ['b', 2, true]]);
      |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^
1 files checked: 2 errors, 0 warnings

In the compiled PHP

Every collection type is array in the signature, and its full type goes into the docblock:

In the .phnIn the docblock
list<T>list<T>
map<K, V>array<K, V>
array<V>array<V>
(string, int)array{string, int}

PHPStan on the compiled PHP sees the same types the checker saw. Nothing is checked at run time that PHP does not check: a PHP caller can pass any array to a list<int> parameter, as it can to a PHP function documented @param list<int>.

Migrating

phn migrate lifts the array types of PHPStan docblocks into signatures: @param list<T> $xs becomes list<T> $xs, array<K, V> becomes map<K, V> (array<array-key, V> and V[] become array<V>), and a bare array whose docblock says nothing becomes array<mixed>. With --list-types, it also types bare arrays from the values they hold, for code that PHPStan never checked at a high level. See migrate a PHP project.

See also