whitten

Lisp Macro implementation

Jul 17th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.16 KB | None | 0 0
  1. ;;from https://gist.github.com/jlongster (James Long)
  2. ;; outlet code for implementing traditional macro expansion
  3.  
  4. ;; macros
  5.  
  6. (define (expand form)
  7.   (cond
  8.    ((variable? form) form)
  9.    ((literal? form) form)
  10.    ((macro? (car form))
  11.     (expand ((macro-function (car form)) form)))
  12.    ((eq? (car form) 'quote)
  13.     form)
  14.    ((eq? (car form) 'lambda)
  15.     `(lambda ,(car (cdr form))
  16.        ,@(map expand (cdr (cdr form)))))  
  17.    (else (map expand form))))
  18.  
  19. (define _macros_ {})
  20.  
  21. (define (macro-function name)
  22.   (ref _macros_ (symbol->string name)))
  23.  
  24. (define (install-macro name func)
  25.   (put! _macros_ (symbol->string name) func))
  26.  
  27. (define (macro? name)
  28.   (not (eq? (ref _macros_ (symbol->string name))
  29.             undefined)))
  30.  
  31. ;; compiler
  32.  
  33. (define (read src)
  34.   (vector-to-list
  35.    (reader grammar src '[begin])))
  36.  
  37. (install-macro 'define (lambda (form)
  38.                          `(define* ,(car (cdr form))
  39.                             ,@(cdr (cdr form)))))
  40.  
  41. (let ((src (fs.readFileSync "example.ol" "utf-8")))
  42.   (pretty (expand (read src))))
  43.  
  44. ;; (define (foo x y z)
  45. ;;   (+ x y z))
  46. ;;
  47. ;; expand to:
  48. ;;
  49. ;; (define* (foo x y z)
  50. ;;   (+ x y z))
Advertisement