如何解决2 + 2和2 + 2冲突 [英] how to resolve 2+2 and 2++2 conflict

查看:128
本文介绍了如何解决2 + 2和2 + 2冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在较大的程序我已经给下面的(柔性/野牛)

在软硬度:

  PN [\\ + | \\  - ]
挖[0-9] +
EXP [E | E] {}掏+

 +{printf的(+检测\\ n);
                返回PLUS_SIGN;}
{PN} {}掏+ {printf的(数字检测 - %S \\ n,yytext中)?;
                sscanf的(yytext中,%D,为(int *)及yylval);
                返回TYPE_INT;}

在野牛:

  expr的:
    EXPR PLUS_SIGN EXPR
      {
        $$ = $ 1 + $ 3;
        的printf($$ =%F \\ N,$$);
      }
    | TYPE_INT
      {
        $$ =(INT)$ 1;
        的printf($$ =%F \\ N,$$);
      }
;

问题是:

当我给2 + 2它承认2和+2代替,+ 2

我怎样才能得到它做加法?


解决方案

  {PN} {}掏+

不要让加号或减号( {PN?} )的数量令牌的一部分。把它们当作两个独立的令牌, + 2 。然后弯曲不会有任何歧义解决。

  {}掏+

相反,有野牛处理一元加号和减号运营商。让它解析器的工作,而不是词法分析器的。

  | PLUS_SIGN EXPR
  {
    $$ = + $ 2;
    的printf($$ =%F \\ N,$$);
  }
| MINUS_SIGN EXPR
  {
    $$ = - $ 2;
    的printf($$ =%F \\ N,$$);
  }

In larger program I have given the following (flex/bison)

In flex:

pn [\+|\-]
dig [0-9]+
exp [e|E]{dig}+

.

.

.

"+"             {printf("+ detected\n");
                return PLUS_SIGN;}




{pn}?{dig}+         { printf("digit detected - %s\n",yytext);
                sscanf(yytext, "%d", (int*)&yylval);
                return TYPE_INT;}

In Bison:

expr:
    expr PLUS_SIGN expr
      {
        $$ = $1 + $3;
        printf(" $$=%f\n",$$);
      }
    | TYPE_INT
      {     
        $$ = (int)$1;
        printf(" $$=%f\n",$$);
      }
;

The problem is:

When I give 2+2 it recognizes 2 and +2 instead of 2 , + , 2

How can I get it to do the addition?

解决方案

{pn}?{dig}+

Don't make the plus or minus sign ({pn?}) part of the number token. Treat them as two separate tokens, + and 2. Then flex won't have any ambiguity to resolve.

{dig}+

Instead, have bison handle the unary plus and minus operators. Make it the parser's job, not the lexer's.

| PLUS_SIGN expr
  {
    $$ = +$2;
    printf(" $$=%f\n",$$);
  }
| MINUS_SIGN expr
  {
    $$ = -$2;
    printf(" $$=%f\n",$$);
  }

这篇关于如何解决2 + 2和2 + 2冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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