Can macro expansion contain (declare …) expression

2019-06-21 13:14发布

The Common Lisp Hyperspec states "Macro forms cannot expand into declarations; declare expressions must appear as actual subexpressions of the form to which they refer."

I'm confused on the meaning of "expand into". A macro such as the following won't work for obvious reasons:

(defmacro optimize-fully ()
    `(declare (optimize (speed 3) (safety 0))))

But what if the macro expansion merely contains a (declare ...) expression?

(defmacro defun-optimized (name (&rest lambda-list) &rest body)
    `(defun ,name ,lambda-list
        (declare (optimize (speed 3) (safety 0)))
        ,@body))

(defun-optimized foobar (a b)
    (* a b))

Is this a violation of the spec? The CL implementation I use, SBCL, does not complain, and in fact, the macro above seems to work precisely as expected. What gives?

1条回答
我命由我不由天
2楼-- · 2019-06-21 13:44

Your first example is exactly what it's prohibiting. You couldn't have code like that combined with something like this:

(defun optimized (a b)
  (optimize-fully)
  (+ a b))

I sometimes see code like this, though:

(defvar *optimization-settings* '(optimize (speed 3) (safety 0)))

(defun foo (a b)
  (declare #.*optimization-settings*)
  ...)
查看更多
登录 后发表回答