Type Parser Component
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.
Installation
Requirements:
PHP >= 8.1
Quick Start
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.
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 — plain AST Nodes.
Three Ways of Reading a Source
TypeParser asks the grammar three different questions, all three declared on TypeParserInterface:
parse(): TypeNode— strict mode. Requires the whole input to be a syntactically valid type statement; throws aParserExceptionInterfaceon the first error.partial(): ParsedResult— reads as much of the input as the grammar describes and returns aTypeLang\Parser\Partial\ParsedResultcarrying the type built out of the read part and the offset the reading stopped at, whatever follows it. Useful for phpdoc/docblock parsing, where a type declaration is followed by a free-text description. See Partial Parsing.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.
Parser Arguments
All three methods accept the source code in any of the following forms:
What's Next
- Feature toggling
Enable or disable individual language constructs (generics, shapes, unions, ...) — see Feature Toggling.
- 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 — see Partial Parsing.
- Visitors
Traverse, search, and rewrite a parsed AST — see Visitors.
- Name resolution
Resolve short/relative names in an AST against
usestatements or any other custom rule — see Name Resolution.