Skip to content

Overview

AST

A type is a tree of TypeLang\Type\* nodes. The parser builds it from a string, the reader from Reflection, the printer turns it back into a string.

composer require type-lang/types
Example<string, int, *>|null
union
type
args
type
type
wildcard
literal

resultTypeLang\Type\LogicalTypeNode\UnionTypeNode

The tree is plain objects, it can be built by hand:

use TypeLang\Type\Literal\NullLiteralNode;
use TypeLang\Type\LogicalTypeNode\UnionTypeNode;
use TypeLang\Type\Name;
use TypeLang\Type\NamedTypeNode;
use TypeLang\Type\Template\TemplateListNode;
use TypeLang\Type\Template\TypedTemplateArgumentNode;
use TypeLang\Type\Template\WildcardTemplateArgumentNode;
$type = new UnionTypeNode([
new NamedTypeNode(
name: new Name('Example'),
arguments: new TemplateListNode([
new TypedTemplateArgumentNode(
new NamedTypeNode(new Name('string')),
),
new TypedTemplateArgumentNode(
new NamedTypeNode(new Name('int')),
),
new WildcardTemplateArgumentNode(),
]),
),
new NullLiteralNode(),
]);
echo new TypeLang\Printer\PrettyTypePrinter()->print($type);
// Example<string, int, *>|null

A node with children is a list or holds its children in public properties. Lists (unions, intersections, template arguments, shape fields, parameters) are indexed, iterable and countable:

$type[0]->name->value; // 'Example'
$type[0]->arguments[1]->value->name->value; // 'int'
count($type[0]->arguments); // 3

The tree is mutable, names and literals are immutable values: a changed name is a new Name.

$type[0]->name = new Name('iterable');
// iterable<string, int, *>|null
$type[0]->name->value = 'iterable';
// throws Error: Cannot modify readonly property TypeLang\Type\Name::$value

Every node keeps the $offset of its first character in the source, 0 for a node built by hand:

$type = new TypeLang\Parser\TypeParser()->parse('list<int>|null');
$type[1]->offset; // 10, the "null"
$type[0]->arguments->offset; // 5, the "<"

To walk or rewrite a whole tree, use the traverser and its visitors.

Node

abstract TypeLang\Type\Node

readonly int $offset

Token offset defined in the source code.

TypeNode

abstract TypeLang\Type\TypeNode extends Node

A node standing where a type is expected.

NodesListNode

abstract TypeLang\Type\NodesListNode extends Node

An ordered list of nodes of one kind, like the arguments of a generic or the fields of a shape.

array $children

SymbolNode

abstract TypeLang\Type\SymbolNode extends Node

A node that stands for a piece of text: an identifier, a name or a variable.

The text of a node is the one it is written with, so a node is told apart from the others by toString() alone.

NamedTypeNode

final TypeLang\Type\NamedTypeNode extends TypeNode

A type referenced by name, along with whatever the name is followed by.

The meaning of what follows is left to whoever reads the tree, as it depends on the type the name stands for. A FOO may be a constant or a class, and the template arguments of an array{a: int, ...<string, int>} are not the ones of an array<int>.

 Some\Any<int, string>
 ^^^^^^^^              the name
         ^^^^^^^^^^^^^ the template arguments

 array{name: string}
 ^^^^^               the name
      ^^^^^^^^^^^^^^ the shape fields

object{name: string, ...<string, mixed>}
^^^^^^                                   the name
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the shape fields
                        ^^^^^^^^^^^^^^^  the template arguments
Name $name
?Template\TemplateListNode $arguments

Template arguments of a type, or null in case of the name is followed by none.

The list is never empty.

 Some       // null
 Some<int>  // a list of 1 argument
?Shape\FieldListNode $fields

Shape fields of a type, or null in case of the name is followed by none. An empty list is not the same as a null: A shape may well be written with no fields at all.

 array           // null: no shape
 array{}         // an empty list: a shape of no fields
 array{a: int}   // a list of 1 field

Name

final TypeLang\Type\Name extends SymbolNode

A name: the namespace it begins with and the word it ends in.

 Some\Any
 ^^^^     the namespace
      ^^^ the word

 \Some\Any
 ^^^^^     a fully qualified namespace begins in a separator

 \Any
 ^    the root namespace

 non-empty-string
 ^^^^^^^^^^^^^^^^ a single word, there is no namespace
readonly string $value

The last word of the name, it has no separators.

readonly ?NamespaceName $namespace

The namespace the word belongs to, or null in case of the name is written with none.

NamespaceName

final TypeLang\Type\NamespaceName extends Node

A namespace a name or a mask of constants belongs to.

 Some\Any\Name
 ^^^^^^^^      a qualified namespace

 \Some\Any\Name
 ^^^^^^^^^      a fully qualified namespace begins in a separator

 namespace\Some\Name
 ^^^^^^^^^^^^^^      a namespace relative to the current one

The class cannot be named Namespace, the word is reserved by PHP.

readonly string $value

The words of the namespace with the separators between them and with no one at the ends. The namespace keyword and the leading separator are not the words.

readonly NamespaceName\NamespaceKind $kind

From where the namespace is read.

NamespaceKind

enum TypeLang\Type\NamespaceName\NamespaceKind

How the namespace of a name is written, that is, from where it is read.

case Qualified

A namespace written as it is.

 Some\Any\Name
 ^^^^^^^^
case FullyQualified

A namespace that begins in a separator, it is read from the root.

 \Some\Any\Name
 ^^^^^^^^^

 \Name
 ^     the root namespace has no words
case NamespaceRelative

A namespace that begins in the namespace keyword, it is read from the current one. The keyword is not a word of the namespace.

 namespace\Some\Name
 ^^^^^^^^^^^^^^

 namespace\Name
 ^^^^^^^^^      the current namespace has no words

Identifier

final TypeLang\Type\Identifier extends SymbolNode

A single word, the one that has no namespace separators in it.

 Some\Any::CONST_NAME
           ^^^^^^^^^^ a single word

 Some\Any::BAR*BAZ
           ^^^ ^^^ two single words
readonly string $value

VariableNode

final TypeLang\Type\VariableNode extends SymbolNode

A variable, written as a name with a $ in front of it.

 callable(int $value): void
 //           ^^^^^^ names a parameter

 ($value is int ? string : bool)
 //^^^^^ stands as the subject of a condition
string $name

The name of the variable, written without the leading $.

ThisTypeNode

final TypeLang\Type\ThisTypeNode extends TypeNode

The type of the object a method is called on, written as a $this.

 callable(): $this

It is written the way a variable is, but it is a type. Any other variable is a VariableNode and no type at all.

LogicalTypeNode

abstract TypeLang\Type\LogicalTypeNode extends TypeNode

Several types joined by an operator, like a union or an intersection.

A type of the same kind is flattened into its parent: an A|(B|C) holds the three types side by side.

The flattening and the minimum of two types are checked on creation only. Since PHP 8.4, property hooks make it possible to keep the checks permanent.

array $children

UnionTypeNode

final TypeLang\Type\LogicalTypeNode\UnionTypeNode extends LogicalTypeNode

Any one of several types.

 int|string|null

IntersectionTypeNode

final TypeLang\Type\LogicalTypeNode\IntersectionTypeNode extends LogicalTypeNode

All of several types at once.

 Some\Any & Stringable

WrappingTypeNode

abstract TypeLang\Type\WrappingTypeNode extends TypeNode

A type built around another one.

 ?Some\Any
 ^         the wrapping type
  ^^^^^^^^ the type it wraps
TypeNode $type

NullableTypeNode

final TypeLang\Type\WrappingTypeNode\NullableTypeNode extends WrappingTypeNode

A type a null is allowed besides, written with a leading ?.

 ?Some\Any

TypesListTypeNode

final TypeLang\Type\WrappingTypeNode\TypesListTypeNode extends WrappingTypeNode

A list of the wrapped type, written in the legacy [] notation.

 Some\Any[]
 ^^^^^^^^   the type the list is made of

 Some\Any[][]
 ^^^^^^^^^^   a list the outer list is made of

TypeOffsetAccessTypeNode

final TypeLang\Type\TypeOffsetAccessTypeNode extends TypeNode

The type standing at an offset of another type.

 Some\Any[int]
 ^^^^^^^^      the type an offset is taken of
          ^^^  the offset itself
TypeNode $type

The type an offset is taken of.

TypeNode $access

The type standing in the square brackets.

LiteralNode

abstract TypeLang\Type\Literal\LiteralNode extends TypeNode

A value standing where a type is expected, kept both as PHP sees it and as it is written.

The two are not the same thing. A value is what PHP would compute, while a raw is the very text it was computed from, quotes, radix and all.

 0x1F     // value: 31,     raw: "0x1F"
 '\x41'   // value: "\x41", raw: "'\x41'"
readonly mixed $value
readonly string $raw

ScalarLiteralNode

abstract TypeLang\Type\Literal\ScalarLiteralNode extends Literal\LiteralNode

BoolLiteralNode

final TypeLang\Type\Literal\BoolLiteralNode extends Literal\ScalarLiteralNode

A true or a false, in any case they are written in.

 TruE  // value: true, raw: "TruE"

NullLiteralNode

final TypeLang\Type\Literal\NullLiteralNode extends Literal\LiteralNode

A null, in any case it is written in.

 NulL  // value: null, raw: "NulL"

IntLiteralNode

final TypeLang\Type\Literal\IntLiteralNode extends Literal\ScalarLiteralNode

A whole number, written in any of the four radixes.

 0xFE_DE  // value: 65246, raw: "0xFE_DE", decimal: "65246", kind: Hexadecimal
 042      // value: 34,    raw: "042",     decimal: "34",    kind: Octal
readonly string $decimal

The value written out in base 10.

readonly Literal\IntLiteralKind $kind

IntLiteralKind

enum TypeLang\Type\Literal\IntLiteralKind

case Binary
case Octal
case Decimal
case Hexadecimal

FloatLiteralNode

final TypeLang\Type\Literal\FloatLiteralNode extends Literal\ScalarLiteralNode

A floating point number.

The value is the nearest double, the mantissa and the exponent keep the exact number: mantissa * 10 ** exponent. A parser stores the nearest bound of the range (PHP_FLOAT_MAX) for a number out of it, never an infinity.

 -1_5.5e+3  // value: -15500.0, mantissa: "-15.5", exponent: "3"
 .42        // value: 0.42,     mantissa: "0.42",  exponent: "0"
 - 1.5      // value: -1.5,     mantissa: "-1.5",  exponent: "0"

 // raw: the text as written, "-1_5.5e+3", ".42", "- 1.5"

A node made by hand has no text to read the exact number from, so the mantissa and the exponent are the ones of the value itself.

readonly string $mantissa

The number before the exponent, without separators and leading zeros. The integer part is always there, the point is there only with a fraction: 0.5, 1, -0.10.

readonly string $exponent

The power of ten, 0 if there is no exponent.

StringLiteralNode

final TypeLang\Type\Literal\StringLiteralNode extends Literal\ScalarLiteralNode

A string, kept both decoded and as it is written.

 "\x41\x42"  // value: "AB", raw: "\"\x41\x42\""
readonly Literal\StringLiteralKind $kind

StringLiteralKind

enum TypeLang\Type\Literal\StringLiteralKind

case SingleQuoted
case DoubleQuoted

ConstTypeNode

final TypeLang\Type\Constant\ConstTypeNode extends TypeNode

A single constant, referenced by its whole name.

 Some\Any::CONST_NAME
 ^^^^^^^^             the class the constant belongs to
           ^^^^^^^^^^ the name of the constant

A name written in part stands for a set of constants, see the ConstMaskTypeNode.

Name|NamespaceName $owner

The class or the namespace the constant belongs to.

A constant of a namespace written by its whole name (Some\CONST_NAME) is a name of a type in the source, so the parser builds it as a NamedTypeNode.

Identifier $constant

ConstMaskTypeNode

final TypeLang\Type\Constant\ConstMaskTypeNode extends TypeNode

A set of constants, referenced by a name written in part.

 Some\Any::SOME_*
 ^^^^^^^^         the class the constants belong to
           ^^^^^^ the mask their names are written as

 Some\Any\SOME_*
 ^^^^^^^^        the namespace the constants belong to

 *_SOME
 ^^^^^^ a mask with no class and no namespace at all

 \SOME_*
 ^       a mask of the root namespace

A name written whole stands for a single constant, see the ConstTypeNode.

Name|NamespaceName|null $owner

The class or the namespace the constants belong to, or null in case of the mask is written with neither.

 Some\Any::SOME_*  // the class Some\Any
 Some\Any\SOME_*   // the namespace Some\Any
 \SOME_*           // the root namespace
 SOME_*            // null
Constant\MaskNode $mask

The name of the constants, written in part.

MaskNode

final TypeLang\Type\Constant\MaskNode extends NodesListNode

The name of a constant written in part.

The segments the name is made of are kept in the order they are written in, with a WildcardMaskNode standing wherever the name is left unsaid.

A mask is never empty.

 Some\Any::BAR*BAZ*SOME
 //           ^   ^      // wildcards
 //        ^^^ ^^^ ^^^^  // segments
 //        the segments and the wildcards between them

 Some\Any::*
 //        ^ a single wildcard

WildcardMaskNode

final TypeLang\Type\Constant\MaskNode\WildcardMaskNode extends Node

An asterisk standing in the place of any run of characters of a constant name.

 Some\Any::CONST_*
 //              ^ the part of the name that is left unsaid

FieldListNode

final TypeLang\Type\Shape\FieldListNode extends NodesListNode

The fields of a shape, in the order they are written in.

An empty list is a shape written with no fields at all, which is a thing of its own.

An array carries no list, while an array{} carries an empty one. See the NamedTypeNode::$fields.

bool $isSealed

Whether the shape is written with the fields it lists and no other. An unsealed one ends in a ..., which says that whatever else it carries was left unsaid.

 array{a: int}       // sealed
 array{a: int, ...}  // unsealed

FieldNode

abstract TypeLang\Type\Shape\FieldNode extends Node

A single field of a shape.

A field is written either with a key or with none, and a shape may mix the two. The keyless ones are numbered from zero in the order they are written in.

 array{name: string, id: int}  // fields written with a key
 array{string, int}            // fields written with none
 array{string, id: int}        // both in one shape
TypeNode $type

ExplicitFieldNode

abstract TypeLang\Type\Shape\ExplicitFieldNode extends Shape\FieldNode

A field of a shape written with a key of its own.

What the key may be is what tells the children of this class apart. A NamedFieldNode carries a bare word, a ScalarFieldNode a scalar value and a ComplexFieldNode a reference that has to be read.

Identifier|TypeNode $key

The key a field is written with.

bool $isOptional

Whether a field may be absent, written as a ? in front of the colon. Only a field with a key can be marked so.

 array{name: string}   // false
 array{name?: string}  // true

NamedFieldNode

final TypeLang\Type\Shape\NamedFieldNode extends Shape\ExplicitFieldNode

A field of a shape keyed by a bare word.

 array{name: string}
 //    ^^^^ the key

A true, a false and a null are bare words as well. In the place of a key they name nothing but themselves.

ScalarFieldNode

final TypeLang\Type\Shape\ScalarFieldNode extends Shape\ExplicitFieldNode

A field of a shape keyed by a number or by a string.

 array{0: string, 1: int}
 //    ^          ^ the keys

 array{"some key": string}
 //    ^^^^^^^^^^ the key

A key is a number or a string and nothing else, the way a key of an array is.

A true and a null are keys of a NamedFieldNode instead. In the place of a key they are read as the words they are written with, not as the values they name elsewhere.

ComplexFieldNode

final TypeLang\Type\Shape\ComplexFieldNode extends Shape\ExplicitFieldNode

A field of a shape keyed by something that has to be read to be understood: A reference to a constant, the mask of a family of them, or any other type.

 array{Some\Any::CONST_NAME: string}
 //    ^^^^^^^^^^^^^^^^^^^^          a class constant

 array{Some\Any::CONST_*: string}
 //    ^^^^^^^^^^^^^^^^^          the mask of a class constant

 array{JSON_*: string}
 //    ^^^^^^          the mask of a global constant

 WeakMap{User<Some>: T}
 //      ^^^^^^^^^^ a type

ImplicitFieldNode

final TypeLang\Type\Shape\ImplicitFieldNode extends Shape\FieldNode

A field of a shape written with no key at all, the way an element of a plain list is.

 array{int, string}
 //    ^^^  ^^^^^^ two implicit fields

TemplateListNode

final TypeLang\Type\Template\TemplateListNode extends NodesListNode

Template arguments a type is referenced with, in the order they are written in. A slot of the list may also declare a parameter in place of passing an argument.

The list is never empty.

 Some\Any<int, string>
 //       ^^^  ^^^^^^ two arguments

TemplateNode

abstract TypeLang\Type\Template\TemplateNode extends Node

Whatever stands in a slot of the <...> list of a type: an argument that is passed or a parameter that is declared right there.

 Some\Any<int, *>
 //       ^^^  ^ two arguments

 callable<T of Some>(T): T
 //       ^^^^^^^^^ a parameter

TemplateArgumentNode

abstract TypeLang\Type\Template\TemplateArgumentNode extends Template\TemplateNode

A value passed to a template parameter, as opposed to a parameter declared by a type.

 Some\Any<int, covariant string, *>
 //       ^^^  ^^^^^^^^^^^^^^^^  ^ three arguments

TypedTemplateArgumentNode

final TypeLang\Type\Template\TypedTemplateArgumentNode extends Template\TemplateArgumentNode

A template argument that is a type, along with the call-site variance it may carry.

 Some\Any<int, covariant string>
 //       ^^^                    an invariant argument
 //            ^^^^^^^^^^^^^^^^  a covariant argument
TypeNode $value
?Template\VarianceNode $variance

Variance standing in front of the argument, or null in case of it carries none, which makes the argument invariant.

 Some\Any<covariant string>
 //       ^^^^^^^^^ the variance

WildcardTemplateArgumentNode

final TypeLang\Type\Template\WildcardTemplateArgumentNode extends Template\TemplateArgumentNode

A template argument that is left unsaid, written as an asterisk.

 Some\Any<*>
 //       ^ an unspecified argument

The node names no type and carries no variance.

VarianceNode

final TypeLang\Type\Template\VarianceNode extends Node

A variance of a template argument or of a template parameter, the word that stands in front of it.

 Some\Any<covariant string>
 //       ^^^^^^^^^ the variance

 callable<contravariant T>(T): void
 //       ^^^^^^^^^^^^^ the variance
readonly Template\VarianceNode\VarianceKind $kind

The kind of the variance.

VarianceKind

enum TypeLang\Type\Template\VarianceNode\VarianceKind

The kind of a variance, it is the word the variance is written with.

case Covariant

A subtype may stand in the place of the type.

 Some\Any<covariant string>
case Contravariant

A supertype may stand in the place of the type.

 Some\Any<contravariant string>
case Invariant

Only the type itself may stand in its place.

 Some\Any<invariant string>

TemplateParameterListNode

final TypeLang\Type\Template\TemplateParameterListNode extends NodesListNode

Template parameters a type declares, in the order they are written in.

The list is never empty: a type that declares no parameters carries no list at all.

 callable<T, U of Some>(T): U
 //       ^  ^^^^^^^^^
 //       two parameters

TemplateParameterNode

final TypeLang\Type\Template\TemplateParameterNode extends Template\TemplateNode

A template parameter declared by a type.

A parameter is a name the type introduces, along with the limits put on it. Each limit is written at most once and any of them may be left out.

 callable<T, U of Some super Any = int>(T): U
 //       ^                              a name and nothing else
 //          ^^^^^^^^^                   the upper bound
 //                    ^^^^^^^^^         the lower bound
 //                              ^^^^^   the default
Identifier $name
?Template\TemplateBoundNode $upper

The end the parameter is bounded at from above, written with an of or an as.

The argument is to be a subtype of it.

?Template\TemplateBoundNode $lower

The end the parameter is bounded at from below, written with a super.

The argument is to be a supertype of it.

?TypeNode $default

The type the parameter takes when no argument is passed, written with an =.

It bounds nothing. A bound says what an argument may be, while a default says what it becomes when left unsaid.

?Template\VarianceNode $variance

Declaration-site variance of the parameter, or null in case of it carries none, which makes the parameter invariant.

TemplateBoundNode

final TypeLang\Type\Template\TemplateBoundNode extends Node

One end a template parameter is bounded at, written as the word it is bounded with and the type the bound is expressed by.

 callable<T of Some super Any>(T): T
 //         ^^^^^^^                  the upper bound
 //                 ^^^^^^^^^        the lower bound
TypeNode $type
Identifier $operator

The word the bound is written with: of and as bound from above, super from below.

CallableTypeNode

final TypeLang\Type\Callable\CallableTypeNode extends TypeNode

Something callable, written as a name with a parameter list behind it.

 Closure<T of Some>(T, string ...$rest): T
 ^^^^^^^                                    the name
        ^^^^^^^^^^^                         the template parameters
                   ^^^^^^^^^^^^^^^^^^^^     the parameters
                                         ^  the return type
Name $name
Callable\CallableParameterListNode $parameters

Parameters a callable accepts. The list is never null, an empty list stands for empty parentheses.

 callable()      // an empty list
 callable(int)   // a list of 1 parameter
?TypeNode $type

A return type of callable, or null in case of it is left unsaid.

 callable()       // null
 callable(): int  // a type
?Template\TemplateParameterListNode $templates

Template parameters a callable declares, or null in case of it declares none.

The list is never empty.

 callable(T): T     // null
 callable<T>(T): T  // a list of 1 parameter

CallableParameterListNode

final TypeLang\Type\Callable\CallableParameterListNode extends NodesListNode

Parameters of a callable, in the order they are written in.

 callable(int, string ...$rest)
 //       ^^^  ^^^^^^^^^^^^^^^
 //       two parameters

CallableParameterNode

final TypeLang\Type\Callable\CallableParameterNode extends Node

A single parameter of a callable.

 callable(int &$byRef, string ...$rest, bool $flag = true)
 //       ^^^^^^^^^^^  ^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^
 //       by reference  variadic         optional, with a default

A parameter is optional when it has a DefaultValueNode, with a value or without one.

The constructor checks the parameter on creation only. The properties are public and writable, so a later change is not checked. Since PHP 8.4, property hooks make it possible to keep the checks permanent.

?TypeNode $type

Type of parameter, or null in case of a parameter that is built by hand and carries a name alone.

?VariableNode $name

Name of a parameter, or null in case of it is written without one.

 callable(int)          // null
 callable(int $value)   // a name
bool $isByReference

Whether a parameter is taken by reference.

It is written as an & behind the type, like the one of a callable(int &$byRef).

bool $isVariadic

Whether a parameter takes every argument left, written as a ...: A callable(string ...$rest).

?Callable\DefaultValueNode $default

Default of a parameter, or null in case of a required one. A variadic parameter is optional itself, so it has no default.

 callable(int $a)            // null
 callable(int $a =)          // a default without a value
 callable(int $a = 42)       // a default with a value

DefaultValueNode

final TypeLang\Type\Callable\DefaultValueNode extends Node

The default of a callable parameter, written as an = and the value it stands for.

The node itself tells that the parameter may be left out, so a parameter with it is optional, and one without it is required.

 callable(int $a =, string $b = 'x')
 //             ^                      no value, the parameter is optional
 //                            ^^^^^^^ the value
?TypeNode $value

The value of a default, or null in case of the parameter is only marked as optional.

The value is a literal or a constant, so it is a type node of the same kind as in any other position.

ConditionalTypeNode

final TypeLang\Type\Condition\ConditionalTypeNode extends TypeNode

A type chosen by a condition.

 ($value is int ? string : bool)
  ^^^^^^^^^^^^^                  the condition
                  ^^^^^^         the type it holds for
                           ^^^^  the type it does not
Condition\ConditionNode $condition
TypeNode $then
TypeNode $else

ConditionNode

final TypeLang\Type\Condition\ConditionNode extends Node

The question a ternary type asks: the two sides of it and the operator between them.

 ($value is int ? string : bool)
 //^^^^^ ^^ ^^^
 //subject  target
 //      the operator
TypeNode|VariableNode $subject
TypeNode|VariableNode $target
Condition\ConditionNode\ConditionKind $kind

The kind of the operator between the sides.

ConditionKind

enum TypeLang\Type\Condition\ConditionNode\ConditionKind

The kind of a condition, it is the operator the condition is written with.

case Equal

Whether the subject is the target.

 ($value is int ? string : bool)
case NotEqual

Whether the subject is anything but the target.

 ($value is not int ? string : bool)