Permalink
Browse files

Make parser reentrant and pass state

  • Loading branch information...
1 parent df83498 commit d100b69d71c558a17265a9c59387448f6eebc560 @halogenandtoast committed Jan 29, 2015
Showing with 30 additions and 10 deletions.
  1. +6 −1 main.c
  2. +4 −0 node.h
  3. +12 −3 parse.y
  4. +8 −6 ruby.l
View
@@ -1,14 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
+#include "node.h"
#include "parse.tab.h"
extern FILE* yyin;
int main(int argc, char *argv[]) {
+ parser_state state = { NULL, 0 };
+
if(argc > 1) {
+ state.source_file = strdup(argv[1]);
yyin = fopen(argv[1], "r");
}
- yyparse();
+ yyparse(&state);
return EXIT_SUCCESS;
}
View
@@ -0,0 +1,4 @@
+typedef struct parser_state {
+ char *source_file;
+ int source_line;
+} parser_state;
View
@@ -1,15 +1,24 @@
%{
#include <stdio.h>
- extern int yylex(void);
- extern void yyerror(char const *s);
+ #include "node.h"
+ extern void yyerror(struct parser_state *state, const char *s);
%}
+%pure-parser
+%parse-param { parser_state *state }
+%lex-param { state }
+
%union {
int ival;
float fval;
char *sval;
}
+%{
+ extern int yylex(YYSTYPE *yylval, parser_state *state);
+%}
+
+
%left tPLUS
%right tEQUAL
@@ -22,7 +31,7 @@
%%
-program: expressions
+program: expressions { printf("%s\n", state->source_file); }
expressions: expressions expression
| expression
View
@@ -1,7 +1,9 @@
%{
#include <stdio.h>
#include <string.h>
+ #include "node.h"
#include "parse.tab.h"
+ #define YY_DECL int yylex(YYSTYPE *yylval, parser_state *state)
#define TOKEN(id) return t##id
#define KEYWORD(id) return k##id
%}
@@ -16,12 +18,12 @@ class { KEYWORD(CLASS); }
end { KEYWORD(END); }
def {KEYWORD(DEF); }
#.*$ {}
-\"([^"]|\\.)*\" { yylval.sval = strdup(yytext); TOKEN(STRING); }
-\'([^']|\\.)*\' { yylval.sval = strdup(yytext); TOKEN(STRING); }
-{NUMBER}(\.{NUMBER}|(\.{NUMBER})?[eE][+-]?{NUMBER}) { yylval.fval = atof(yytext); TOKEN(FLOAT); }
-{NUMBER} { yylval.ival = atoi(yytext); TOKEN(NUMBER); }
-[a-z_][a-zA-Z0-9_]* { yylval.sval = strdup(yytext); TOKEN(ID); }
-[A-Z][a-zA-Z0-9_]* { yylval.sval = strdup(yytext); TOKEN(CONSTANT); }
+\"([^"]|\\.)*\" { yylval->sval = strdup(yytext); TOKEN(STRING); }
+\'([^']|\\.)*\' { yylval->sval = strdup(yytext); TOKEN(STRING); }
+{NUMBER}(\.{NUMBER}|(\.{NUMBER})?[eE][+-]?{NUMBER}) { yylval->fval = atof(yytext); TOKEN(FLOAT); }
+{NUMBER} { yylval->ival = atoi(yytext); TOKEN(NUMBER); }
+[a-z_][a-zA-Z0-9_]* { yylval->sval = strdup(yytext); TOKEN(ID); }
+[A-Z][a-zA-Z0-9_]* { yylval->sval = strdup(yytext); TOKEN(CONSTANT); }
"=" { TOKEN(EQUAL); }
">" { TOKEN(GT); }
"<" { TOKEN(LT); }

0 comments on commit d100b69

Please sign in to comment.