简体   繁体   English

算术表达式语法

[英]Arithmetic expression grammar

I'm trying to create an appropriate grammer for some arithmetic expressions.我正在尝试为一些算术表达式创建一个合适的语法。 The valid tokens for my expressions are the following:我的表达式的有效标记如下:

'+', '-', '/', '*' , and '**' for powers. '+', '-', '/', '*''**'表示幂。 The expressions could also contain symbols and functions.表达式还可以包含符号和函数。 The functions can take multiple arguments, some of which might be optional.这些函数可以采用多个 arguments,其中一些可能是可选的。 From what little I remember from expression parsing, I must come up with a grammar that is not left-recursive and also preserves operator associativity.从我对表达式解析的记忆中,我必须想出一个不是左递归并且还保留运算符关联性的语法。

So here is what I came up with, after a little bit of searching (though not sure about associativity):所以这是我想出的,经过一番搜索(虽然不确定关联性):

E = T Eopt
Eopt = '+' T Eopt | '-' T Eopt | ε 
T = F Topt
Topt = '*' F Topt | '/' F Topt | ε
F = Number | '(' E ')' 

which can be found in many textbooks.这可以在许多教科书中找到。 What changes does the above grammar need, so that it can acommodate the power token ('**') and both symbols and functions?上述语法需要进行哪些更改,以便它可以容纳权力标记('**')以及符号和函数?

Please do not point me to flex/yacc etc. Thank you.请不要将我指向 flex/yacc 等。谢谢。

You're almost there.您快到了。 Changes begin at F:变化从 F 开始:

E = T Eopt
Eopt = '+' T Eopt | '-' T Eopt | ε 
T = F Topt
Topt = '*' F Topt | '/' F Topt | ε
F = P Fopt
Fopt = '**' P Fopt | ε
P = Number | '(' E ')'

This assumes your tokenizer is distinguishing between * and ** .这假设您的标记器区分***

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

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