Skip to content

Extending

Combinators

A combinator reads one piece of a tag line: a type, a variable, a URI. A grammar refers to it by name: Spec::rule(TypeCombinator::NAME, 'type').

interface CombinatorInterface
{
public function __invoke(Cursor $cursor): mixed;
}

A combinator reads its part from the Cursor and returns the value, or throws a NoMatchException: the grammar then rolls the cursor back and tries the next alternative.

Cursor method Reads
peek($length), read($length) a number of bytes, without or with moving
readWhile($chars), readUntil($chars) a run of, or up to, the characters
readWord() up to the next whitespace
readPhpIdentifier(), readPhpQualifiedName() a name, without or with \
readLiteral($text) the exact text, false when it is not next
readRemainder() everything left
skipWhitespace(), isEof()
Name Returns Reads
Type TypeReference a TypeLang type
CallableType TypeReference a callable type
Variable string a $name, without the $
Name string an identifier
Integer int a non-negative integer
Reference CodeReference a class, function, method, constant, property or variable
AssertSubject CodeReference $value, $this->items, $this->getItems(), self::$instances
URI UriReference a word of RFC 3986
URL UrlReference a URI with a scheme
Version string a word beginning with a digit
IssueName string letters, digits, _, - and .
Description DescriptionInterface everything left, with its inline tags
Visibility Visibility public, protected or private
AuthorName string everything up to an optional <
Email string an address, up to its closing >
FlowType FlowType a taint flow kind of Psalm

A combinator reading a low or high priority:

enum Priority: string
{
case Low = 'low';
case High = 'high';
}
final class PriorityCombinator implements CombinatorInterface
{
public const string NAME = 'Priority';
public function __invoke(Cursor $cursor): Priority
{
return Priority::tryFrom($cursor->readWord())
?? throw new NoMatchException('Expected a priority level');
}
}

It is registered by a platform and used as a built-in one:

final class PriorityPlatform extends Platform
{
public function getCombinators(): iterable
{
return [PriorityCombinator::NAME => new PriorityCombinator()];
}
// ...
}
// "@priority" <Priority>
Spec::rule(PriorityCombinator::NAME, 'priority');
$parser->parse('/** @priority high */')[0];
// PriorityTag { priority: Priority::High }
$parser->parse('/** @priority urgent */')[0];
// InvalidTag: Malformed "@priority" tag, expected: <Priority>