January, 2006 Archives
Macro Expansion Hook for Gauche
By Arto on Thu, 2006-01-12 19:26. Gauche | Lisp | macros | Scheme | snippetsInspired by Common Lisp’s macroexpand-hook, here’s a pretty useful snippet I recently hacked together to assist me in debugging Scheme macros for Gauche :
(define-macro (define-macroexpand-hook hook)
`((with-module gauche define-macro) (define-macro formals . body)
(cond
((list? formals)
`(define-macro ,(car formals)
(lambda (,@(cdr formals)) ,@body)))
((symbol? formals)
`((with-module gauche define-macro) ,formals
(lambda args (apply ,',hook ,@body ',formals args))))
(else
(error "symbol required, but got" formals)))))
define-macroexpand-hook is a straightforward (well, not too hairy, anyway) macro-generating macro that overwrites the binding of the define-macro special form in the current module, with the result that any macros subsequently defined will include a call to a user-defined procedure (passed as the argument to define-macroexpand-hook), which will be invoked whenever the macro is applied.
(The immense power inherent in this brief code snippet will not, sadly, be something most programmers unfamiliar with Lisp can appreciate. What this is doing is essentially dynamically injecting additional code into the Scheme compiler itself — it’s not every language that lets you patch the compiler on the fly, while running.)
