+(define (codegen-case switch cases si env)
+ (define dls (env-data-layouts env))
+ (define exit-label (fresh-label))
+
+
+ ; checks if equal and returns assoc list of bindings
+ (define (check-equal jne-label type inner-offset x)
+
+ ; TODO: tidy this up! comparibles and binds could be merged
+ ; (foo a 2 (bar x)) -> ((2 Int 1) ((bar x) A 2))
+ ; sum: foo
+ (define (comparibles sum)
+ (let ([product-types (cdr (assoc sum (cdr (assoc type dls))))])
+ (if (null? product-types)
+ '()
+ (filter (lambda (x) (not (eqv? 'var (ast-type (car x)))))
+ (map (lambda (x t i) (list x t i))
+ (cdr x)
+ product-types
+ (range 0 (length product-types)))))))
+
+ (define (binds sum)
+ (let ([product-types (cdr (assoc sum (cdr (assoc type dls))))])
+ (if (null? product-types)
+ '()
+ (filter (lambda (x) (eqv? 'var (ast-type (car x))))
+ (map (lambda (x i)
+ (cons x
+ (- inner-offset
+ (data-product-offset dls type sum i))))
+ (cdr x)
+ (range 0 (length (cdr x))))))))
+
+
+ (let ([sums (assoc type dls)])
+ (if sums
+ (let* ([sum (if (list? x) (car x) x)] ; can sometimes be a singleton
+ [tag (data-sum-tag dls type sum)])
+ ; the tag is at the top (beginning) of the adt on the stack
+ (emit "cmpq $~a, ~a(%rbp)" tag inner-offset)
+ (emit "jne ~a" jne-label)
+
+ (append (binds sum)
+ (flat-map
+ (lambda (cmp) ; cmp = (x type index)
+ (check-equal jne-label
+ (cadr cmp)
+ (- inner-offset (data-product-offset dls type sum (caddr cmp)))
+ (car cmp)))
+ (comparibles sum))))
+ (if (eqv? 'var (ast-type x))
+ (list (cons x inner-offset))
+ (begin
+ (emit "cmpq $~a, ~a(%rbp)" x inner-offset)
+ (emit "jne ~a" jne-label)
+ '() )))))
+
+ (define (codegen-adt-match type case)
+ (let* ([match (car case)]
+ [expr (cadr case)]
+ [next-section-label (fresh-label)]
+ [inner-si (- si (type-size dls type))]
+ [new-env (env-append-bindings env
+ (check-equal next-section-label type si match))])
+
+
+ (codegen-expr expr inner-si new-env)
+ (emit "jmp ~a" exit-label)
+
+ (emit "~a:" next-section-label)))
+
+ (define (codegen-literal-match case)
+ (let ([next-section-label (fresh-label)])
+ (emit "cmpq $~a, %rax" (car case))
+ (emit "jne ~a" next-section-label)
+ (codegen-expr (cadr case) si env)
+ (emit "jmp ~a" exit-label)
+ (emit "~a:" next-section-label)))
+
+ ; generate the switch
+ ; (and store it on the stack if not a stack value)
+ (codegen-expr switch si env)
+
+ (if (eqv? 'stack (ast-type switch))
+ ; adt pattern match
+ (for-each (lambda (x) (codegen-adt-match (cadr switch) x)) cases)
+ (for-each codegen-literal-match cases))
+ (emit "~a:" exit-label))
+
+