简体   繁体   English

解析算术表达式

[英]Parsing arithmetic expressions

I'm studying the dragon book and can't wait to write an expression parser. 我正在研究《龙书》,迫不及待想要编写一个表达式解析器。

In order to deal with negative number input, my lexer reads digits when meet the symbol '-' to return a number token. 为了处理负数输入,我的词法分析器在遇到符号“-”时会读取数字以返回数字标记。

"-4+2" Will get (-4,number) (+,operator) (2,number) “ -4 + 2”将获得(-4,number)(+,operator)(2,number)

but then I found that it can't do things as easy as "4-2" because 但后来我发现它做不到像“ 4-2”一样简单的事情,因为

(4,number) (-2,number) It's a wrong syntax. (4,number)(-2,number)这是错误的语法。

One of my solution is doing some pre-processing before evaluating an expression, such as appending a zero if the first token is a minus. 我的解决方案之一是在评估表达式之前进行一些预处理,例如,如果第一个标记为负号,则添加零。 I'm wondering how you guys deal with this situation? 我想知道你们如何处理这种情况?

Thanks. 谢谢。

You should have the following grammar, but not make "-" number into a token. 您应该具有以下语法,但不能将"-" number标记为令牌。

number := DIGIT+

unary := number
unary := "-" unary

expr := expr "+" unary
expr := expr "-" unary
...

As there are unary expressions, it is not a operator-precedence grammar. 由于存在一元表达式,因此它不是运算符优先语法。 You should parse it with a more complex parser. 您应该使用更复杂的解析器对其进行解析。

my lexer reads digits when meet the symbol '-' to return a negative number 我的词法分析器在遇到符号“-”时会读取数字以返回负数

Don't. 别。 Unary operators should be dealt with by the parser, not the lexer. 一元运算符应由解析器而不是词法分析器处理。

One of my solution is doing some pre-processing before evaluating an expression, such as appending a zero if the first token is a minus. 我的解决方案之一是在评估表达式之前进行一些预处理,例如,如果第一个标记为负号,则添加零。

No. Fix the problem. 否。解决问题。

When you're in a hole, stop digging. 当您陷入困境时,请停止挖掘。

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

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