Bison 在 reduce 前后识别不同的 token

Bison recognizing different tokens before and after reduce

RELOP 可以是:== | != | < | > | <= | >=

& 我在 bison 中有这条规则应该被识别:

这是 LEX 文件夹中的部分代码:

=           {return ASSIGN;}
[<=|>=]                         {return RELOP1;}
[<|>]                           {return RELOP3;}

这是我的 ypp 文件夹中的代码:

%right    ASSIGN
%left     RELOP2
%left     BINOP2
%nonassoc RELOP1
%nonassoc RELOP3

Exp: Exp RELOP1 Exp { output::printProductionRule(46);}
        | Exp RELOP3 Exp { output::printProductionRule(46);}
        | Exp RELOP2 Exp { output::printProductionRule(46);}

这是测试:

int bar() {
    if (bar <= bar >= bar) {
        print("Then you got your associativity wrong");
    }
}

正如您在所附的屏幕截图中所见,bison 在执行 reduce 之前识别出 IF 中的第一个 '<=' (RELOP1),但第二次它只识别出 assign!什么会导致那?野牛

谢谢:)

[<=|>=] 是一个 字符 class,它只匹配一个字符,在这种情况下,如果该字符是 < 之一、=|>。 (将同一个字符放置两次 — =,在这种情况下 — 在字符 class 内是允许的,但没有任何效果。)

你想要 "<="|">="

如果两个模式匹配相同的最长字符串,flex 总是 returns 扫描器定义中的第一个。所以 flex 生成的第一个标记是 <,它与 RELOP1 匹配,因为 RELOP3 出现在文件的后面;然后它将 = 匹配为 ASSIGN 因为它来得更早。

我确定 Flex 发出了 RELOP3 规则无法匹配任何内容的警告。这个警告不应该被忽略;它几乎总是表示您的模式有误。

另请注意,RELOP3 规则也匹配 |,这可能不是您想要的。

请阅读 (f)lex patterns 上的文档。