Skip to content

php-type-language/parser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

285 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP 8.4+ Latest Stable Version Latest Unstable Version License MIT


The reference parser for TypeLang — a declarative type language inspired by static analyzers like PHPStan and Psalm.

It reads a type declaration string and builds an AST of TypeLang\Type\* nodes, checking the grammar along the way. The node classes themselves live in the separate type-lang/types package.

Installation

Install the package via Composer:

composer require type-lang/parser

Requirements:

  • PHP 8.4+

Usage

TypeLang\Parser\TypeParser is the entry point. Its parse() method turns a type declaration into a TypeLang\Type\TypeNode:

$parser = new TypeLang\Parser\TypeParser();

$type = $parser->parse('array{ key: int }');

var_dump($type);
// object(TypeLang\Type\NamedTypeNode) {
//   ["name"]   => "array"
//   ["fields"] => object(TypeLang\Type\Shape\FieldsListNode) { ... }
//   ...
// }

Every node exposes an $offset (byte offset in the source) plus a handful of properties describing its kind.

Strict vs. Tolerant Parsing

  • parse(): TypeNode — strict mode; requires the whole input to be a valid type and throws a ParserExceptionInterface on the first error.
  • parseTolerant(): ParsedResult — parses as much as it can and reports how far it consumed the source. Useful for phpdoc, where a type is followed by a free-text description.
$result = $parser->parseTolerant('int and some trailing description');

$result->type;   // TypeLang\Type\NamedTypeNode ("int")
$result->offset; // offset where parsing stopped

See the documentation for feature toggling, visitors and name resolution.

About

[READ ONLY] 🧱 Library for parsing and validating TypeLang syntax and converting it into AST nodes

Topics

Resources

License

Code of conduct

Stars

51 stars

Watchers

2 watching

Forks

Contributors

Languages