summaryrefslogtreecommitdiff
path: root/lisp.y
blob: 8ed479d4d397c2172d6e8d0c38e09067fda85566 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
%{
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "lisp.h"

int yylex(void);
int yyerror(const char *s);

static int is_integer(double x) {
    return floor(x) == x && isfinite(x);
}
%}

%union {
        int ival;
        double dval;
        const char *strval;
        value *val;
}
%token <dval> NUMBER
%token <strval> STRING SYMBOL
%token <ival> LPAREN RPAREN DOT
%token <ival> PLUS MINUS MULT DIV

%type <val> sexpr atom list list_items

%start sexprs

%%
sexprs: sexpr
      {
        print_value(eval(global_env, $1)); printf("\n");
      }
      | sexprs sexpr
      {
        print_value(eval(global_env, $2)); printf("\n");
      };

sexpr:  atom
     |  list
     |  LPAREN sexpr DOT sexpr RPAREN
     {
       $$ = cons($2, $4);
     };

list: LPAREN list_items RPAREN
    { $$ = $2; };

list_items: /* empty list */ { $$ = make_nil(); }
          | sexpr list_items { $$ = cons($1, $2); }
          | sexpr DOT sexpr { $$ = cons($1, $3); };

atom:   NUMBER
    {
      if(is_integer($1)) {
        $$ = make_int($1);
      } else {
        $$ = make_double($1);
      }
    }
    |   STRING { $$ = make_string($1); };
    |   SYMBOL { $$ = make_symbol($1); };
%%

int yyerror(const char *s) { 
  printf("%s\n",s); 
}