Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created October 18, 2016 10:12
Show Gist options
  • Save DmitrySoshnikov/7f0bd98ff12e2d2a52926898b8ded926 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/7f0bd98ff12e2d2a52926898b8ded926 to your computer and use it in GitHub Desktop.
calculator.ast.php.js
/**
* Calculator grammar for a parser in Python.
*
* syntax-cli -g calculator.ast.php.js -m LALR1 -o CalcParser.php
*
* <?php
*
* require('CalcParser.php');
* var_dump(CalcParser::parse('2 + 2 * 2'));
*/
{
"lex": {
"rules": [
["\\s+", "/* skip whitespace */"],
["\\d+", "return 'NUMBER'"],
["\\*", "return '*'"],
["\\+", "return '+'"],
["\\(", "return '('"],
["\\)", "return ')'"],
]
},
"moduleInclude": `
// Can be "require" statments, or direct declarations.
class Node {
public function __construct($type) {
$this->type = $type;
}
}
class BinaryExpression extends Node {
public function __construct($left, $right, $op) {
parent::__construct('Binary');
$this->left = $left;
$this->right = $right;
$this->op = $op;
}
}
class PrimaryExpression extends Node {
public function __construct($value) {
parent::__construct('Primary');
$this->value = intval($value);
}
}
// Standard hook on parse beging, and end:
yyparse::setOnParseBegin(function($string) {
var_dump('Custom hook on parse begin. Parsing:', $string);
});
yyparse::setOnParseEnd(function($value) {
var_dump('Custom hook on parse end. Parsed:', $value);
});
`,
"operators": [
["left", "+"],
["left", "*"],
],
"bnf": {
"E": [
["E + E", "$$ = new BinaryExpression($1, $3, $2)"],
["E * E", "$$ = new BinaryExpression($1, $3, $2)"],
["NUMBER", "$$ = new PrimaryExpression($1)"],
["( E )", "$$ = $1"],
],
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment