Permalink
Browse files

Expand parser to support example program's syntax

  • Loading branch information...
halogenandtoast committed Jan 3, 2015
1 parent 6079c33 commit df8349870087a6bb8a94d7e08a885a9c435dd28a
Showing with 44 additions and 9 deletions.
  1. +33 −2 parse.y
  2. +11 −7 ruby.l
35 parse.y
@@ -4,11 +4,19 @@
extern void yyerror(char const *s);
%}
%union {
int ival;
float fval;
char *sval;
}
%left tPLUS
%right tEQUAL
%token tSTRING tFLOAT tNUMBER tID tCONSTANT tEQUAL tGT tLT tGTE tLTE tNEQUAL
%token tPLUS tMINUS tMULT tDIV tMOD tEMARK tQMARK tAND tOR tLSBRACE tRSBRACE
%token tLPAREN tRPAREN tLBRACE tRBRACE tAT tDOT tCOMMA tCOLON
%token kCLASS kEND kDEF
%start program
@@ -19,5 +27,28 @@ program: expressions
expressions: expressions expression
| expression
expression: tNUMBER
| expression tPLUS expression { printf("%d\n", $1 + $3); }
expression: class_definition
| binary_expression
| method_definition
| variable
| assignment
| method_call
| value
binary_expression: expression tPLUS expression
assignment: variable tEQUAL expression
class_definition: kCLASS tCONSTANT expressions kEND
method_definition: kDEF tID expressions kEND
| kDEF tID tLPAREN tID tRPAREN expressions kEND
method_call: variable tDOT tID
| tCONSTANT tDOT tID tLPAREN tSTRING tRPAREN
| tID tSTRING
variable: tID
| tAT tID
value: tNUMBER
18 ruby.l
@@ -1,8 +1,9 @@
%{
#include <stdio.h>
#include <string.h>
#include "parse.tab.h"
#define VTYPE(type, value) printf("%s(%s)\n", type, value)
#define TOKEN(id) return t##id
#define KEYWORD(id) return k##id
%}
%option noyywrap
@@ -11,13 +12,16 @@
NUMBER [0-9](_[0-9]|[0-9])*
%%
class { KEYWORD(CLASS); }
end { KEYWORD(END); }
def {KEYWORD(DEF); }
#.*$ {}
\"([^"]|\\.)*\" { VTYPE("STRING", yytext); TOKEN(STRING); }
\'([^']|\\.)*\' { VTYPE("STRING", yytext); TOKEN(STRING); }
{NUMBER}(\.{NUMBER}|(\.{NUMBER})?[eE][+-]?{NUMBER}) { VTYPE("FLOAT", yytext); TOKEN(FLOAT); }
{NUMBER} { yylval = atoi(yytext); TOKEN(NUMBER); }
[a-z_][a-zA-Z0-9_]* { VTYPE("ID", yytext); TOKEN(ID); }
[A-Z][a-zA-Z0-9_]* { VTYPE("CONSTANT", 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 df83498

Please sign in to comment.