Skip to content

Parser

Visitors

TypeLang\Parser\Traverser walks a parsed type and calls its visitors for every node. A visitor extends Traverser\Visitor and overrides only the methods it needs:

use TypeLang\Parser\Traverser;
use TypeLang\Parser\Traverser\Command;
use TypeLang\Parser\Traverser\Visitor;
use TypeLang\Type\Node;
$type = new TypeLang\Parser\TypeParser()->parse('list<int>|null');
$visitor = new class extends Visitor {
public function enter(Node $node): ?Command
{
echo $node::class . "\n";
return null;
}
};
Traverser::new([$visitor])->traverse([$type]);
// TypeLang\Type\LogicalTypeNode\UnionTypeNode
// TypeLang\Type\NamedTypeNode
// TypeLang\Type\Name
// TypeLang\Type\Template\TemplateListNode
// TypeLang\Type\Template\TypedTemplateArgumentNode
// TypeLang\Type\NamedTypeNode
// TypeLang\Type\Name
// TypeLang\Type\Literal\NullLiteralNode
Method Called
before(): void once, before the first node
enter(Node $node): ?Command on the way down, before the children
leave(Node $node): void on the way back up, after the children
after(): void once, after the last node
int|string
before
enter UnionTypeNode
enter NamedTypeNode
enter Name int
leave Name
leave NamedTypeNode
enter NamedTypeNode
enter Name string
leave Name
leave NamedTypeNode
leave UnionTypeNode
after

enter() may return Command::SkipChildren: the children of the node are not visited, leave() of the node itself is still called.

public function enter(Node $node): ?Command
{
echo $node::class . "\n";
if ($node instanceof NamedTypeNode) {
return Command::SkipChildren;
}
return null;
}
// list<int>|null
//
// TypeLang\Type\LogicalTypeNode\UnionTypeNode
// TypeLang\Type\NamedTypeNode
// TypeLang\Type\Literal\NullLiteralNode
// several visitors, each is called for every node
Traverser::new([$first, $second])->traverse([$type]);
// one visitor, returned back to read its state
$visitor = Traverser::through($visitor, [$type]);
// a new traverser with one more visitor
$traverser = $traverser->with($visitor);
$traverser = $traverser->with($visitor, prepend: true);

The children of a node are found by SimplePropertyAccessor: every non-readonly property holding a node or a list of nodes. Readonly values, such as the parts of a Name, are not visited. Another PropertyAccessorInterface is set by withPropertyAccessor().

Visitor Purpose
MatcherVisitor finds the first node by a predicate
ClassNameMatcherVisitor finds the first node of a class
TypeMapVisitor rewrites the names
StringDumperVisitor dumps the tree into a string
StreamDumperVisitor dumps the tree into a stream
DumperVisitor the base of a dumper of your own

Finds the first node the matcher returns true for. After the traversal $finder->node is the node or null, $finder->hasMatches() tells whether it is found.

use TypeLang\Parser\Traverser\MatcherVisitor;
$type = $parser->parse('int|non-empty-string|bool');
$finder = Traverser::through(new MatcherVisitor(
static fn(Node $node): bool => $node instanceof NamedTypeNode
&& \strlen($node->name->toString()) > 5,
), [$type]);
$finder->node->name->toString(); // 'non-empty-string'

The optional break stops the search at a node the matcher did not take:

$type = $parser->parse('array{a: true}|false');
$finder = Traverser::through(new MatcherVisitor(
matcher: static fn(Node $node): bool => $node instanceof BoolLiteralNode,
break: static fn(Node $node): bool => $node instanceof FieldListNode,
), [$type]);
$finder->hasMatches(); // false: stopped at the fields of the shape

A MatcherVisitor that matches by instanceof.

use TypeLang\Parser\Traverser\ClassNameMatcherVisitor;
$type = $parser->parse('int|string');
$finder = Traverser::through(
new ClassNameMatcherVisitor(NamedTypeNode::class),
[$type],
);
$finder->node->name->toString(); // 'int', the first one
$finder = Traverser::through(
new ClassNameMatcherVisitor(BoolLiteralNode::class),
[$type],
);
$finder->hasMatches(); // false
$finder->node; // null

Calls a callback for every Name of a type: the name of a named or a callable type, the owner of a class constant. A returned Name replaces the original one in place, null keeps it.

use TypeLang\Parser\Traverser\TypeMapVisitor;
use TypeLang\Type\Name;
use TypeLang\Type\NamespaceName;
$visitor = new TypeMapVisitor(static function (Name $name): ?Name {
if ($name->toLowerString() === 'user') {
return new Name('User', new NamespaceName('App'));
}
return null;
});
$type = $parser->parse('User|Admin');
Traverser::new([$visitor])->traverse([$type]);
// App\User|Admin
$type = $parser->parse('User::STATUS_ACTIVE');
Traverser::new([$visitor])->traverse([$type]);
// App\User::STATUS_ACTIVE

Dumps the tree into $visitor->output, one node per line. Useful in tests: assert on the string instead of comparing object graphs.

use TypeLang\Parser\Traverser\StringDumperVisitor;
$type = $parser->parse('list<int>|null');
$visitor = Traverser::through(new StringDumperVisitor(), [$type]);
echo $visitor->output;
LogicalTypeNode\UnionTypeNode
NamedTypeNode
Name(list)
Template\TemplateListNode
Template\TypedTemplateArgumentNode
NamedTypeNode
Name(int)
Literal\NullLiteralNode(null)

Every line ends with "\n". The output is cleared by the next traverse() call or by $visitor->reset().

The same dump written to a stream, php://stderr by default:

use TypeLang\Parser\Traverser\StreamDumperVisitor;
Traverser::new([new StreamDumperVisitor()])->traverse([$type]);
// any URI accepted by fopen()
new StreamDumperVisitor(stream: __DIR__ . '/types.log');

The abstract base of both dumpers. A line is the class of the node without the TypeLang\Type\ prefix and, in parentheses, the node as a string (Name(int)) or its scalar properties (Shape\FieldListNode(isSealed=true)).

A dumper of your own implements write():

use TypeLang\Parser\Traverser\DumperVisitor;
final class LinesDumperVisitor extends DumperVisitor
{
public array $lines = [];
protected function write(string $data): void
{
$this->lines[] = \rtrim($data, "\n");
}
}
$visitor = Traverser::through(
new LinesDumperVisitor(),
[$parser->parse('int|null')],
);
$visitor->lines;
// [
// 'LogicalTypeNode\UnionTypeNode',
// ' NamedTypeNode',
// ' Name(int)',
// ' Literal\NullLiteralNode(null)',
// ]

The prefix to strip is the first argument of a dumper, an empty string keeps the full class names:

new StringDumperVisitor(simplifyNodeNamespace: '');
// TypeLang\Type\LogicalTypeNode\UnionTypeNode
// TypeLang\Type\NamedTypeNode
// TypeLang\Type\Name(int)
// TypeLang\Type\Literal\NullLiteralNode(null)