]> git.lizzy.rs Git - nothing.git/blob - src/script/expr.h
TODO(#394)
[nothing.git] / src / script / expr.h
1 #ifndef EXPR_H_
2 #define EXPR_H_
3
4 #include <stdlib.h>
5 #include <stdbool.h>
6
7 typedef struct Gc Gc;
8 typedef struct Scope Scope;
9
10 struct Cons;
11 struct Atom;
12
13 #define NUMBER(G, X) atom_as_expr(create_number_atom(G, X))
14 #define STRING(G, S) atom_as_expr(create_string_atom(G, S, NULL))
15 #define SYMBOL(G, S) atom_as_expr(create_symbol_atom(G, S, NULL))
16 #define NATIVE(G, F, P) atom_as_expr(create_native_atom(G, F, P))
17 #define CONS(G, CAR, CDR) cons_as_expr(create_cons(G, CAR, CDR))
18 #define NIL(G) SYMBOL(G, "nil")
19
20 #define CAR(O) ((O).cons->car)
21 #define CDR(O) ((O).cons->cdr)
22
23 enum ExprType
24 {
25     EXPR_ATOM = 0,
26     EXPR_CONS,
27     EXPR_VOID
28 };
29
30 struct Expr
31 {
32     enum ExprType type;
33     union {
34         struct Cons *cons;
35         struct Atom *atom;
36     };
37 };
38
39 struct Expr atom_as_expr(struct Atom *atom);
40 struct Expr cons_as_expr(struct Cons *cons);
41 struct Expr void_expr(void);
42
43 void destroy_expr(struct Expr expr);
44 void print_expr_as_sexpr(struct Expr expr);
45 int expr_as_sexpr(struct Expr expr, char *output, size_t n);
46
47 // TODO(#337): EvalResult does not belong to expr unit
48 struct EvalResult
49 {
50     bool is_error;
51     struct Expr expr;
52 };
53
54
55 typedef struct EvalResult (*NativeFunction)(void *param, Gc *gc, struct Scope *scope, struct Expr args);
56
57 struct Native
58 {
59     NativeFunction fun;
60     void *param;
61 };
62
63 enum AtomType
64 {
65     ATOM_SYMBOL = 0,
66     ATOM_NUMBER,
67     ATOM_STRING,
68     ATOM_NATIVE
69 };
70
71 struct Atom
72 {
73     enum AtomType type;
74     union
75     {
76         // TODO(#330): Atom doesn't support floats
77         long int num;           // ATOM_NUMBER
78         char *sym;              // ATOM_SYMBOL
79         char *str;              // ATOM_STRING
80         struct Native native;   // ATOM_NATIVE
81     };
82 };
83
84 struct Atom *create_number_atom(Gc *gc, long int num);
85 struct Atom *create_string_atom(Gc *gc, const char *str, const char *str_end);
86 struct Atom *create_symbol_atom(Gc *gc, const char *sym, const char *sym_end);
87 struct Atom *create_native_atom(Gc *gc, NativeFunction fun, void *param);
88 void destroy_atom(struct Atom *atom);
89 void print_atom_as_sexpr(struct Atom *atom);
90
91 struct Cons
92 {
93     struct Expr car;
94     struct Expr cdr;
95 };
96
97 struct Cons *create_cons(Gc *gc, struct Expr car, struct Expr cdr);
98 void destroy_cons(struct Cons *cons);
99 void print_cons_as_sexpr(struct Cons *cons);
100
101 #endif  // EXPR_H_