如何在 PHP PEG 基本计算器语法中添加隐式乘法?

问题描述 投票:0回答:1

我在 PHP 中使用 php-peg我的 PEG 语法有问题(该项目有更新的分支发布到 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'] ;
    }

位于项目示例目录

我在 GitHub 上创建了基本计算器示例项目

php parser-generator peg
1个回答
0
投票

我会尝试将

Product
规则更改为:

Times: '*' > operand:Value >
ImplicitTimes: operand:Value >
Div: '/' > operand:Value >
Product: Value > ( Times | ImplicitTimes | Div ) *
    function Value( &$result, $sub ) {
        $result['val'] = $sub['val'] ;
    }
    function Times( &$result, $sub ) {
        $result['val'] *= $sub['operand']['val'] ;
    }
    function ImplicitTimes( &$result, $sub ) {
        $result['val'] *= $sub['operand']['val'] ;
    }
    function Div( &$result, $sub ) {
        $result['val'] /= $sub['operand']['val'] ;
    }
© www.soinside.com 2019 - 2024. All rights reserved.