https://github.com/mrsuh/php-bison-skeleton
PHP skeleton for Bison
https://github.com/mrsuh/php-bison-skeleton
bison parser-generator php php-bison-skeleton skeleton
Last synced: 10 months ago
JSON representation
PHP skeleton for Bison
- Host: GitHub
- URL: https://github.com/mrsuh/php-bison-skeleton
- Owner: mrsuh
- License: gpl-3.0
- Created: 2023-03-08T11:47:36.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2024-11-23T09:34:59.000Z (about 1 year ago)
- Last Synced: 2025-03-31T11:04:09.435Z (11 months ago)
- Topics: bison, parser-generator, php, php-bison-skeleton, skeleton
- Language: M4
- Homepage: https://mrsuh.com/projects/php-bison-skeleton/
- Size: 166 KB
- Stars: 37
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# PHP skeleton for Bison



A set of Bison skeleton files that can be used to generate a Bison parser written in PHP.
## Requirements:
* PHP >= 7.4
* Bison >= 3.8
## Installation
```bash
composer require --dev mrsuh/php-bison-skeleton
```
## Usage
```bash
bison -S vendor/mrsuh/php-bison-skeleton/src/php-skel.m4 -o parser.php grammar.y
```
## Posts
* [PHP Skeleton for Bison](https://mrsuh.com/articles/2023/php-skeleton-for-bison/)
* [AST parser with PHP and Bison](https://mrsuh.com/articles/2023/ast-parser-with-php-and-bison/)
* [Nginx parser with PHP and Bison](https://mrsuh.com/articles/2023/nginx-parser-with-php-and-bison/)
* [JSON parser with PHP and Bison](https://mrsuh.com/articles/2023/json-parser-with-php-and-bison/)
## Docker
* [Bison docker image](https://github.com/mrsuh/docker-bison)
## Example
`grammar.y`
```php
%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);
}
```
```bash
bison -S vendor/mrsuh/php-bison-skeleton/src/php-skel.m4 -o parser.php grammar.y
```
```bash
php parser.php <<< "1 + 2"
3
```
See more examples in the [folder](./examples)
### Tests
```bash
composer test
```