Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Expand parser to support example program's syntax
  • Loading branch information
halogenandtoast committed Jan 3, 2015
1 parent 6079c33 commit df83498
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 9 deletions.
35 changes: 33 additions & 2 deletions parse.y
Expand Up @@ -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

Expand All @@ -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 changes: 11 additions & 7 deletions 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
Expand All @@ -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); }
Expand Down

0 comments on commit df83498

Please sign in to comment.