swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 1 | /* -*- mode:c -*- */ |
| 2 | |
swissChili | ca107a0 | 2021-04-14 12:07:30 -0700 | [diff] [blame] | 3 | #include "compiler.h" |
| 4 | |
| 5 | #include <dasm_proto.h> |
| 6 | #include <dasm_x86.h> |
| 7 | |
| 8 | #define value_size sizeof (struct value) |
| 9 | |
| 10 | |.arch x86; |
| 11 | |
| 12 | |.macro setup, nvars; |
| 13 | | push ebp; |
| 14 | | mov ebp, esp; |
swissChili | 8cfb7c4 | 2021-04-18 21:17:58 -0700 | [diff] [blame] | 15 | | sub esp, (value_size * nvars); |
swissChili | ca107a0 | 2021-04-14 12:07:30 -0700 | [diff] [blame] | 16 | |.endmacro; |
| 17 | |
| 18 | |.macro cleanup; |
| 19 | | mov esp, ebp; |
| 20 | | pop ebp; |
| 21 | | ret; |
| 22 | |.endmacro; |
| 23 | |
| 24 | dasm_State *d; |
| 25 | unsigned int npc = 8; |
| 26 | |
| 27 | struct function *find_function (struct environment *env, char *name) |
| 28 | { |
| 29 | struct function *f = env->first; |
| 30 | |
| 31 | while ( strcmp (f->name, name) != 0 ) |
| 32 | { |
| 33 | if ( f->prev ) |
| 34 | f = f->prev; |
| 35 | else |
| 36 | return NULL; |
| 37 | } |
| 38 | |
| 39 | return f; |
| 40 | } |
| 41 | |
| 42 | void compile (struct istream *is) |
| 43 | { |
| 44 | |.section code; |
| 45 | dasm_init (&d, DASM_MAXSECTION); |
| 46 | |
| 47 | |.globals lbl_; |
| 48 | void *labels[ lbl__MAX ]; |
| 49 | dasm_setupglobal (&d, labels, lbl__MAX); |
| 50 | |
| 51 | |.actionlist lisp_actions; |
| 52 | dasm_setup (&d, lisp_actions); |
| 53 | |
| 54 | dasm_growpc (&d, npc); |
| 55 | } |
swissChili | b3ca4fb | 2021-04-20 10:33:00 -0700 | [diff] [blame^] | 56 | |
| 57 | void compile_expression (struct environment *env, struct local *local, |
| 58 | value_t val, dasm_State **Dst) |
| 59 | { |
| 60 | if ( integerp (val) || stringp (val) || symbolp (val) ) |
| 61 | { |
| 62 | | mov eax, val; |
| 63 | } |
| 64 | else if ( listp (val) ) |
| 65 | { |
| 66 | value_t func = car (val); |
| 67 | if ( !symbolp (func) ) |
| 68 | err ("function name must be a symbol"); |
| 69 | |
| 70 | struct function *func = find_function (env, func ^ SYMBOL_TAG); |
| 71 | value_t args = cdr (val); |
| 72 | int nargs = length (args); |
| 73 | |
| 74 | if ( nargs != func->nargs ) |
| 75 | err ("wrong number of args"); |
| 76 | |
| 77 | for ( int i = length (args) - 1; i >= 0; i++ ) |
| 78 | { |
| 79 | compile_expression (env, local, elt (args, i), Dst); |
| 80 | | push eax; |
| 81 | } |
| 82 | |
| 83 | | call (func->code_addr); |
| 84 | | add esp, (nargs * 4); |
| 85 | // result in eax |
| 86 | } |
| 87 | } |