我最近开始学习基本的 Flex 和 Bison,因为我必须为简单(但不太简单)的语法制作解析器。我决定在我的语法中制作一种简化的 Java 语言。我制作了.l
文件.y
,一切都编译没有错误(我正在使用 gcc 编译)。问题是每次我运行生成的程序时,我都会得到Syntax Error
,即使是简单的输入,例如:private class Something{}
。我没有得到 a 的唯一一次Syntax Error
是当我输入一个空行 ( \n
) 时。我已经为此苦苦挣扎了几天,我怀疑我的语法有问题,但我似乎找不到。当然也可能有其他问题,因为我对 Flex 和 Bison 还很陌生。
任何帮助将非常感激。
以下是.l
和.y
文件:
java.l
%{
#include "java.tab.h"
%}
%option noyywrap
%%
"\n" return 0;
[ \t] ;
"private" {return PRIVATE;}
"public" {return PUBLIC;}
"protected" {return PROTECTED;}
"implenets" {return IMPLEMENTS;}
"extends" {return EXTENDS;}
"class" {return CLASS;}
"interface" {return INTERFACE;}
"if" {return IF;}
"while" {return WHILE;}
"return" {return RETURN;}
"true" {return BOOLEAN;}
"false" {return BOOLEAN;}
[A-z][a-z0-9]* {return NAME;}
"\""[A-z0-9]*"\"" {return STRING;}
"-"?[1-9][0-9]* {return INT;}
"+"|"-"|"*"|"/"|"="|"==" {return OPERATOR;}
%%
java.y
%{
#include <stdio.h>
int cond=0;
int loops=0;
int assigns=0;
int funcs=0;
int classes=0;
void yyerror(const char* msg){printf("Error: %s\n", msg);}
%}
%token PUBLIC
%token PRIVATE
%token PROTECTED
%token NAME
%token IMPLEMENTS
%token EXTENDS
%token CLASS
%token INTERFACE
%token IF
%token WHILE
%token STRING
%token BOOLEAN
%token OPERATOR
%token RETURN
%token INT
%%
Code: Class Code | /*empty*/ {printf("classes: %d\n", classes); printf("functions: %d\n", funcs); printf("conditions: %d\n", cond);
printf("loops: %d\n", loops); printf("assign operations: %d\n", assigns);} ;
Class: Modifier ClassType NAME Extra '{' Functions '}' ;
Modifier: PUBLIC | PRIVATE | PROTECTED ;
ClassType: CLASS | INTERFACE ;
Extra: IMPLEMENTS NAME | EXTENDS NAME | /*empty*/ ;
Functions: Function Functions | /*empty*/ ;
Function: Type NAME '(' Arguments ')' '{' Commands '}' {funcs++;} ;
Arguments: Argument Arguments | /*empty*/ ;
Argument: Type NAME Separator ;
Type: STRING | INT | BOOLEAN ;
Separator: ',' | /*empty*/ ;
Commands: Command Commands | /*empty*/ ;
Command: Condition | Loop | Assignment | Return ;
Condition: IF '(' Comparison ')' '{' Commands '}' {cond++;} ;
Loop: WHILE '(' Comparison ')' '{' Commands '}' {loops++;} ;
Comparison: NAME OPERATOR INT | NAME OPERATOR NAME | INT OPERATOR NAME ;
Assignment: NAME '=' Type ';' {assigns++;} ;
Return: RETURN RetVal ';' ;
RetVal: NAME | Type ;
%%
int main()
{
yyparse();
return 0;
}