我正在建立一个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 ...
}
我不知道如何&#34; concat&#34;所有陈述到&#34; statement_list&#34;的$$。 :(
答案 0 :(得分:0)
您必须设计一个类层次结构。仅使用char * / string不足以保留程序语义。