Skip to content

Instantly share code, notes, and snippets.

@fjolnir
Created May 27, 2012 14:11
Show Gist options
  • Save fjolnir/2814353 to your computer and use it in GitHub Desktop.
Save fjolnir/2814353 to your computer and use it in GitHub Desktop.
%union {
double dbl;
char *text;
}
%token <text> tLPAREN tRPAREN /* () */
%token <text> tLBRACE tRBRACE /* {} */
%token <text> tLBRACKET tRBRACKET /* {} */
%token <text> tPIPE /* | */
%token <text> tCOLON /* : */
%token <text> tSEMICOLON /* ; */
%token <text> tDOT /* . */
%token <text> tCOMMA /* , */
%token <text> tASSIGN /* = */
%token <text> tARROW /* -> */
%token <dbl> tNUMBER /* <number> */
%token <text> tSTRING /* Contents of a quoted string */
%token <text> tIDENTIFIER /* An identifier, non quoted string matching [a-zA-Z0-9_]+ */
%type<text> variable assignment expression lhs object_access literal object
%start expressions
%{
#include <stdio.h>
#include <stdlib.h>
extern int yylineno;
extern char* yytext;
%}
%%
assignment:
lhs tASSIGN expression { printf("------ %s = %s\n", $1, $3); $$=malloc(128); sprintf($$, "%s=%s", $1, $3); }
;
lhs:
variable
| object_access
;
variable:
tIDENTIFIER { printf("variable: %s\n", $1); $$=malloc(128); sprintf($$, "%s", $1); }
;
expressions:
| expressions expression
;
expression: { $$ = "expr"; }
object { printf("object!\n"); }
| block { printf("Block!\n"); }
| call { printf("Call!\n"); }
| assignment
| object_access
| variable
| literal
| tLPAREN expression tRPAREN
;
/* Block definition */
block:
tLBRACE block_args tPIPE expressions tRBRACE
| tLBRACE tPIPE expressions tRBRACE
| tLBRACE expressions tRBRACE
;
block_args:
tCOLON block_arg
| block_args tCOLON block_arg
| block_args block_arg_identifier tCOLON block_arg
;
block_arg:
tIDENTIFIER { printf("arg var: %s\n", $1); }
;
block_arg_identifier:
tIDENTIFIER { printf("arg name: %s\n", $1); }
;
/* Block call */
call:
lhs tDOT
| lhs block_args tDOT
;
/* Object definition */
object:
tLBRACKET object_members tRBRACKET
;
object_members:
| object_members object_member
;
object_member:
tIDENTIFIER tARROW expression { printf("object member: %s\n", $1); }
;
/* Object access */
object_access:
variable tDOT tIDENTIFIER { printf("objectacc: %s.%s\n", $1, $3); $$=malloc(128); sprintf($$, "%s.%s", $1, $3); }
;
literal:
tNUMBER { printf("num %f\n", $1); $$=malloc(128); sprintf($$, "%f", $1); }
| tSTRING { printf("str '%s'\n", $1); }
;
%%
int yyerror(char *str)
{
fprintf(stderr, "%d: error: '%s' at '%s'\n", yylineno, str, yytext);
exit(3);
return 0;
}
int yywrap(void) {
return 1;
}
int main()
{
yydebug = 5;
yyparse();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment