【问题标题】:Concat value in yacc recursionyacc递归中的concat值
【发布时间】:2016-12-08 08:42:07
【问题描述】:

我正在构建一个 yacc 程序来检查 while 和 do-while 循环。

这是我的程序

%{
#include<stdio.h>
#include<string.h>
#include <stdlib.h>

#include"my_lex.tab.h"

extern FILE *yyin;

int yylex();
void yyerror(const char *str);

%}

%token ID NUMBER WHILE DO CONDITION OR AND VAR
%left AND OR "-" "+" "*" "/"
%start S

%union {
    char *s;
    string str;
}
%type <s> S_W S_DW block assignment statement declaration statement_list
%%

S : S1                  
   |S1 S


S1 : S_W                           
    |S_DW    
    |statement
    { printf("- Stand-alone statement \n");}

S_DW : DO block WHILE '(' condition ')' ';'     { printf("- Do-while loop \n"); printf("%s \n", $2); }

S_W    : WHILE '(' condition ')' block          { printf("- While loop \n"); printf("%s \n", $5); }


block : '{' statement_list '}'                  { $$ = $2; }

statement_list : /* blank */                    
                { $$ = ""; }
                | statement statement_list      
                { 
                    I'm stucking right here ...
                }

statement : declaration                         { $$ = $1; }
            | assignment                        { $$ = $1; }

........

所以现在当我运行我的程序时,我希望它把我的 yacc 打印为解析树,如下所示:

\\ input file

do {
    a = a + 4;
    b = c + d - 4;
} while (i <= 0);

var test = 4;

while (i > 0 && a && b) {
    var x = a - b;
}

\\ yacc output:

- do-while loop
-- assignment
-- assignment
- stand-alone statement
- while loop
-- declaration

我坚持递归语句定义。

statement_list : /* blank */                    
               { $$ = ""; }
                | statement statement_list      
                { 
                    I'm stucking right here ...
                }

我不知道如何将所有语句“连接”到“statement_list”的 $$。 :(

【问题讨论】:

    标签: c++ bison yacc


    【解决方案1】:

    您必须设计一个类层次结构。仅使用 char*/string 不足以保留程序语义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 2021-12-26
      • 2021-06-18
      相关资源
      最近更新 更多