X-Git-Url: https://git.lukelau.me/?p=scheme.git;a=blobdiff_plain;f=ast.scm;h=2beb94507572eafd20b586d2ce9ef3867ec63d3e;hp=a0899192e21a1d44b0fe3296e380604133a3f1d2;hb=9d93b066cfd6505849dff12146159bedeadf96b9;hpb=94d1c48d51bfe32aa1e14d4fb012b283ec9352ef diff --git a/ast.scm b/ast.scm index a089919..2beb945 100644 --- a/ast.scm +++ b/ast.scm @@ -34,6 +34,42 @@ ('if `(if ,@(map f (cdr x)))) (else x))) +(define (ast-collect f x) + (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)))] + ['app (append (f x) + (fold-map inner x))] + ['lambda (append (f x) + (inner (lambda-body x)))] + ['if (append (f x) + (fold-map inner (cdr x)))] + [else (f x)])) + +(define (ast-find p x) + (define (inner y) (ast-find p y)) + (define (any p x) (fold-left + (lambda (acc y) (if acc #t (p y))) + #f + x)) + (define (either . fs) + (if (null? fs) #f + (if (car fs) (car fs) + (apply either (cdr fs))))) + + (case (ast-type x) + ['let (either (p x) + (any inner (let-bindings x)) + (any inner (let-body x)))] + ['app (either (p x) + (any inner x))] + ['lambda (either (p x) + (inner (lambda-body x)))] + ['if (either (p x) (any inner (cdr x)))] + [else (p x)])) + (define let-bindings cadr) (define let-body cddr) @@ -45,3 +81,19 @@ ; for use elsewhere (define lambda-args cadr) (define lambda-body caddr) + +; utils +(define (fold-map f x) (fold-left append '() (map f x))) +(define (repeat x n) (if (<= n 0) '() + (cons x (repeat x (- n 1))))) + + +(define-syntax push! + (syntax-rules () + ((_ s x) (set! s (cons x s))))) + +(define-syntax pop! + (syntax-rules () + ((_ s) (let ([x (car s)]) + (set! s (cdr s)) + x))))