Skip to content

Parser

Partial parsing

partial() reads a type followed by any other text, such as the type of a @return tag followed by its description. It never throws on a syntax error and returns a TypeLang\Parser\Partial\ParsedResult:

Result The source Holds
SuccessfulParsedResult is a type as a whole $type, $offset
PartialParsedResult begins with a type $type, $offset
FailureParsedResult does not begin with a type $message, $position, $offset
$source = 'int and more text';
$result = $parser->partial($source);
// PartialParsedResult
$result->type; // NamedTypeNode of `int`
$result->offset; // 4
substr($source, $result->offset); // 'and more text'

The offset is the byte after the type and the whitespace following it.

// @return Example<T> Returns something
$body = 'Example<T> Returns something';
$result = $parser->partial($body);
$result->type; // Example<T>
substr($body, $result->offset); // 'Returns something'

Broken syntax is not repaired: the reading stops after the last complete type, the rest is trailing text.

$result = $parser->partial('array{');
$result->type; // array
$result->offset; // 5, the "{"

validate() tells whether the source is a type and builds nothing. It returns a TypeLang\Parser\Validation\CheckResult:

$parser->validate('array{id: int}'); // SuccessfulCheckResult
$parser->validate('array{id: int} and more'); // PartialCheckResult
$parser->validate('array{'); // PartialCheckResult
$parser->validate(')'); // FailureCheckResult
$isType = $parser->validate($source) instanceof SuccessfulCheckResult;

A failure holds the message and the place, the line and the column are 1-based:

$result = $parser->validate('int string');
$result->message; // 'Unexpected "string"'
$result->offset; // 4
$result->position->line; // 1
$result->position->column; // 5