我无法找出我的计划无效的原因。 没有" a = 5;"在解析程序(这是下面的代码块)
%{
#include <iostream>
int line_count = 0;
#include "translator.h"
%}
%union
{
Stmt *separator;
Expr *exp;
Stmt *statement;
int int_val;
char name[256];
};
%token <int_val> NUM
%token <name> ID
%token STRING ENDLINE BOOLEAN INT MAIN PUBLIC CLASS VOID STATIC PRINTLN EQ
%start programm
%type <separator> separator
%type <statement> statement
%type <statement> assign_statement
%type <exp> exp
%type <exp> var_ref
%type <exp> literal_exp
%left EQ
%%
programm:
class_declaration
;
class_declaration:
PUBLIC CLASS ID opencurlybracket main_method_declaration closecurlybracket
;
main_method_declaration:
PUBLIC STATIC VOID MAIN '(' STRING '[' ']' ID ')' opencurlybracket method_body closecurlybracket
;
method_body:
local_declarations
|
statements
;
statements:
statement
|
statements statement
;
statement:
assign_statement
;
assign_statement:
var_ref '=' exp ';' separator { $$ = new StmtAssign($1, $3); }
;
local_declarations:
local_declaration
|
local_declarations local_declaration
;
local_declaration:
type ID ';' separator
;
exp:
var_ref
|
literal_exp
;
var_ref:
ID { $$ = new ExprVar($1); }
;
literal_exp:
NUM { $$ = new ExprNum($1); }
;
type:
INT
|
BOOLEAN
;
separator:
ENDLINE
{
++line_count;
$$ = new StmtEndline(line_count);
}
;
opencurlybracket:
'{'
|
'{' separator
;
closecurlybracket:
'}'
|
'}' separator
;
%%
通过这种语法解析的代码:
public class Summ {
public static void main(String[] args) {
int a;
a = 5;
}
}
和lex文件:
%{
#include <stdlib.h>
#include <stdio.h>
#include "translator.h"
%}
%option noyywrap
%%
(public) { return (PUBLIC); }
(class) { return (CLASS); }
(static) { return (STATIC); }
(void) { return (VOID); }
(main) { return (MAIN); }
(String) { return (STRING); }
(int) { return (INT); }
(println) { return (PRINTLN); }
(\{) { return '{'; }
(\}) { return '}'; }
(\() { return '('; }
(\)) { return ')'; }
(\[) { return '['; }
(\]) { return ']'; }
(\;) { return ';'; }
(\=) { return '='; }
"==" { return (EQ); }
(\n) { return (ENDLINE); }
[a-zA-Z_\$][a-zA-Z0-9_\$]* {
printf("found %s\n", yytext);
strcpy(yylval.name, yytext);
return ID;
}
([0])|([1-9][0-9]*) {
printf("found %s\n", yytext);
yylval.int_val = atoi(yytext);
return NUM;
}
" " { /*space - do nothing*/ }
. { /*do nothing*/ }
%%
我希望有人在我的代码中发现错误。
答案 0 :(得分:0)
以下是您对method_body
的定义:
method_body:
local_declarations
|
statements
;
这指定method_body
包含local_declarations
或statements
,但不包含。您需要将其更改为接受local_declarations
后跟statements
。