LanguageType tests and narrowing

Language

Type tests and narrowing

Phaenon has no type-test operators; PHP's own tests (is_int, instanceof, array_is_list, count, isset, match) narrow types as PHPStan narrows them.

A type test in Phaenon is PHP's own: is_int($x), $x instanceof User, $x === null, is_array($x) && array_is_list($x). The checker reads the test and narrows the value's type where the test holds, as PHPStan does, so that $x is an int inside if (is_int($x)). A .phn file reads as PHP here: the line that tests is the line that runs, and the compiled PHP is the same line.

At a glance

you write
namespace App;

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

function emailOf(mixed $value): ?string {
    if ($value instanceof User) {
        return $value->email;
    }
    if (is_string($value) && str_contains($value, '@')) {
        return $value;
    }

    return null;
}

/** @return list<string> */
function tags(mixed $decoded): array {
    if (!is_array($decoded) || !array_is_list($decoded)) {
        return [];
    }

    return array_values(array_filter($decoded, is_string(...)));
}
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) {}
}

function emailOf(mixed $value): ?string
{
    if ($value instanceof User) {
        return $value->email;
    }
    if (is_string($value) && str_contains($value, '@')) {
        return $value;
    }

    return null;
}

/** @return list<string> */
function tags(mixed $decoded): array
{
    if (!is_array($decoded) || !array_is_list($decoded)) {
        return [];
    }

    return array_values(array_filter($decoded, is_string(...)));
}

$value is mixed on entry, a User in the first branch, a string in the second. After the early return, $decoded is a list<mixed>, and array_filter() with is_string(...) keeps the strings.

What narrows

TestNarrows to, where it holds
is_int($x), is_string($x), is_bool($x), is_float($x), is_array($x), is_object($x), is_callable($x), is_numeric($x)the type tested
$x instanceof User, $x instanceof $class with $class a class<T>User, T
$x === null, $x !== null, isset($x)null, or the type without null
$x === 'a', in_array($x, ['a', 'b'], true)the literal types 'a', 'a'|'b'
is_array($x) && array_is_list($x)list<mixed>
count($xs) > 0, $xs !== []a non-empty array
mb_check_encoding($b, 'UTF-8') on bytesstring&bytes (see text and bytes)
a guard function with @phpstan-assertwhat its tag says

The negation narrows the other way: after if (!$x instanceof User) { return; }, $x is a User. Narrowing follows &&, ||, !, ternaries, early return, throw, continue and break, assert(), a switch on the value, and a test stored in a variable first ($isUser = $x instanceof User; if ($isUser) …).

match (true) narrows in each arm:

namespace App;

interface Shape {}

final class Circle implements Shape
{
    __construct(public float $radius) {}
}

final class Square implements Shape
{
    __construct(public float $side) {}
}

function area(Shape $shape): float => match (true) {
    $shape instanceof Circle => M_PI * $shape->radius ** 2,
    $shape instanceof Square => $shape->side ** 2,
    default => throw new \LogicException('unknown shape ' . $shape::class),
};

A checked conversion

Phaenon has no cast that checks. A value that must be an int and might not be is written as PHP writes it, the test and the failure together:

namespace App;

final class User {}

/** @param map<string, mixed> $values */
function limit(array $values): int {
    $limit = $values['limit'] ?? 10;

    return is_int($limit) ? $limit : throw new \TypeError('limit must be an int, got ' . get_debug_type($limit));
}

function owner(mixed $value): ?User => $value instanceof User ? $value : null;

Your own guards

A test PHP has no function for, such as "a list of strings" or "a pair of ints", is a function or a method you write, with a PHPStan assertion tag. The checker honours @phpstan-assert, @phpstan-assert-if-true and @phpstan-assert-if-false (and their @psalm- spellings) as PHPStan does:

namespace App;

/** @phpstan-assert-if-true list<string> $value */
function isStringList(mixed $value): bool => is_array($value)
    && array_is_list($value)
    && array_all($value, fn (mixed $item): bool => is_string($item));

/** @phpstan-assert-if-true array{int, int} $value */
function isPair(mixed $value): bool => is_array($value) && array_is_list($value) && count($value) === 2
    && is_int($value[0]) && is_int($value[1]);

function joined(mixed $value): string => isStringList($value) ? implode(', ', $value) : '';

function window(mixed $value): ?(int, int) => isPair($value) ? $value : null;

The checker trusts the tag: it does not verify that the body tests what the tag claims.

What does not narrow

  • A collection's contents. is_array($x) && array_is_list($x) gives list<mixed>; nothing in PHP tests that every element is an int. Write a guard as above, or filter.
  • A tuple or a shape. They are types only, with no test of their own: a guard with a tag, or a test of each entry the code reads, does the work.
  • isset($row['id']) and array_key_exists('id', $row) on an array<mixed> say that the key is there, not what it holds: $row['id'] stays mixed until a test of its value.
  • gettype($x) and a resource. gettype($x) === 'integer' narrows $x as is_int($x) does, and so do 'boolean', 'double', 'string', 'array', 'object' and 'NULL', in an if, a switch or a match. 'resource' narrows nothing: write is_resource($x).
  • A property after a call that may change it. What was narrowed about $this->email is forgotten after a call to a method of the class that returns void, as PHPStan forgets it. Copy the property into a variable first.

No is or as

Releases before 0.4.0 had operators is, as and as?. They are gone, since each was a second spelling of a PHP test: $x is int is is_int($x). A leftover is P1001, whose message gives the PHP test, and phn fmt run in the project rewrites each into the test it compiled to:

if ($x is int) { … }        // becomes: if (is_int($x)) { … }
$u = $y as User;            // becomes: $u = $y instanceof User ? $y : throw new \TypeError('expected App\\User, got ' . get_debug_type($y));
$v = $z as? User;           // becomes: $v = $z instanceof User ? $z : null;

What the checker reports

CodeWhen
P2103A value used before a test narrows it to the type expected
P2305=== or !== between types that cannot be equal
P2306instanceof that is always true or always false
P2307?-> that does nothing: on a value that is never null, or on a property that ??, isset() or empty() reads, which forgive the null themselves
P2308?? on a value that is never null
P2401A warning: code after a statement that never completes
P2402A condition that always has the same result, such as is_int() on an int
P1001A leftover is, as or as?
you write
namespace App;

final class Circle
{
    public float $radius = 1.0;
}

function radius(Circle $circle, int $n): float {
    if ($circle instanceof Circle && is_int($n)) {
        return $circle?->radius;
    }

    return 0.0;
}
$ phn checkexit 1
src/Example.phn:9:9: error P2306: App\Circle is always an instance of App\Circle
    9 |     if ($circle instanceof Circle && is_int($n)) {
      |         ^^^^^^^^^^^^^^^^^^^^^^^^^
src/Example.phn:9:38: error P2402: is_int() on int is always true
    9 |     if ($circle instanceof Circle && is_int($n)) {
      |                                      ^^^^^^^^^^
src/Example.phn:10:16: error P2307: ?-> on App\Circle, which is never null
   10 |         return $circle?->radius;
      |                ^^^^^^^^^^^^^^^^
1 files checked: 3 errors, 0 warnings

In the compiled PHP

The tests are PHP and stay as written. The compiler adds no check of its own anywhere: a value that crosses into Phaenon code from PHP is what its type says because the code that produced it says so, or because your code tested it.

See also