X-Git-Url: https://git.lukelau.me/?p=scheme.git;a=blobdiff_plain;f=ast.scm;h=1a4afe21f3258d829c4f305ea78fd2f804cca2ad;hp=2beb94507572eafd20b586d2ce9ef3867ec63d3e;hb=25ef5a684dec5eedfc4e34a12b00a04e2d6b2b1b;hpb=8b8c603a6106151188bdeab95501cacaf72912d4 diff --git a/ast.scm b/ast.scm index 2beb945..1a4afe2 100644 --- a/ast.scm +++ b/ast.scm @@ -38,14 +38,14 @@ (define (inner y) (ast-collect f y)) (case (ast-type x) ['let (append (f x) - (fold-map inner (let-bindings x)) - (fold-map inner (let-body x)))] + (flat-map inner (let-bindings x)) + (flat-map inner (let-body x)))] ['app (append (f x) - (fold-map inner x))] + (flat-map inner x))] ['lambda (append (f x) (inner (lambda-body x)))] ['if (append (f x) - (fold-map inner (cdr x)))] + (flat-map inner (cdr x)))] [else (f x)])) (define (ast-find p x) @@ -70,12 +70,44 @@ ['if (either (p x) (any inner (cdr x)))] [else (p x)])) -(define let-bindings cadr) +(define (let-bindings e) + (define (pattern-match x body) + (if (eqv? (ast-type x) 'var) + (cons x body) + (let* ([constructor (car x)] + [destructor (lambda (i) `(destruct ,i ,constructor))]) + (flat-map (lambda (y i) + (pattern-match y (list (destructor i) body))) + (cdr x) + (range 0 (length (cdr x))))))) + (flat-map (lambda (x) (pattern-match (car x) (cdr x))) (cadr e))) (define let-body cddr) (define (lambda? x) (and (list? x) (eq? (car x) 'lambda))) + +(define (statement-type x) + (cond + [(and (list? x) + (eqv? (car x) 'data)) 'data] + [(and (list? x) + (eqv? (car x) 'define)) 'define] + [else 'expr])) + +(define (program-datas program) + (filter (lambda (x) (eqv? (statement-type x) 'data)) + program)) + +(define (program-defines program) + (filter (lambda (x) (eqv? (statement-type x) 'defines)) + program)) + +(define (program-body program) + `(let () + ,@(filter (lambda (x) (eqv? (statement-type x) 'expr)) + program))) + ; for use in normalized form (define lambda-arg caadr) ; for use elsewhere @@ -83,7 +115,12 @@ (define lambda-body caddr) ; utils -(define (fold-map f x) (fold-left append '() (map f x))) +(define (range s n) + (if (= 0 n) '() + (append (range s (- n 1)) + (list (+ s (- n 1)))))) + +(define (flat-map f . xs) (fold-left append '() (apply map (cons f xs)))) (define (repeat x n) (if (<= n 0) '() (cons x (repeat x (- n 1)))))