遗漏的细节太多了。例如,“int”可以用作类别名称吗?你打算如何存储你解析的数据?
尽管如此,解析器的初始草图将是这样的:
%token CATEGORY "category"
EQ "="
COLON ":"
COMMA ","
LBRA "["
RBRA "]"
INT "int"
CHAR "char"
ID
NATURAL
;
%%
categories:
category
| categories category
;
category:
"category" ID fields
;
fields:
field
| fields "," field
;
field:
ID ":" type
;
type:
"char"
| "int"
| type "[" NATURAL "]"
;
这对于扫描仪:
%%
"category" return CATEGORY;
"=" return EQ;
":" return COLON;
"," return COMMA;
"[" return LBRA;
"]" return RBRA;
"int" return INT;
"char" return CHAR;
[a-zA-Z]+ return ID;
[0-9]+ return NATURAL;
[ \n\t]+ continue;