Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Part 4 - Our Initial Parser
- Loading branch information
Showing
with
33 additions
and
7 deletions.
-
+2
−0
.gitignore
-
+7
−3
Makefile
-
+2
−2
main.c
-
+19
−0
parse.y
-
+3
−2
ruby.l
|
|
@@ -1,3 +1,5 @@ |
|
|
program.rb |
|
|
lex.yy.c |
|
|
ruby |
|
|
parse.tab.c |
|
|
parse.tab.h |
|
|
@@ -1,10 +1,14 @@ |
|
|
SRC=main.c parse.tab.c lex.yy.c |
|
|
all: ruby |
|
|
|
|
|
ruby: main.c lex.yy.c |
|
|
cc -o ruby main.c lex.yy.c |
|
|
ruby: ${SRC} |
|
|
cc -o ruby ${SRC} |
|
|
|
|
|
lex.yy.c: ruby.l |
|
|
flex ruby.l |
|
|
|
|
|
parse.tab.c: parse.y |
|
|
bison -d parse.y |
|
|
|
|
|
clean: |
|
|
rm -rf ruby lex.yy.c |
|
|
rm -rf ruby lex.yy.c parse.tab.c parse.tab.h |
|
|
@@ -1,14 +1,14 @@ |
|
|
#include <stdio.h> |
|
|
#include <stdlib.h> |
|
|
#include "parse.tab.h" |
|
|
|
|
|
extern FILE* yyin; |
|
|
extern int yylex(void); |
|
|
|
|
|
int main(int argc, char *argv[]) { |
|
|
if(argc > 1) { |
|
|
yyin = fopen(argv[1], "r"); |
|
|
} |
|
|
|
|
|
yylex(); |
|
|
yyparse(); |
|
|
return EXIT_SUCCESS; |
|
|
} |
|
|
@@ -0,0 +1,19 @@ |
|
|
%{ |
|
|
#include <stdio.h> |
|
|
extern int yylex(void); |
|
|
void yyerror(char const *s) { fprintf(stderr, "%s\n", s); } |
|
|
%} |
|
|
|
|
|
%token tNUMBER |
|
|
%token tPLUS |
|
|
%start program |
|
|
|
|
|
%% |
|
|
|
|
|
program: expressions |
|
|
|
|
|
expressions: expressions expression |
|
|
| expression |
|
|
|
|
|
expression: tNUMBER |
|
|
| expression tPLUS expression { printf("%d\n", $1 + $3); } |
|
|
@@ -1,5 +1,6 @@ |
|
|
%{ |
|
|
#include <stdio.h> |
|
|
#include "parse.tab.h" |
|
|
#define VTYPE(type, value) printf("%s(%s)\n", type, value) |
|
|
#define TYPE(type) printf("%s\n", type) |
|
|
%} |
|
@@ -13,7 +14,7 @@ NUMBER [0-9](_[0-9]|[0-9])* |
|
|
\"([^"]|\\.)*\" { VTYPE("STRING", yytext); } |
|
|
\'([^']|\\.)*\' { VTYPE("STRING", yytext); } |
|
|
{NUMBER}(\.{NUMBER}|(\.{NUMBER})?[eE][+-]?{NUMBER}) { VTYPE("FLOAT", yytext); } |
|
|
{NUMBER} { VTYPE("NUMBER", yytext); } |
|
|
{NUMBER} { yylval = atoi(yytext); return tNUMBER; } |
|
|
[a-z_][a-zA-Z0-9_]* { VTYPE("ID", yytext); } |
|
|
[A-Z][a-zA-Z0-9_]* { VTYPE("CONSTANT", yytext); } |
|
|
"=" { TYPE("EQUAL"); } |
|
@@ -22,7 +23,7 @@ NUMBER [0-9](_[0-9]|[0-9])* |
|
|
">=" { TYPE("GTE"); } |
|
|
"<=" { TYPE("LTE"); } |
|
|
"!=" { TYPE("NEQUAL"); } |
|
|
"+" { TYPE("PLUS"); } |
|
|
"+" { return tPLUS; } |
|
|
"-" { TYPE("MINUS"); } |
|
|
"*" { TYPE("MULT"); } |
|
|
"/" { TYPE("DIV"); } |
|
|