(import scheme (only fmt fmt) (chicken base) (chicken condition) (chicken irregex) (chicken module) (chicken plist) (chicken string) utils) (export cat comment macro? apply-macro defmacro macro-definition restore-macro!) (define (cat-syms s-1 s-2) (fmt #f s-1 s-2)) (define (cat sym-1 sym-2) (string->symbol (cat-syms sym-1 sym-2))) ;;; The reader keeps `;' comments as (comment "...") forms so they can ;;; be re-emitted into the generated C. In a macro body a comment ;;; should be a call which does nothing, hence this one (define (comment . _) (void)) (define (register-macro name arglist body) (put! name 'sex-macro `(lambda ,arglist ;; A macro body is ordinary Scheme, evaluated at compile ;; time. It gets `cat' for building names, and read access to ;; the type database (import scheme (scheme base) ;; a type is a list, so a macro reading one wants ;; `(third type)' rather than `(caddr type)' (only srfi-1 first second third fourth fifth last) (only sex-macros cat comment) (only types get-type-info get-tag-info get-fields get-underlying-type type-match type-pattern-matches? map-fields get-name-type get-return-type type-of get-method)) ,@body))) (define (get-macro name) (eval (get name 'sex-macro))) (define (macro? form) (and (list? form) (symbol? (car form)) (get (car form) 'sex-macro))) ;;; CHICKEN would report a wrong argument count about a procedure with ;;; no name, and an error raised in a macro's body without the call: both ;;; are told here, where the call is known (define (apply-macro form) (assert (macro? form) (fmt #f (car form) " is not a macro")) (let ((name (car form))) (check-macro-arity form name (cadr (get name 'sex-macro)) (length (cdr form))) (handle-exceptions e (let ((message ((condition-property-accessor 'exn 'message #f) e))) ;; one raised about a form of its own already says where (if (and message (not (irregex-search "^[^ ]+:[0-9]+: " message))) (apply sex-error form (string-append "expanding " (symbol->string name) ": " message) ((condition-property-accessor 'exn 'arguments (list)) e)) (abort e))) (apply (get-macro name) (cdr form))))) ;;; (defmacro (one x) ...) takes one; (defmacro (many x . more) ...) one ;;; or more (define (check-macro-arity form name arglist given) (let count ((args arglist) (required 0)) (cond ((pair? args) (count (cdr args) (+ required 1))) ((null? args) (unless (= given required) (sex-error form "macro takes this many arguments" name required))) ((< given required) (sex-error form "macro takes at least this many arguments" name required))))) ;;; What a name is defined as a macro to, or #f; and putting that back, ;;; for a macro lent for a while -- a module's, while its interface is ;;; read (define (macro-definition name) (get name 'sex-macro)) (define (restore-macro! name definition) (if definition (put! name 'sex-macro definition) (remprop! name 'sex-macro))) (define (defmacro form) (let ((arglist (car form)) (body (cdr form))) (register-macro (car arglist) (cdr arglist) body)))