Permalink
Browse files

Part 4 - Our Initial Parser

  • Loading branch information...
halogenandtoast committed Oct 1, 2014
1 parent 8b514ae commit 4a4ce7e25d6b8b63560baa46ebdb123bb6efc810
Showing with 33 additions and 7 deletions.
  1. +2 −0 .gitignore
  2. +7 −3 Makefile
  3. +2 −2 main.c
  4. +19 −0 parse.y
  5. +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
4 main.c
@@ -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;
}
19 parse.y
@@ -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); }
5 ruby.l
@@ -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"); }

0 comments on commit 4a4ce7e

Please sign in to comment.