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/typesExample<string, int, *>|null
resultTypeLang\Type\LogicalTypeNode\UnionTypeNode
Building a tree
Section titled “Building a tree”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, *>|nullReading and changing
Section titled “Reading and changing”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); // 3The 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::$valueEvery 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.
Base classes
Section titled “Base classes”Node
-
readonly int $offset Token offset defined in the source code.
TypeNode
A node standing where a type is expected.
NodesListNode
An ordered list of nodes of one kind, like the arguments of a generic or the fields of a shape.
-
array $children
SymbolNode
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
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
nullin 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
nullin case of the name is followed by none. An empty list is not the same as anull: 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
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
nullin case of the name is written with none.
NamespaceName
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 oneThe 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
namespacekeyword and the leading separator are not the words.-
readonly NamespaceName\NamespaceKind $kind From where the namespace is read.
NamespaceKind
How the namespace of a name is written, that is, from where it is read.
case QualifiedA namespace written as it is.
Some\Any\Name ^^^^^^^^case FullyQualifiedA namespace that begins in a separator, it is read from the root.
\Some\Any\Name ^^^^^^^^^ \Name ^ the root namespace has no wordscase NamespaceRelativeA namespace that begins in the
namespacekeyword, 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
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
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
The type of the object a method is called on, written as a $this.
callable(): $thisIt is written the way a variable is, but it is a type. Any other variable is a VariableNode and no type at all.
Logical types
Section titled “Logical types”LogicalTypeNode
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
Any one of several types.
int|string|nullIntersectionTypeNode
All of several types at once.
Some\Any & StringableWrappingTypeNode
A type built around another one.
?Some\Any
^ the wrapping type
^^^^^^^^ the type it wraps-
TypeNode $type
NullableTypeNode
A type a null is allowed besides, written with a leading ?.
?Some\AnyTypesListTypeNode
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 ofTypeOffsetAccessTypeNode
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.
Literals
Section titled “Literals”LiteralNode
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
BoolLiteralNode
A true or a false, in any case they are written in.
TruE // value: true, raw: "TruE"NullLiteralNode
A null, in any case it is written in.
NulL // value: null, raw: "NulL"IntLiteralNode
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
case Binarycase Octalcase Decimalcase Hexadecimal
FloatLiteralNode
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,
0if there is no exponent.
StringLiteralNode
A string, kept both decoded and as it is written.
"\x41\x42" // value: "AB", raw: "\"\x41\x42\""-
readonly Literal\StringLiteralKind $kind
StringLiteralKind
case SingleQuotedcase DoubleQuoted
Constants
Section titled “Constants”ConstTypeNode
A single constant, referenced by its whole name.
Some\Any::CONST_NAME
^^^^^^^^ the class the constant belongs to
^^^^^^^^^^ the name of the constantA 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 aNamedTypeNode.-
Identifier $constant
ConstMaskTypeNode
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 namespaceA 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
nullin 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
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 wildcardWildcardMaskNode
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 unsaidShapes
Section titled “Shapes”FieldListNode
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
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
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
A field of a shape keyed by a bare word.
array{name: string}
// ^^^^ the keyA true, a false and a null are bare words as well. In the place of a key they name nothing but themselves.
ScalarFieldNode
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 keyA 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
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 typeImplicitFieldNode
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 fieldsTemplates
Section titled “Templates”TemplateListNode
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 argumentsTemplateNode
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 parameterTemplateArgumentNode
A value passed to a template parameter, as opposed to a parameter declared by a type.
Some\Any<int, covariant string, *>
// ^^^ ^^^^^^^^^^^^^^^^ ^ three argumentsTypedTemplateArgumentNode
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
nullin case of it carries none, which makes the argument invariant.Some\Any<covariant string> // ^^^^^^^^^ the variance
WildcardTemplateArgumentNode
A template argument that is left unsaid, written as an asterisk.
Some\Any<*>
// ^ an unspecified argumentThe node names no type and carries no variance.
VarianceNode
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
The kind of a variance, it is the word the variance is written with.
case CovariantA subtype may stand in the place of the type.
Some\Any<covariant string>case ContravariantA supertype may stand in the place of the type.
Some\Any<contravariant string>case InvariantOnly the type itself may stand in its place.
Some\Any<invariant string>
TemplateParameterListNode
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 parametersTemplateParameterNode
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
ofor anas.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
nullin case of it carries none, which makes the parameter invariant.
TemplateBoundNode
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:
ofandasbound from above,superfrom below.
Callables
Section titled “Callables”CallableTypeNode
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
nullin case of it is left unsaid.callable() // null callable(): int // a type-
?Template\TemplateParameterListNode $templates Template parameters a callable declares, or
nullin case of it declares none.The list is never empty.
callable(T): T // null callable<T>(T): T // a list of 1 parameter
CallableParameterListNode
Parameters of a callable, in the order they are written in.
callable(int, string ...$rest)
// ^^^ ^^^^^^^^^^^^^^^
// two parametersCallableParameterNode
A single parameter of a callable.
callable(int &$byRef, string ...$rest, bool $flag = true)
// ^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
// by reference variadic optional, with a defaultA 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
nullin case of a parameter that is built by hand and carries a name alone.-
?VariableNode $name Name of a parameter, or
nullin 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 acallable(int &$byRef).-
bool $isVariadic Whether a parameter takes every argument left, written as a
...: Acallable(string ...$rest).-
?Callable\DefaultValueNode $default Default of a parameter, or
nullin 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
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
nullin 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.
Conditional types
Section titled “Conditional types”ConditionalTypeNode
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
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
The kind of a condition, it is the operator the condition is written with.
case EqualWhether the subject is the target.
($value is int ? string : bool)case NotEqualWhether the subject is anything but the target.
($value is not int ? string : bool)