由于 SBCL 是 compiler-only implementation,这意味着所有代码都是自动编译的(与“解释”相反)。对宏的调用作为编译的一部分被扩展,因此某些东西是宏调用的事实就丢失了。
(defmacro m (n)
`(/ 10 ,n))
(defun foo (x) (m x))
SBCL:
* (foo 0)
debugger invoked on a DIVISION-BY-ZERO in thread
#<THREAD "main thread" RUNNING {1001E06493}>:
arithmetic error DIVISION-BY-ZERO signalled
Operation was /, operands (10 0).
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [ABORT] Exit debugger, returning to top level.
(SB-KERNEL::INTEGER-/-INTEGER 10 0)
0] backtrace
Backtrace for: #<SB-THREAD:THREAD "main thread" RUNNING {1001E06493}>
0: (SB-KERNEL::INTEGER-/-INTEGER 10 0)
1: (FOO 0)
2: (SB-INT:SIMPLE-EVAL-IN-LEXENV (FOO 0) #<NULL-LEXENV>)
3: (EVAL (FOO 0))
4: (INTERACTIVE-EVAL (FOO 0) :EVAL NIL)
[...]
一些实现,例如Allegro CL,支持解释代码和编译代码,第一个有助于调试,第二个提供更好的性能。 (我在这里展示了命令行交互。Allegro 还提供了一个 GUI 来设置我不熟悉的断点。)
cl-user(4): (foo 0)
Error: Attempt to divide 10 by zero.
[condition type: division-by-zero]
Restart actions (select using :continue):
0: Return to Top Level (an "abort" restart).
1: Abort entirely from this (lisp) process.
[1] cl-user(5): :zoom
Evaluation stack:
(error division-by-zero :operation ...)
->(/ 10 0)
(foo 0)
(eval (foo 0))
[...]
zoom command 有许多选项以更详细,这显示了(block foo (m x)) 的形式:
[1] cl-user(6): :zoom :all t
Evaluation stack:
... 4 more newer frames ...
((:runsys "lisp_apply"))
[... sys::funcall-tramp ]
(excl::error-from-code 17 nil ...)
(sys::..runtime-operation "integer_divide" :unknown-args)
(excl::/_2op 10 0)
->(/ 10 0)
[... excl::eval-as-progn ]
(block foo (m x))
(foo 0)
(sys::..runtime-operation "comp_to_interp" 0)
[... excl::%eval ]
(eval (foo 0))
当您(compile 'foo) 时,宏调用将被扩展(例如 SBCL)并且不再显示在回溯中(但 Allegro 的 source-level debugging 可以提供帮助)。
一般来说,在定义宏时,为了帮助调试,请尝试扩展为函数调用而不是大量代码。例如。而不是:
(defmacro with-foo ((var-x var-y thing) &body body)
`(let ((,var-x (..derive from ,thing ..))
(,var-y (..derive from ,thing ..)))
,@body))
我会这样写:
(defmacro with-foo ((var-x var-y thing) &body body)
`(call-with-foo (lambda (,var-x ,var-y) ,@body) ,thing))
(defun call-with-foo (func thing)
(let ((x (..derive from thing ..)
(y (..derive from thing ..))
(funcall func x y)))
所以它最终会出现在堆栈跟踪中并且很容易重新定义。
看到这个great post by Kent Pitman:
顺便说一句,回到 CL,你应该知道,当我写这些
WITH-xxx 宏,我几乎总是伴随着一个 CALL-WITH-xxx
这样我就可以拨打任何一种电话。但我发现我几乎从不使用
CALL-WITH-xxx 即使我是提供它作为选项的人。
我写它们的主要原因不是为了使用它们,而是为了制作
重新定义更容易,因为我可以重新定义 CALL-WITH-xxx 而无需
重新定义宏,所以我不必重新编译调用者如果
定义改变了。