mrsuh/php-bison-skeleton
Bison 的 PHP 骨架
1.2.0
2023-05-07 15:22 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^9.6
- symfony/process: ^5.4
This package is auto-updated.
Last update: 2024-08-31 00:26:03 UTC
README
一套可以用于生成 PHP 编写的 Bison 解析器的骨架文件。
要求
- PHP >= 7.4
- Bison >= 3.8
安装
composer require --dev mrsuh/php-bison-skeleton
使用方法
bison -S vendor/mrsuh/php-bison-skeleton/src/php-skel.m4 -o parser.php grammar.y
帖子
Docker
示例
grammar.y
%define api.parser.class {Parser} %token T_NUMBER %left '-' '+' %% start: expression { printf("%d\n", $1); } ; expression: T_NUMBER { $$ = $1; } | expression '+' expression { $$ = $1 + $3; } | expression '-' expression { $$ = $1 - $3; } ; %% class Lexer implements LexerInterface { private array $words; private int $index = 0; private int $value = 0; public function __construct($resource) { $this->words = explode(' ', trim(fgets($resource))); } public function yyerror(string $message): void { printf("%s\n", $message); } public function getLVal() { return $this->value; } public function yylex(): int { if ($this->index >= count($this->words)) { return LexerInterface::YYEOF; } $word = $this->words[$this->index++]; if (is_numeric($word)) { $this->value = (int)$word; return LexerInterface::T_NUMBER; } return ord($word); } } $lexer = new Lexer(STDIN); $parser = new Parser($lexer); if (!$parser->parse()) { exit(1); }
bison -S vendor/mrsuh/php-bison-skeleton/src/php-skel.m4 -o parser.php grammar.y
php parser.php <<< "1 + 2" 3
更多示例请参阅 文件夹
测试
composer test