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
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(...)));
}<?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
| Test | Narrows 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 bytes | string&bytes (see text and bytes) |
a guard function with @phpstan-assert | what 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)giveslist<mixed>; nothing in PHP tests that every element is anint. 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'])andarray_key_exists('id', $row)on anarray<mixed>say that the key is there, not what it holds:$row['id']staysmixeduntil a test of its value.gettype($x)and a resource.gettype($x) === 'integer'narrows$xasis_int($x)does, and so do'boolean','double','string','array','object'and'NULL', in anif, aswitchor amatch.'resource'narrows nothing: writeis_resource($x).- A property after a call that may change it. What was narrowed about
$this->emailis forgotten after a call to a method of the class that returnsvoid, 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
| Code | When |
|---|---|
P2103 | A value used before a test narrows it to the type expected |
P2305 | === or !== between types that cannot be equal |
P2306 | instanceof 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 |
P2401 | A warning: code after a statement that never completes |
P2402 | A condition that always has the same result, such as is_int() on an int |
P1001 | A leftover is, as or as? |
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;
}src/Example.phn:9:9: error P2306:
9 | if ($circle instanceof Circle && is_int($n)) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^
src/Example.phn:9:38: error P2402:
9 | if ($circle instanceof Circle && is_int($n)) {
| ^^^^^^^^^^
src/Example.phn:10:16: error P2307:
10 | return $circle?->radius;
| ^^^^^^^^^^^^^^^^
1 files checked: 3 errors, 0 warningsIn 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
- Lists, maps and tuples
- Named shapes and type aliases
- Generics, for
instanceofwith aclass<T>