The Parser Component
Edit pageLast modified: 10 October 2024A parser component is used to analyze and construct types AST with their information and grammar checking.
Installation
Via Composer: composer require type-lang/parser
Requirements:
PHP >= 8.1
ext-pcre
ext-mbstring
optional
Usage
To create a parser instance, the TypeLang\Parser\Parser
class is used. To run code analysis, you should use the parse()
method.
$parser = new TypeLang\Parser\Parser();
$result = $parser->parse('example');
Result
{...}
Feature Toggling
You can enable or disable a set of parser features if your task requires only partial support of the functionality. Such a feature allows you to conveniently implement more strict functionality.
$parser = new TypeLang\Parser\Parser(
literals: false,
);
$result = $parser->parse('42');
// Uncaught TypeLang\Parser\Exception\ParseException:
// Literal values not allowed in "42" at column 1
Parser Arguments
The first argument of the TypeLang\Parser\Parser::parse(<source>)
method corresponds to the source code data and can be of the following types:
- Method signature
- stringresource (stream)SplFileInfoReadableInterface
$result = $parser->parse(<<<'CODE' object{ key?: int<0, max> } CODE);
$result = $parser->parse( fopen(__DIR__ . '/source.txt', 'rb'), );
$result = $parser->parse( new SplFileInfo(__DIR__ . '/source.txt'), );
$result = $parser->parse( Phplrt\Source\File::fromPathname(__DIR__ . '/source.txt'), );