题目:
.输入一符号串,若合法,则输出括号( )的对数
S' : S print (S. num)
S : ( L ) S. num := L.num + 1
S : a S. num := 0
L : L1 , S L. num := L1. num + S. num
L : S L. num := S.num
.lex文件
%{
/*
* 输入一符号串,若合法,则输出括号的对数
*/
#include <stdlib.h>
void yyerror(char*);
%}
%%
[()\n] {
return *yytext;
}
. {return a;}
%%
int yywrap(void)
{
return 1;
}
.y文件
%token a
%{
#include <stdio.h>
#define YYSTYPE St
void yyerror(char*);
int yylex(void);
typedef struct
{
int num;
}St;
%}
%%
program:
program statement '\n'
|
;
statement:
head {printf("\n");}
;
head : s {printf("%d\n"),$1.num;}
;
s : '(' l ')' {$$.num=$2.num+1;}
| a {$$.num=0;}
;
l : l ',' s {$$.num=$1.num+$3.num;}
| s {$$.num=$1.num;}
;
%%
void yyerror(char* s)
{
fprintf(stderr, "%s\n", s);
}
#include "lex.yy.c"
int main(void)
{
printf("panduankuohaoduishu.\n");
yyparse();
return 0;
}
运行结果: