使用 bison 时 yacc 嵌入式操作的问题

Problem with yacc embedded actions when using bison

我正在尝试实现 Brian Kernighan 和 Rob Pike 于 1984 年出版的“The Unix Programming Environment”一书中的编译器。该书采用 yacc,但我使用的是 Mac,它的 bison 版本为 2.3 .代码题在书中第276页有描述

我从使用嵌入式操作(yacc 术语)的 grammar/actions 中收到警告,我认为这与 bison 中的中间规则操作相同。

下面是生成警告的语法(行号来自清单):

158: defn: FUNC procname         { ->type=FUNCTION; indef=1; }
159:       '(' ')' stmt          { code(procret); define(); indef=0; }
160:     | PROC procname         { ->type=PROCEDURE; indef=1; }
161:       '(' ')' stmt          { code(procret); define(); indef=0; }
162:     ;
163:
164:
165: procname: VAR
166:    | FUNCTION
167:    | PROCEDURE
168:    ;

以下是来自 Bison 的警告:

7 rules never reduced
hoc.y: warning: 4 useless nonterminals and 7 useless rules
hoc.y:158.1-4: warning: useless nonterminal: defn
hoc.y:158.29-59: warning: useless nonterminal: @1
hoc.y:160.29-60: warning: useless nonterminal: @2
hoc.y:47.17-24: warning: useless nonterminal: procname
hoc.y:158.29-59: warning: useless rule: @1: /* empty */
hoc.y:158.7-159.67: warning: useless rule: defn: FUNC procname @1 '(' ')' stmt
hoc.y:160.29-60: warning: useless rule: @2: /* empty */
hoc.y:160.7-161.67: warning: useless rule: defn: PROC procname @2 '(' ')' stmt
hoc.y:165.11-13: warning: useless rule: procname: VAR
hoc.y:166.7-14: warning: useless rule: procname: FUNCTION
hoc.y:167.7-15: warning: useless rule: procname: PROCEDURE

grammar/actions 是否可以被 yacc 而不是 bison 接受?如果是这样,bison 是否有“yacc 模式”?如果不是,应该如何重写 grammar/actions 才能被 bison 接受?谢谢

这些 mid-rule 行为在野牛中是完全可以接受的。那不是你的问题。

如评论中所述,导致此错误消息的最可能原因是您的语法缺少包含 defn 的产生式,这是 list 的第三个产生式:

list:     /* nothing */
    | list '\n'
    | list defn '\n'
    | list asgn '\n'  { code2(xpop, STOP); return 1; }
    | list stmt '\n'  { code(STOP); return 1; } 
    | list expr '\n'  { code2(printtop, STOP); return 1; }
    | list error '\n' { yyerrok; }
    ;

您可以使用 Wayback Machine aka web.archive.org. I got that link from the Wikipedia entry for hoc 下载包含 UPE 书中所有代码的 tarball,其中还包含指向其他 hoc 实现的链接。