【问题标题】:Output produced for the given input using the bottom up parsing使用自下而上解析为给定输入生成的输出
【发布时间】:2021-01-06 17:56:28
【问题描述】:

我尝试解决这个问题,答案是选项 c。但在少数教科书中给出的答案是选项b。我很困惑正确的答案是什么?请帮助我

【问题讨论】:

  • 你有多本教科书都有同一个例子?
  • 两本教科书给出的答案不同。

标签: parsing compiler-construction bottom-up


【解决方案1】:

GAAAAT是正确答案;它是解析器产生的输出,它尊重翻译规则中的动作顺序(其中一些发生在规则中间)。

Yacc/bison 就是这样一种解析器,它可以很容易地验证:

%{
#include <ctype.h>
#include <stdio.h>
void yyerror(const char* msg) {
  fprintf(stderr, "%s\n", msg);
}
int yylex(void) {
  int ch;
  while ((ch = getchar()) != EOF) {
    if (isalnum(ch)) return ch;
  }
  return 0;
}
%}
%%
S: 'p'    { putchar('G'); } P 
P: 'q'    { putchar('A'); } Q
P: 'r'    { putchar('T'); } 
P: %empty { putchar('E'); } 
Q: 's'    { putchar('A'); } P
Q: %empty { putchar('O'); }
%%
int main(void) {
  yyparse();
  putchar('\n');
}
$ bison -o gate.c gate.y
$ gcc -std=c99 -Wall -o gate gate.c
$ ./gate<<<pqsqsr
GAAAAT

如果我们修改语法以将所有动作放在各自规则的末尾,我们得到答案 (b)。 (除了语法,其他都和上一个例子一样,所以我只展示新的翻译规则。)

S: 'p'    P { putchar('G'); } 
P: 'q'    Q { putchar('A'); }
P: 'r'    { putchar('T'); } 
P: %empty { putchar('E'); } 
Q: 's'    P { putchar('A'); } 
Q: %empty { putchar('O'); }
$ bison -o gate_no_mra.c gate_no_mra.y
$ gcc -std=c99 -Wall -o gate_no_mra gate_no_mra.c
$ ./gate_no_mra<<<pqsqsr
TAAAAG

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2012-10-18
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多