简体   繁体   English

在形成算术表达式的正确语法时需要帮助

[英]Need help in forming a correct grammar for arithmetic expressions

I am trying to do an old archived java course for which there is no forum help.我正在尝试做一个没有论坛帮助的旧存档 java 课程。 I have been stuck on one problem for a couple of days, would really appreciate any sort of help.我已经被一个问题困住了几天,非常感谢任何形式的帮助。 I am supposed to make an abstract Syntax Tree using a parser.我应该使用解析器制作一个抽象的语法树。 The parser reads from a Expression Grammar file, and then I have to make an Abstract tree using recursive call.解析器从表达式语法文件中读取,然后我必须使用递归调用创建一个抽象树。 The expression grammar that I have written is我写的表达式语法是

    @skip whitespace{
    root ::= expr;
    expr ::=  (product | sum) ((add| multi)* (product | sum)*)*   ;
    sum ::= primitive ( add  primitive)*  ;
    product ::=  primitive (multi primitive)*;
    primitive ::= variable | number | '(' sum ')' | '(' product ')' ;
    
}

    whitespace ::= [ \t\r\n];
    number ::= [0-9]+('.'[0-9]+)*;
    variable ::= [a-zA-Z]+;
    add ::= '+';
    multi ::= '*';

with this grammar the tree I am generating is for the input 1+2+3*4+5+6*7+8+(3*2*1) is attached below使用此语法,我生成的树用于输入1+2+3*4+5+6*7+8+(3*2*1)附在下面

在此处输入图像描述

you can see that its picking the product when its in brackets but I dont seem to get how to write the grammar such that 3*4 and 6*7 are captured as a product too and in Sums the number that comes before a multiplication sign is not included in the previous sum node您可以看到它在括号中时选择了产品,但我似乎不知道如何编写语法,以便将3*46*7也捕获为product ,并且在Sums中,乘法符号之前的数字是不包含在上一个求和节点中

You could get rid of expr here, but it's maybe more scalable like this.您可以在这里摆脱expr ,但它可能像这样更具可扩展性。 In any case, it's really much simpler than you think:无论如何,它真的比你想象的要简单得多:

root ::= expr;
expr ::= sum;
sum ::= product ( add product )* ;
product ::= primitive ( multi primitive )* ;
primitive ::= variable | number | '(' expr ')' ;

That should be intuitive (if you hone your intuitions :-) A sum is the sum of several products;这应该是直观的(如果你磨练你的直觉:-) 总和是几个产品的总和; a product cannot be the product of a sum.乘积不能是总和的乘积。 It can be the product of parenthesised sums, but a parenthesised sum is not a sum;它可以是带括号的和的乘积,但带括号的和不是和; it's a primitive, grammatically speaking.从语法上讲,这是一个原始的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM