Skip to content

Parser

Type parser

The parser component analyzes a TypeLang type declaration string and builds an AST (Abstract Syntax Tree) out of it, checking the grammar along the way.

composer require type-lang/parser

Requires PHP 8.1 or later.

The TypeLang\Parser\TypeParser class is the entry point of the component. Its parse() method turns a type declaration string into a TypeLang\Type\TypeNode instance (a NamedTypeNode, UnionTypeNode, etc., depending on the source).

$parser = new TypeLang\Parser\TypeParser();
$type = $parser->parse('array{key: int}'); // NamedTypeNode
$type->name->toString(); // 'array'
count($type->fields); // 1
$type->fields->isSealed; // true

Every node exposes an $offset (byte offset in the source where the node starts) and, depending on its kind, a handful of other public properties. The node classes themselves (TypeLang\Type\*) belong to the separate type-lang/types package.

TypeParser asks the grammar three different questions, all three declared on TypeParserInterface:

  • parse(): TypeNode is the strict mode. Requires the whole input to be a syntactically valid type statement, throws a ParserExceptionInterface on the first error.
  • partial(): ParsedResult reads as much of the input as the grammar describes and returns a TypeLang\Parser\Partial\ParsedResult carrying the type built out of the read part and the offset the reading stopped at. Useful for docblock parsing, where a type declaration is followed by a free-text description. See tolerant mode.
  • validate(): CheckResult tells whether the source is a type, building nothing of it. This is the cheapest of the three whenever the type itself is of no use. See validation.

All three methods accept a string, a resource, an SplFileInfo or a phplrt ReadableInterface:

$parser->parse('object{key?: int<0, max>}');
$parser->parse(fopen(__DIR__ . '/source.txt', 'rb'));
$parser->parse(new SplFileInfo(__DIR__ . '/source.txt'));
$parser->parse(Phplrt\Source\FileSource::createFromPathname($pathname));

By default the parser reads a whole type. Two context methods return a new parser that starts from another grammar rule:

use TypeLang\Parser\TypeParser;
$parser = new TypeParser();
// TypeLang\Type\TypeNode
$type = $parser->forType()->parse('Type<U, V>');
// TypeLang\Type\Template\TemplateParameterNode
$template = $parser->forTemplateParameter()->parse('T of U<V> = Default<Z>');

Every exception thrown by the parser implements TypeLang\Parser\Exception\ParserExceptionInterface and carries the $source and the $range (ParsingErrorRange with $offset and $length) of the problematic fragment.

Exception Thrown when
UnexpectedTokenException a token stands where another one is expected: Unexpected "and"
MalformedSyntaxException a construct is broken: The group is not closed properly, ")" expected
UnrecognizedSyntaxException a fragment is not a part of the syntax at all: Unrecognized syntax "~"
FeatureNotEnabledException the syntax is disabled: Unions feature is not allowed

The first three extend SyntaxErrorException, and all of them extend ParsingException. MalformedSyntaxException extends UnexpectedTokenException.

  • Feature toggling: enable or disable individual language constructs (generics, shapes, unions, …).
  • Partial parsing and validation: read a type declaration embedded in free-form text, such as a phpdoc annotation, or ask whether a source is a type at all.
  • Visitors: traverse, search and rewrite a parsed AST.
  • Name resolution: resolve short and relative names in an AST against use statements or any other custom rule.