24,857
社区成员




%{
#include "y.tab.h"
#include <math.h>
extern void *yyerror(char *msg);
%}
var [A-Za-z0-9]+
%%
AAA:{var} {
yylval.sval = yytext;
return KEYWORD;
}
BBB:{var} {
yylval.sval = yytext;
return KEYWORD;
}
[ \t] {
printf ( "whitespace\n" );
return WHITESPACE;
}
\n {
yylval.sval = yytext;
printf ( "newline\n" );
return NEWLINE;
}
. {
yylval.sval = yytext;
return ERROR;
}
%%
int yywrap()
{
return 1;
}
%{
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
extern FILE *yyin;
%}
%union {
int ival;
char *sval;
}
%token KEYWORD
%token WHITESPACE
%token NEWLINE
%token ERROR
%type <sval> KEYWORD
%type <sval> WHITESPACE
%type <sval> NEWLINE
%type <sval> ERROR
%%
statement_list: error
| statement '\n'
| statement_list statement '\n'
;
statement: KEYWORD { printf("%s\n", $1); }
| WHITESPACE { printf("WHITESPACE:%s\n", $1); }
| NEWLINE { printf("NEWLINE:%s\n", $1); }
| ERROR { yyerror($1); }
;
%%
int yyerror(char *msg)
{
printf("Error encountered: %s\n", msg);
}
int main()
{
yyin = fopen("test.txt", "r");
yyparse();
}
AAA:aaaqwer
BBB:bbbasf
YACC=yacc
LEX=lex
CC=gcc
main:y.tab.c lex.yy.c
$(CC) y.tab.c lex.yy.c -o main
y.tab.c:yacc.y
$(YACC) -d yacc.y
lex.yy.c:lex.l
$(LEX) lex.l
AAA:aaaqwer
newline
Error encountered: syntax error
NEWLINE:
BBB:bbbasf
newline
NEWLINE: