- (let* ((heap-offsets (range 4 (length captured))) ; 4, 12, 20, etc.
- (inner-si (- si (* (length captured) wordsize))))
- (emit "movl $~a, (heap_start)")
- (emit "add $4, (heap_start)")
- (for-each (lambda (var-name new-offset)
- (emit "movq ~a(%rbp), ~a(heap_start)" ; todo: do we need to copy this?
- (cdr (assoc var-name env))
- new-offset)
- (emit "add $8, (heap_start)")
+ (let* ((heap-offsets (map (lambda (i) (+ 8 (* 8 i)))
+ (range 0 (length captured))))) ; 4, 12, 20, etc.
+
+ (emit "## creating closure")
+
+ (emit "movq heap_start@GOTPCREL(%rip), %rbx")
+
+ (emit "movq (%rbx), %rax") ; %rax = heap addr of closure
+
+
+ ; point heap_start to next space
+ (emit "addq $~a, (%rbx)" (+ 8 (* 8 (length captured))))
+
+ (emit "## storing address to lambda")
+ ; store the address to the lambda code
+ (emit "movq ~a@GOTPCREL(%rip), %rbx" label)
+ (emit "movq %rbx, 0(%rax)")
+
+ (emit "## storing captives")
+ ; store the captured vars
+ (for-each
+ (lambda (var-name new-offset)
+ (begin
+ (emit "movq ~a(%rbp), %rbx" (cdr (assoc var-name env)))
+ (emit "movq %rbx, ~a(%rax)" new-offset)))