+/- 数字前缀符号:词汇/句法元素?
我想为我的表达式计算器的数字添加 +/- 符号支持,但是我不确定它是否应该是词汇元素作为数字标记的一部分(例如 number = [\+\-]*[0 -9]+
)或语法(例如 primary ::= [ ( "+" | "-" ) ] Primary | number
其中 number = [0-9]+ )。
从上面可以看出,这个符号可以是任意多个。目前,我已经使用递归下降和运算符优先级解析实现了语法版本。但我仍然不确定这是否是一个好的选择。我发现的一件事是,语法版本要求对其遇到的每个符号进行递归。
I would like to add +/- sign support to number for my expression evaluator, however I'm not sure whether it should be lexical element as part of number token (e.g. number = [\+\-]*[0-9]+
) or syntactical (e.g. primary ::= [ ( "+" | "-" ) ] primary | number
where number = [0-9]+
).
As can be seen from above, this sign could be arbitrarily many. Currently, I've implemented the syntactical version using both recursive descent and operator precedence parsing. But I'm still not sure whether this is a good choice or not. One thing I spot, the syntactical version requires recursion for each sign it meets.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为如果您同时使用两者就很好:
1 - -1 = 2
I think it's good if you use both:
1 - -1 = 2
实际上,很难使“-”成为一个词法元素,因为您还需要在其其他用法中将其识别为标准的双操作数“减”运算符。
如果您生成“-”作为独立的词位,则解析器可以根据您提供的语法规则轻松确定它是减法运算符还是否定运算符。
词法分析器无法做出此决定,因为根据设计,它无法访问解析器状态。那么它如何合理地判断它刚刚遇到的“-”字符是否应该导致生成“-”标记,或者被后面的数字文字消耗?如果它被以下数字文字消耗,那么您的解析器将遇到表达式问题:
您可能想要的语法规则来处理两种类型的减号是:(
我会让您将它们重构为适合您的任何形式) 。
As a practical matter, it is hard to make "-" be a lexical element, because you also need to recognize it in its other usage as the standard two-operand "subtract" operator.
If you produce "-" as a standalone lexeme, the parser can easily decide if it is the subtract operator or a negate operator because of the grammmar rules you provide.
The lexer cannot make this decision since by design it doesn't have access to the parser state. So how can it reasonably tell if the "-" character it has just encountered, should cause the generation of a '-' token, or be consumed by a following numeric literal? If it is consumed by the following numeric literal, then your parser will have trouble with the expression:
What you probabaly want as grammar rules to handle both type of minus signs are:
(I'll let you refactor these into whatever form suits you).