Skip to content

Commit 5bca02f

Browse files
author
Fiwo735
committed
Moved yyerror to parser and added detailed errors using bison's options
1 parent 5fbac2d commit 5bca02f

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/parser.y

+13
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
#include "ast.hpp"
99
using namespace ast;
1010

11+
extern int yylineno;
12+
extern char* yytext;
1113
extern Node* g_root;
1214
extern FILE* yyin;
1315

@@ -16,6 +18,9 @@
1618
int yylex_destroy(void);
1719
}
1820

21+
%define parse.error detailed
22+
%define parse.lac full
23+
1924
%union {
2025
Node* node;
2126
NodeList* node_list;
@@ -33,6 +38,7 @@
3338
%token CHAR SHORT INT LONG SIGNED UNSIGNED FLOAT DOUBLE CONST VOLATILE VOID
3439
%token STRUCT UNION ENUM ELLIPSIS
3540
%token CASE DEFAULT IF ELSE SWITCH WHILE DO FOR GOTO CONTINUE BREAK RETURN
41+
%token UNKNOWN
3642

3743
%type <node> translation_unit external_declaration function_definition primary_expression postfix_expression
3844
%type <node> unary_expression cast_expression multiplicative_expression additive_expression shift_expression relational_expression
@@ -185,6 +191,13 @@ expression
185191

186192
%%
187193

194+
void yyerror (const char *s)
195+
{
196+
std::cerr << "Error: " << s << " at line " << yylineno;
197+
std::cerr << " near '" << yytext << "'" << std::endl;
198+
std::exit(1);
199+
}
200+
188201
Node* g_root;
189202

190203
NodePtr ParseAST(std::string file_name)

src/parser_full.y.example

+13
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
#include "ast.hpp"
55
using namespace ast;
66

7+
extern int yylineno;
8+
extern char* yytext;
79
extern Node* g_root;
810
extern FILE* yyin;
911

@@ -12,6 +14,9 @@
1214
int yylex_destroy(void);
1315
}
1416

17+
%define parse.error detailed
18+
%define parse.lac full
19+
1520
// Represents the value associated with any kind of AST node.
1621
%union {
1722
Node* node;
@@ -30,6 +35,7 @@
3035
%token CHAR SHORT INT LONG SIGNED UNSIGNED FLOAT DOUBLE CONST VOLATILE VOID
3136
%token STRUCT UNION ENUM ELLIPSIS
3237
%token CASE DEFAULT IF ELSE SWITCH WHILE DO FOR GOTO CONTINUE BREAK RETURN
38+
%token UNKNOWN
3339

3440
%type <node> translation_unit external_declaration function_definition primary_expression postfix_expression argument_expression_list
3541
%type <node> unary_expression cast_expression multiplicative_expression additive_expression shift_expression relational_expression
@@ -462,6 +468,13 @@ jump_statement
462468

463469
%%
464470

471+
void yyerror (const char *s)
472+
{
473+
std::cerr << "Error: " << s << " at line " << yylineno;
474+
std::cerr << " near '" << yytext << "'" << std::endl;
475+
std::exit(1);
476+
}
477+
465478
Node* g_root;
466479

467480
NodePtr ParseAST(std::string file_name)

0 commit comments

Comments
 (0)