我对使用php-peg的PHP中的my PEG grammar有一个问题(该项目有更新的fork,即发布给Packagist).我的项目是一个表达式解析器的分支,我想用一个更容易修改的生成的解析器来替换它.
到目前为止一切运行良好,但我有一个问题,添加隐式乘法,这是原始项目功能的一部分.
它看起来像这样:
8(5/2)
它应该隐式地用分数乘以8.
到目前为止,我的语法有很多功能,但我只想知道如何将隐式乘法添加到一个基本的计算器示例中,如下所示:
Number: /[0-9]+/
Value: Number > | '(' > Expr > ')' >
function Number( &$result, $sub ) {
$result['val'] = $sub['text'] ;
}
function Expr( &$result, $sub ) {
$result['val'] = $sub['val'] ;
}
Times: '*' > operand:Value >
Div: '/' > operand:Value >
Product: Value > ( Times | Div ) *
function Value( &$result, $sub ) {
$result['val'] = $sub['val'] ;
}
function Times( &$result, $sub ) {
$result['val'] *= $sub['operand']['val'] ;
}
function Div( &$result, $sub ) {
$result['val'] /= $sub['operand']['val'] ;
}
Plus: '+' > operand:Product >
Minus: '-' > operand:Product >
Sum: Product > ( Plus | Minus ) *
function Product( &$result, $sub ) {
$result['val'] = $sub['val'] ;
}
function Plus( &$result, $sub ) {
$result['val'] += $sub['operand']['val'] ;
}
function Minus( &$result, $sub ) {
$result['val'] -= $sub['operand']['val'] ;
}
Expr: Sum
function Sum( &$result, $sub ) {
$result['val'] = $sub['val'] ;
}
位于project examples directory号.
我已经在GitHub上创建了basic calculator example project个.