Merge from emacs-24; up to 2012-12-25T17:37:29Z!eliz@gnu.org
[bpt/emacs.git] / lisp / emacs-lisp / macroexp.el
CommitLineData
513749ee 1;;; macroexp.el --- Additional macro-expansion support -*- lexical-binding: t; coding: utf-8 -*-
4d449b11 2;;
ab422c4d 3;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
4d449b11
MB
4;;
5;; Author: Miles Bader <miles@gnu.org>
6;; Keywords: lisp, compiler, macros
7
8;; This file is part of GNU Emacs.
9
d6cba7ae 10;; GNU Emacs is free software: you can redistribute it and/or modify
4d449b11 11;; it under the terms of the GNU General Public License as published by
d6cba7ae
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
4d449b11
MB
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
d6cba7ae 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
4d449b11
MB
22
23;;; Commentary:
24;;
25;; This file contains macro-expansions functions that are not defined in
26;; the Lisp core, namely `macroexpand-all', which expands all macros in
27;; a form, not just a top-level one.
28;;
29
30;;; Code:
31
32;; Bound by the top-level `macroexpand-all', and modified to include any
33;; macros defined by `defmacro'.
34(defvar macroexpand-all-environment nil)
35
fa779ab0 36(defun macroexp--cons (car cdr original-cons)
4d449b11
MB
37 "Return (CAR . CDR), using ORIGINAL-CONS if possible."
38 (if (and (eq car (car original-cons)) (eq cdr (cdr original-cons)))
39 original-cons
40 (cons car cdr)))
41
42;; We use this special macro to iteratively process forms and share list
43;; structure of the result with the input. Doing so recursively using
fa779ab0 44;; `macroexp--cons' results in excessively deep recursion for very long
4d449b11 45;; input forms.
fa779ab0 46(defmacro macroexp--accumulate (var+list &rest body)
4d449b11
MB
47 "Return a list of the results of evaluating BODY for each element of LIST.
48Evaluate BODY with VAR bound to each `car' from LIST, in turn.
49Return a list of the values of the final form in BODY.
50The list structure of the result will share as much with LIST as
51possible (for instance, when BODY just returns VAR unchanged, the
5de35ba4
RS
52result will be eq to LIST).
53
54\(fn (VAR LIST) BODY...)"
6fe79b7c 55 (declare (indent 1))
5de35ba4
RS
56 (let ((var (car var+list))
57 (list (cadr var+list))
4d449b11
MB
58 (shared (make-symbol "shared"))
59 (unshared (make-symbol "unshared"))
60 (tail (make-symbol "tail"))
61 (new-el (make-symbol "new-el")))
62 `(let* ((,shared ,list)
63 (,unshared nil)
64 (,tail ,shared)
65 ,var ,new-el)
61b108cc 66 (while (consp ,tail)
4d449b11
MB
67 (setq ,var (car ,tail)
68 ,new-el (progn ,@body))
69 (unless (eq ,var ,new-el)
70 (while (not (eq ,shared ,tail))
71 (push (pop ,shared) ,unshared))
72 (setq ,shared (cdr ,shared))
73 (push ,new-el ,unshared))
74 (setq ,tail (cdr ,tail)))
75 (nconc (nreverse ,unshared) ,shared))))
4d449b11 76
fa779ab0 77(defun macroexp--all-forms (forms &optional skip)
4d449b11
MB
78 "Return FORMS with macros expanded. FORMS is a list of forms.
79If SKIP is non-nil, then don't expand that many elements at the start of
80FORMS."
fa779ab0 81 (macroexp--accumulate (form forms)
4d449b11 82 (if (or (null skip) (zerop skip))
fa779ab0 83 (macroexp--expand-all form)
4d449b11
MB
84 (setq skip (1- skip))
85 form)))
86
fa779ab0 87(defun macroexp--all-clauses (clauses &optional skip)
4d449b11
MB
88 "Return CLAUSES with macros expanded.
89CLAUSES is a list of lists of forms; any clause that's not a list is ignored.
90If SKIP is non-nil, then don't expand that many elements at the start of
91each clause."
fa779ab0 92 (macroexp--accumulate (clause clauses)
4d449b11 93 (if (listp clause)
fa779ab0 94 (macroexp--all-forms clause skip)
4d449b11
MB
95 clause)))
96
f38ea36d
SM
97(defun macroexp--compiler-macro (handler form)
98 (condition-case err
99 (apply handler form (cdr form))
100 (error (message "Compiler-macro error for %S: %S" (car form) err)
a64a94ed 101 form)))
f38ea36d 102
ce97595b 103(defun macroexp--funcall-if-compiled (_form)
972debf2
SM
104 "Pseudo function used internally by macroexp to delay warnings.
105The purpose is to delay warnings to bytecomp.el, so they can use things
106like `byte-compile-log-warning' to get better file-and-line-number data
107and also to avoid outputting the warning during normal execution."
108 nil)
ce97595b 109(put 'macroexp--funcall-if-compiled 'byte-compile
972debf2 110 (lambda (form)
ce97595b 111 (funcall (eval (cadr form)))
972debf2
SM
112 (byte-compile-constant nil)))
113
95b9712e
SM
114(defun macroexp--warn-and-return (msg form)
115 (let ((when-compiled (lambda () (byte-compile-log-warning msg t))))
116 (cond
117 ((null msg) form)
118 ;; FIXME: ¡¡Major Ugly Hack!! To determine whether the output of this
119 ;; macro-expansion will be processed by the byte-compiler, we check
120 ;; circumstantial evidence.
121 ((member '(declare-function . byte-compile-macroexpand-declare-function)
122 macroexpand-all-environment)
ce97595b
SM
123 `(progn
124 (macroexp--funcall-if-compiled ',when-compiled)
95b9712e
SM
125 ,form))
126 (t
a5f74442
GM
127 (message "%s%s" (if (stringp load-file-name)
128 (concat (file-relative-name load-file-name) ": ")
129 "")
130 msg)
95b9712e
SM
131 form))))
132
133(defun macroexp--obsolete-warning (fun obsolescence-data type)
134 (let ((instead (car obsolescence-data))
135 (asof (nth 2 obsolescence-data)))
136 (format "`%s' is an obsolete %s%s%s" fun type
137 (if asof (concat " (as of " asof ")") "")
138 (cond ((stringp instead) (concat "; " instead))
139 (instead (format "; use `%s' instead." instead))
140 (t ".")))))
35f5b19d 141
fa779ab0 142(defun macroexp--expand-all (form)
4d449b11
MB
143 "Expand all macros in FORM.
144This is an internal version of `macroexpand-all'.
145Assumes the caller has bound `macroexpand-all-environment'."
146 (if (and (listp form) (eq (car form) 'backquote-list*))
147 ;; Special-case `backquote-list*', as it is normally a macro that
148 ;; generates exceedingly deep expansions from relatively shallow input
149 ;; forms. We just process it `in reverse' -- first we expand all the
150 ;; arguments, _then_ we expand the top-level definition.
fa779ab0 151 (macroexpand (macroexp--all-forms form 1)
4d449b11
MB
152 macroexpand-all-environment)
153 ;; Normal form; get its expansion, and then expand arguments.
972debf2
SM
154 (let ((new-form
155 (macroexpand form macroexpand-all-environment)))
156 (setq form
157 (if (and (not (eq form new-form)) ;It was a macro call.
158 (car-safe form)
159 (symbolp (car form))
63314e57
SM
160 (get (car form) 'byte-obsolete-info)
161 (or (not (fboundp 'byte-compile-warning-enabled-p))
162 (byte-compile-warning-enabled-p 'obsolete)))
95b9712e
SM
163 (let* ((fun (car form))
164 (obsolete (get fun 'byte-obsolete-info)))
165 (macroexp--warn-and-return
63314e57
SM
166 (macroexp--obsolete-warning
167 fun obsolete
168 (if (symbolp (symbol-function fun))
169 "alias" "macro"))
95b9712e 170 new-form))
972debf2 171 new-form)))
6fe79b7c
SM
172 (pcase form
173 (`(cond . ,clauses)
fa779ab0 174 (macroexp--cons 'cond (macroexp--all-clauses clauses) form))
6fe79b7c 175 (`(condition-case . ,(or `(,err ,body . ,handlers) dontcare))
fa779ab0 176 (macroexp--cons
6fe79b7c 177 'condition-case
fa779ab0
SM
178 (macroexp--cons err
179 (macroexp--cons (macroexp--expand-all body)
180 (macroexp--all-clauses handlers 1)
6fe79b7c
SM
181 (cddr form))
182 (cdr form))
183 form))
fa779ab0 184 (`(,(or `defvar `defconst) . ,_) (macroexp--all-forms form 2))
6fe79b7c 185 (`(function ,(and f `(lambda . ,_)))
fa779ab0
SM
186 (macroexp--cons 'function
187 (macroexp--cons (macroexp--all-forms f 2)
6fe79b7c
SM
188 nil
189 (cdr form))
190 form))
191 (`(,(or `function `quote) . ,_) form)
192 (`(,(and fun (or `let `let*)) . ,(or `(,bindings . ,body) dontcare))
fa779ab0
SM
193 (macroexp--cons fun
194 (macroexp--cons (macroexp--all-clauses bindings 1)
195 (macroexp--all-forms body)
6fe79b7c
SM
196 (cdr form))
197 form))
198 (`(,(and fun `(lambda . ,_)) . ,args)
199 ;; Embedded lambda in function position.
fa779ab0
SM
200 (macroexp--cons (macroexp--all-forms fun 2)
201 (macroexp--all-forms args)
6fe79b7c
SM
202 form))
203 ;; The following few cases are for normal function calls that
204 ;; are known to funcall one of their arguments. The byte
205 ;; compiler has traditionally handled these functions specially
206 ;; by treating a lambda expression quoted by `quote' as if it
207 ;; were quoted by `function'. We make the same transformation
208 ;; here, so that any code that cares about the difference will
209 ;; see the same transformation.
210 ;; First arg is a function:
9c848d8a 211 (`(,(and fun (or `funcall `apply `mapcar `mapatoms `mapconcat `mapc))
876c194c 212 ',(and f `(lambda . ,_)) . ,args)
ce97595b 213 (macroexp--warn-and-return
9c848d8a
SM
214 (format "%s quoted with ' rather than with #'"
215 (list 'lambda (nth 1 f) '...))
ce97595b 216 (macroexp--expand-all `(,fun ,f . ,args))))
6fe79b7c 217 ;; Second arg is a function:
876c194c 218 (`(,(and fun (or `sort)) ,arg1 ',(and f `(lambda . ,_)) . ,args)
ce97595b 219 (macroexp--warn-and-return
9c848d8a
SM
220 (format "%s quoted with ' rather than with #'"
221 (list 'lambda (nth 1 f) '...))
ce97595b 222 (macroexp--expand-all `(,fun ,arg1 ,f . ,args))))
57a7d507
SM
223 (`(,func . ,_)
224 ;; Macro expand compiler macros. This cannot be delayed to
225 ;; byte-optimize-form because the output of the compiler-macro can
226 ;; use macros.
7abaf5cc 227 (let ((handler (function-get func 'compiler-macro)))
57a7d507
SM
228 (if (null handler)
229 ;; No compiler macro. We just expand each argument (for
230 ;; setq/setq-default this works alright because the variable names
231 ;; are symbols).
fa779ab0 232 (macroexp--all-forms form 1)
d9857e53
SM
233 ;; If the handler is not loaded yet, try (auto)loading the
234 ;; function itself, which may in turn load the handler.
7abaf5cc 235 (unless (functionp handler)
d9857e53 236 (ignore-errors
7abaf5cc 237 (autoload-do-load (indirect-function func) func)))
f38ea36d 238 (let ((newform (macroexp--compiler-macro handler form)))
57a7d507
SM
239 (if (eq form newform)
240 ;; The compiler macro did not find anything to do.
fa779ab0 241 (if (equal form (setq newform (macroexp--all-forms form 1)))
57a7d507
SM
242 form
243 ;; Maybe after processing the args, some new opportunities
244 ;; appeared, so let's try the compiler macro again.
f38ea36d 245 (setq form (macroexp--compiler-macro handler newform))
53aacf21 246 (if (eq newform form)
57a7d507 247 newform
fa779ab0
SM
248 (macroexp--expand-all newform)))
249 (macroexp--expand-all newform))))))
57a7d507 250
6fe79b7c 251 (t form))))
4d449b11
MB
252
253;;;###autoload
254(defun macroexpand-all (form &optional environment)
255 "Return result of expanding macros at all levels in FORM.
256If no macros are expanded, FORM is returned unchanged.
257The second optional arg ENVIRONMENT specifies an environment of macro
258definitions to shadow the loaded ones for use in file byte-compilation."
259 (let ((macroexpand-all-environment environment))
fa779ab0 260 (macroexp--expand-all form)))
4d449b11 261
4dd1c416
SM
262;;; Handy functions to use in macros.
263
264(defun macroexp-progn (exps)
265 "Return an expression equivalent to `(progn ,@EXPS)."
266 (if (cdr exps) `(progn ,@exps) (car exps)))
267
de7e2b36
SM
268(defun macroexp-unprogn (exp)
269 "Turn EXP into a list of expressions to execute in sequence."
270 (if (eq (car-safe exp) 'progn) (cdr exp) (list exp)))
271
4dd1c416
SM
272(defun macroexp-let* (bindings exp)
273 "Return an expression equivalent to `(let* ,bindings ,exp)."
274 (cond
275 ((null bindings) exp)
276 ((eq 'let* (car-safe exp)) `(let* (,@bindings ,@(cadr exp)) ,@(cddr exp)))
277 (t `(let* ,bindings ,exp))))
278
279(defun macroexp-if (test then else)
280 "Return an expression equivalent to `(if ,test ,then ,else)."
281 (cond
282 ((eq (car-safe else) 'if)
283 (if (equal test (nth 1 else))
284 ;; Doing a test a second time: get rid of the redundancy.
285 `(if ,test ,then ,@(nthcdr 3 else))
286 `(cond (,test ,then)
287 (,(nth 1 else) ,(nth 2 else))
288 (t ,@(nthcdr 3 else)))))
289 ((eq (car-safe else) 'cond)
290 `(cond (,test ,then)
291 ;; Doing a test a second time: get rid of the redundancy, as above.
292 ,@(remove (assoc test else) (cdr else))))
293 ;; Invert the test if that lets us reduce the depth of the tree.
294 ((memq (car-safe then) '(if cond)) (macroexp-if `(not ,test) else then))
295 (t `(if ,test ,then ,else))))
296
2ee3d7f0 297(defmacro macroexp-let2 (test var exp &rest exps)
4dd1c416
SM
298 "Bind VAR to a copyable expression that returns the value of EXP.
299This is like `(let ((v ,EXP)) ,EXPS) except that `v' is a new generated
300symbol which EXPS can find in VAR.
301TEST should be the name of a predicate on EXP checking whether the `let' can
302be skipped; if nil, as is usual, `macroexp-const-p' is used."
dc5d230c 303 (declare (indent 3) (debug (sexp sexp form body)))
4dd1c416
SM
304 (let ((bodysym (make-symbol "body"))
305 (expsym (make-symbol "exp")))
306 `(let* ((,expsym ,exp)
dc5d230c 307 (,var (if (funcall #',(or test #'macroexp-const-p) ,expsym)
f5695c9a 308 ,expsym (make-symbol ,(symbol-name var))))
4dd1c416
SM
309 (,bodysym ,(macroexp-progn exps)))
310 (if (eq ,var ,expsym) ,bodysym
311 (macroexp-let* (list (list ,var ,expsym))
312 ,bodysym)))))
313
2ee3d7f0
SM
314(defun macroexp--maxsize (exp size)
315 (cond ((< size 0) size)
316 ((symbolp exp) (1- size))
317 ((stringp exp) (- size (/ (length exp) 16)))
318 ((vectorp exp)
319 (dotimes (i (length exp))
320 (setq size (macroexp--maxsize (aref exp i) size)))
321 (1- size))
322 ((consp exp)
323 ;; We could try to be more clever with quote&function,
324 ;; but it is difficult to do so correctly, and it's not obvious that
325 ;; it would be worth the effort.
326 (dolist (e exp)
327 (setq size (macroexp--maxsize e size)))
328 (1- size))
329 (t -1)))
330
331(defun macroexp-small-p (exp)
332 "Return non-nil if EXP can be considered small."
333 (> (macroexp--maxsize exp 10) 0))
334
4dd1c416
SM
335(defsubst macroexp--const-symbol-p (symbol &optional any-value)
336 "Non-nil if SYMBOL is constant.
337If ANY-VALUE is nil, only return non-nil if the value of the symbol is the
338symbol itself."
339 (or (memq symbol '(nil t))
340 (keywordp symbol)
341 (if any-value
342 (or (memq symbol byte-compile-const-variables)
343 ;; FIXME: We should provide a less intrusive way to find out
344 ;; if a variable is "constant".
345 (and (boundp symbol)
346 (condition-case nil
347 (progn (set symbol (symbol-value symbol)) nil)
348 (setting-constant t)))))))
349
350(defun macroexp-const-p (exp)
351 "Return non-nil if EXP will always evaluate to the same value."
352 (cond ((consp exp) (or (eq (car exp) 'quote)
353 (and (eq (car exp) 'function)
354 (symbolp (cadr exp)))))
355 ;; It would sometimes make sense to pass `any-value', but it's not
356 ;; always safe since a "constant" variable may not actually always have
357 ;; the same value.
358 ((symbolp exp) (macroexp--const-symbol-p exp))
359 (t t)))
360
361(defun macroexp-copyable-p (exp)
362 "Return non-nil if EXP can be copied without extra cost."
363 (or (symbolp exp) (macroexp-const-p exp)))
364
972debf2
SM
365;;; Load-time macro-expansion.
366
367;; Because macro-expansion used to be more lazy, eager macro-expansion
368;; tends to bump into previously harmless/unnoticeable cyclic-dependencies.
369;; So, we have to delay macro-expansion like we used to when we detect
370;; such a cycle, and we also want to help coders resolve those cycles (since
371;; they can be non-obvious) by providing a usefully trimmed backtrace
372;; (hopefully) highlighting the problem.
373
374(defun macroexp--backtrace ()
375 "Return the Elisp backtrace, more recent frames first."
376 (let ((bt ())
377 (i 0))
378 (while
379 (let ((frame (backtrace-frame i)))
380 (when frame
381 (push frame bt)
382 (setq i (1+ i)))))
383 (nreverse bt)))
384
385(defun macroexp--trim-backtrace-frame (frame)
386 (pcase frame
387 (`(,_ macroexpand (,head . ,_) . ,_) `(macroexpand (,head …)))
388 (`(,_ internal-macroexpand-for-load (,head ,second . ,_) . ,_)
389 (if (or (symbolp second)
390 (and (eq 'quote (car-safe second))
391 (symbolp (cadr second))))
392 `(macroexpand-all (,head ,second …))
393 '(macroexpand-all …)))
394 (`(,_ load-with-code-conversion ,name . ,_)
395 `(load ,(file-name-nondirectory name)))))
396
397(defvar macroexp--pending-eager-loads nil
398 "Stack of files currently undergoing eager macro-expansion.")
399
400(defun internal-macroexpand-for-load (form)
401 ;; Called from the eager-macroexpansion in readevalloop.
402 (cond
403 ;; Don't repeat the same warning for every top-level element.
404 ((eq 'skip (car macroexp--pending-eager-loads)) form)
405 ;; If we detect a cycle, skip macro-expansion for now, and output a warning
406 ;; with a trimmed backtrace.
407 ((and load-file-name (member load-file-name macroexp--pending-eager-loads))
408 (let* ((bt (delq nil
409 (mapcar #'macroexp--trim-backtrace-frame
410 (macroexp--backtrace))))
411 (elem `(load ,(file-name-nondirectory load-file-name)))
412 (tail (member elem (cdr (member elem bt)))))
413 (if tail (setcdr tail (list '…)))
414 (if (eq (car-safe (car bt)) 'macroexpand-all) (setq bt (cdr bt)))
415 (message "Warning: Eager macro-expansion skipped due to cycle:\n %s"
416 (mapconcat #'prin1-to-string (nreverse bt) " => "))
417 (push 'skip macroexp--pending-eager-loads)
418 form))
419 (t
420 (condition-case err
421 (let ((macroexp--pending-eager-loads
422 (cons load-file-name macroexp--pending-eager-loads)))
423 (macroexpand-all form))
424 (error
425 ;; Hopefully this shouldn't happen thanks to the cycle detection,
426 ;; but in case it does happen, let's catch the error and give the
427 ;; code a chance to macro-expand later.
428 (message "Eager macro-expansion failure: %S" err)
429 form)))))
430
431;; ¡¡¡ Big Ugly Hack !!!
432;; src/bootstrap-emacs is mostly used to compile .el files, so it needs
433;; macroexp, bytecomp, cconv, and byte-opt to be fast. Generally this is done
434;; by compiling those files first, but this only makes a difference if those
435;; files are not preloaded. But macroexp.el is preloaded so we reload it if
436;; the current version is interpreted and there's a compiled version available.
437(eval-when-compile
438 (add-hook 'emacs-startup-hook
439 (lambda ()
440 (and (not (byte-code-function-p
441 (symbol-function 'macroexpand-all)))
442 (locate-library "macroexp.elc")
443 (load "macroexp.elc")))))
444
4d449b11
MB
445(provide 'macroexp)
446
4d449b11 447;;; macroexp.el ends here