|
3 | 3 |
|
4 | 4 | ;; type CEnv = [Listof Variable] |
5 | 5 |
|
| 6 | +(define imm-shift 1) |
| 7 | +(define imm-type-mask (sub1 (arithmetic-shift 1 imm-shift))) |
| 8 | +(define imm-type-int #b0) |
| 9 | +(define imm-type-true #b11) |
| 10 | +(define imm-type-false #b01) |
| 11 | + |
6 | 12 | ;; Expr -> Asm |
7 | 13 | (define (compile e) |
8 | 14 | `(entry |
|
18 | 24 | (match e |
19 | 25 | [(? integer? i) (compile-integer i)] |
20 | 26 | [(? boolean? b) (compile-boolean b)] |
21 | | - [(? symbol? x) (compile-variable x c)] |
| 27 | + [(? symbol? x) (compile-variable x c)] |
22 | 28 | [`(add1 ,e0) (compile-add1 e0 c)] |
23 | 29 | [`(sub1 ,e0) (compile-sub1 e0 c)] |
24 | 30 | [`(zero? ,e0) (compile-zero? e0 c)] |
|
27 | 33 |
|
28 | 34 | ;; Integer -> Asm |
29 | 35 | (define (compile-integer i) |
30 | | - `((mov rax ,(* i 2)))) |
| 36 | + `((mov rax ,(arithmetic-shift i imm-shift)))) |
31 | 37 |
|
32 | 38 | ;; Boolean -> Asm |
33 | 39 | (define (compile-boolean b) |
34 | | - `((mov rax ,(if b #b11 #b01)))) |
| 40 | + `((mov rax ,(if b imm-type-true imm-type-false)))) |
35 | 41 |
|
36 | 42 | ;; Expr CEnv -> Asm |
37 | 43 | (define (compile-add1 e0 c) |
38 | 44 | (let ((c0 (compile-e e0 c))) |
39 | 45 | `(,@c0 |
40 | 46 | ,@assert-integer |
41 | | - (add rax 2)))) |
| 47 | + (add rax ,(arithmetic-shift 1 imm-shift))))) |
42 | 48 |
|
43 | 49 | ;; Expr CEnv -> Asm |
44 | 50 | (define (compile-sub1 e0 c) |
45 | 51 | (let ((c0 (compile-e e0 c))) |
46 | 52 | `(,@c0 |
47 | 53 | ,@assert-integer |
48 | | - (sub rax 2)))) |
| 54 | + (sub rax ,(arithmetic-shift 1 imm-shift))))) |
49 | 55 |
|
50 | 56 | ;; Expr CEnv -> Asm |
51 | 57 | (define (compile-zero? e0 c) |
|
55 | 61 | `(,@c0 |
56 | 62 | ,@assert-integer |
57 | 63 | (cmp rax 0) |
58 | | - (mov rax #b01) ; #f |
| 64 | + (mov rax ,imm-type-false) |
59 | 65 | (jne ,l0) |
60 | | - (mov rax #b11) ; #t |
| 66 | + (mov rax ,imm-type-true) |
61 | 67 | ,l0))) |
62 | 68 |
|
63 | 69 | ;; Expr Expr Expr CEnv -> Asm |
|
68 | 74 | (l0 (gensym)) |
69 | 75 | (l1 (gensym))) |
70 | 76 | `(,@c0 |
71 | | - (cmp rax #b01) ; compare to #f |
| 77 | + (cmp rax ,imm-type-false) |
72 | 78 | (je ,l0) ; jump to c2 if #f |
73 | 79 | ,@c1 |
74 | 80 | (jmp ,l1) ; jump past c2 |
|
94 | 100 | (match cenv |
95 | 101 | ['() (error "undefined variable:" x)] |
96 | 102 | [(cons y cenv) |
97 | | - (match (symbol=? x y) |
| 103 | + (match (eq? x y) |
98 | 104 | [#t (length cenv)] |
99 | 105 | [#f (lookup x cenv)])])) |
100 | 106 |
|
101 | 107 | (define assert-integer |
102 | 108 | `((mov rbx rax) |
103 | | - (and rbx 1) |
104 | | - (cmp rbx 0) |
| 109 | + (and rbx ,imm-type-mask) |
| 110 | + (cmp rbx ,imm-type-int) |
105 | 111 | (jne err))) |
0 commit comments