字节编译宏时,"返回的值未使用"警告

Ric*_*sen 2 emacs elisp compiler-warnings emacs24

为什么字节编译以下会产生警告?

(defmacro foomacro (shiftcode)
  `(defun foo (&optional arg)
     (interactive ,(concat shiftcode "p"))
     (message "arg is %i" arg))
  `(defun bar (&optional arg)
     (interactive ,(concat shiftcode "Nenter a number: "))
     (message "arg is %i" arg)))
;; provide backward compatibility for Emacs 22
(if (fboundp 'handle-shift-selection)
    (foomacro "^")
  (foomacro ""))
Run Code Online (Sandbox Code Playgroud)

这是我收到的警告:

$ emacs -Q --batch --eval '(byte-compile-file "foo.el")'

In foomacro:
foo.el:1:21:Warning: value returned from (concat shiftcode "p") is unused
Run Code Online (Sandbox Code Playgroud)

如果我摆脱bar,警告就会消失:

(defmacro foomacro (shiftcode)
  `(defun foo (&optional arg)
     (interactive ,(concat shiftcode "p"))
     (message "arg is %i" arg)))
;; provide backward compatibility for Emacs 22
(if (fboundp 'handle-shift-selection)
    (foomacro "^")
  (foomacro ""))
Run Code Online (Sandbox Code Playgroud)

我正在使用GNU Emacs 24.2.1.

sds*_*sds 5

那是因为你忘了将宏体包裹在预测中:

(defmacro foomacro (shiftcode)
  `(progn
     (defun foo (&optional arg)
       (interactive ,(concat shiftcode "p"))
       (message "arg is %i" arg))
     (defun bar (&optional arg)
       (interactive ,(concat shiftcode "Nenter a number: "))
       (message "arg is %i" arg))))
Run Code Online (Sandbox Code Playgroud)

想想宏是如何工作的.当你调用时(foomacro "..."),lisp引擎识别出它foomacro是一个宏并扩展它,即在所提供的参数上调用它.正如预期的那样,宏的返回值是第二种 defun形式; 而第一种 defun形式被丢弃.然后lisp引擎评估返回值(这是第二种 defun形式).因此,在你的progn版本中,只bar定义了,而不是foo.

要理解这个过程,你需要意识到宏只是"代码转换"工具; 他们什么都没做.因此,编译器(或解释器)只能看到它们的返回值.