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