编译器在解析器过程中如何区分负数和负数 [英] How Compiler distinguishes minus and negative number during parser process

查看:468
本文介绍了编译器在解析器过程中如何区分负数和负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我最近参与了一个编译器开发,我遇到了负号(-)和负数(-1)的问题。假设现在我有5--3、5 + -3,如何编写语法规则,以便在抽象语法树构建期间,yacc会生成正确的抽象语法树?
我的语法像:

expr:
常数{}
| id {}
| exec_expr {}


exec_expr:
expr PLUS expr {}
| expr MINUS expr {}
| expr MUL expr {}
| expr DIV expr {}

Hey I'm recently involved in a compiler developer, I've encountered a problem with minus sign(-) and negative number(-1). Suppose now I have 5--3, 5+-3, how to write a grammar rule such that during the abstract syntax tree construction, yacc will produce a correct abstract syntax tree? My grammar is like: expr : constant {} | id {} | exec_expr {} exec_expr : expr PLUS expr {} | expr MINUS expr {} | expr MUL expr {} | expr DIV expr {}

我现在的想法是要处理一个具有最高顺序(非关联)的UMINUS符号案子。
不知何故,我们的编译器不得不将表达式拆分为expr和exec_expr,我尝试使用该方法,但由于某些原因它不起作用。

My thought for now is to have a UMINUS symbol with highest order (nonassociate) to deal with the case. Somehow, our compiler has to split the expression into expr and exec_expr, I've tried with the method but it doesn't work for some reasons.

用其他任何语言处理此案件的标准解决方案是什么?特别是那些带有LR(0)自动机的机器。非常感谢!

What's the standard solution for dealing with this case in any other language? Especially those with LR(0) automaton. Thanks so much!

推荐答案

从实际工程的角度来看, lexer 通常无法处理签名数字。

As a matter of practical engineering, usually the lexer doesn't handle signed numbers.

这意味着解析器可以处理减号,可以是两个操作数之间的减法(其中第二个可能是数字),也可以是负数。操作数(其中操作数可以是数字)。这也使得处理诸如 a--7之类的奇数表达式变得容易。因此,您所需要的只是 MINUS令牌。

This means the parser can handle the minus sign, either as a subtract between two operands (the second of which may be a number), or as the negative of the the operand (of which the operand may be a number). That also makes it easy to handle odd expressions like "a- -7". So all you need is the "MINUS" token.

您可以设计一个词法分析器和解析器,使词法分析器吞下符号字符。通常,它需要解析器的反馈,以了解安全的做法。这很不方便组织,因此也不实用。

You can design a lexer and parser where the lexer swallows the sign character. Usually it needs feedback from the parser to know what is safe to do. That's inconvenient to organize, and thus the practical engineering approach.

这篇关于编译器在解析器过程中如何区分负数和负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆