Merge from origin/emacs-24
[emacs.git] / lisp / emacs-lisp / macroexp.el
blob68bf4f62c3430c1beb3e879423eade1323389b22
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-parse-body (body)
301 "Parse a function BODY into (DECLARATIONS . EXPS)."
302 (let ((decls ()))
303 (while (and (cdr body)
304 (let ((e (car body)))
305 (or (stringp e)
306 (memq (car-safe e)
307 '(:documentation declare interactive cl-declare)))))
308 (push (pop body) decls))
309 (cons (nreverse decls) body)))
311 (defun macroexp-progn (exps)
312 "Return an expression equivalent to `(progn ,@EXPS)."
313 (if (cdr exps) `(progn ,@exps) (car exps)))
315 (defun macroexp-unprogn (exp)
316 "Turn EXP into a list of expressions to execute in sequence."
317 (if (eq (car-safe exp) 'progn) (cdr exp) (list exp)))
319 (defun macroexp-let* (bindings exp)
320 "Return an expression equivalent to `(let* ,bindings ,exp)."
321 (cond
322 ((null bindings) exp)
323 ((eq 'let* (car-safe exp)) `(let* (,@bindings ,@(cadr exp)) ,@(cddr exp)))
324 (t `(let* ,bindings ,exp))))
326 (defun macroexp-if (test then else)
327 "Return an expression equivalent to `(if ,test ,then ,else)."
328 (cond
329 ((eq (car-safe else) 'if)
330 (if (equal test (nth 1 else))
331 ;; Doing a test a second time: get rid of the redundancy.
332 `(if ,test ,then ,@(nthcdr 3 else))
333 `(cond (,test ,then)
334 (,(nth 1 else) ,(nth 2 else))
335 (t ,@(nthcdr 3 else)))))
336 ((eq (car-safe else) 'cond)
337 `(cond (,test ,then)
338 ;; Doing a test a second time: get rid of the redundancy, as above.
339 ,@(remove (assoc test else) (cdr else))))
340 ;; Invert the test if that lets us reduce the depth of the tree.
341 ((memq (car-safe then) '(if cond)) (macroexp-if `(not ,test) else then))
342 (t `(if ,test ,then ,else))))
344 (defmacro macroexp-let2 (test var exp &rest exps)
345 "Bind VAR to a copyable expression that returns the value of EXP.
346 This is like `(let ((v ,EXP)) ,EXPS) except that `v' is a new generated
347 symbol which EXPS can find in VAR.
348 TEST should be the name of a predicate on EXP checking whether the `let' can
349 be skipped; if nil, as is usual, `macroexp-const-p' is used."
350 (declare (indent 3) (debug (sexp sexp form body)))
351 (let ((bodysym (make-symbol "body"))
352 (expsym (make-symbol "exp")))
353 `(let* ((,expsym ,exp)
354 (,var (if (funcall #',(or test #'macroexp-const-p) ,expsym)
355 ,expsym (make-symbol ,(symbol-name var))))
356 (,bodysym ,(macroexp-progn exps)))
357 (if (eq ,var ,expsym) ,bodysym
358 (macroexp-let* (list (list ,var ,expsym))
359 ,bodysym)))))
361 (defmacro macroexp-let2* (test bindings &rest body)
362 "Bind each binding in BINDINGS as `macroexp-let2' does."
363 (declare (indent 2) (debug (sexp (&rest (sexp form)) body)))
364 (pcase-exhaustive bindings
365 (`nil (macroexp-progn body))
366 (`((,var ,exp) . ,tl)
367 `(macroexp-let2 ,test ,var ,exp
368 (macroexp-let2* ,test ,tl ,@body)))))
370 (defun macroexp--maxsize (exp size)
371 (cond ((< size 0) size)
372 ((symbolp exp) (1- size))
373 ((stringp exp) (- size (/ (length exp) 16)))
374 ((vectorp exp)
375 (dotimes (i (length exp))
376 (setq size (macroexp--maxsize (aref exp i) size)))
377 (1- size))
378 ((consp exp)
379 ;; We could try to be more clever with quote&function,
380 ;; but it is difficult to do so correctly, and it's not obvious that
381 ;; it would be worth the effort.
382 (dolist (e exp)
383 (setq size (macroexp--maxsize e size)))
384 (1- size))
385 (t -1)))
387 (defun macroexp-small-p (exp)
388 "Return non-nil if EXP can be considered small."
389 (> (macroexp--maxsize exp 10) 0))
391 (defsubst macroexp--const-symbol-p (symbol &optional any-value)
392 "Non-nil if SYMBOL is constant.
393 If ANY-VALUE is nil, only return non-nil if the value of the symbol is the
394 symbol itself."
395 (or (memq symbol '(nil t))
396 (keywordp symbol)
397 (if any-value
398 (or (memq symbol byte-compile-const-variables)
399 ;; FIXME: We should provide a less intrusive way to find out
400 ;; if a variable is "constant".
401 (and (boundp symbol)
402 (condition-case nil
403 (progn (set symbol (symbol-value symbol)) nil)
404 (setting-constant t)))))))
406 (defun macroexp-const-p (exp)
407 "Return non-nil if EXP will always evaluate to the same value."
408 (cond ((consp exp) (or (eq (car exp) 'quote)
409 (and (eq (car exp) 'function)
410 (symbolp (cadr exp)))))
411 ;; It would sometimes make sense to pass `any-value', but it's not
412 ;; always safe since a "constant" variable may not actually always have
413 ;; the same value.
414 ((symbolp exp) (macroexp--const-symbol-p exp))
415 (t t)))
417 (defun macroexp-copyable-p (exp)
418 "Return non-nil if EXP can be copied without extra cost."
419 (or (symbolp exp) (macroexp-const-p exp)))
421 (defun macroexp-quote (v)
422 "Return an expression E such that `(eval E)' is V.
424 E is either V or (quote V) depending on whether V evaluates to
425 itself or not."
426 (if (and (not (consp v))
427 (or (keywordp v)
428 (not (symbolp v))
429 (memq v '(nil t))))
431 (list 'quote v)))
433 ;;; Load-time macro-expansion.
435 ;; Because macro-expansion used to be more lazy, eager macro-expansion
436 ;; tends to bump into previously harmless/unnoticeable cyclic-dependencies.
437 ;; So, we have to delay macro-expansion like we used to when we detect
438 ;; such a cycle, and we also want to help coders resolve those cycles (since
439 ;; they can be non-obvious) by providing a usefully trimmed backtrace
440 ;; (hopefully) highlighting the problem.
442 (defun macroexp--backtrace ()
443 "Return the Elisp backtrace, more recent frames first."
444 (let ((bt ())
445 (i 0))
446 (while
447 (let ((frame (backtrace-frame i)))
448 (when frame
449 (push frame bt)
450 (setq i (1+ i)))))
451 (nreverse bt)))
453 (defun macroexp--trim-backtrace-frame (frame)
454 (pcase frame
455 (`(,_ macroexpand (,head . ,_) . ,_) `(macroexpand (,head …)))
456 (`(,_ internal-macroexpand-for-load (,head ,second . ,_) . ,_)
457 (if (or (symbolp second)
458 (and (eq 'quote (car-safe second))
459 (symbolp (cadr second))))
460 `(macroexpand-all (,head ,second …))
461 '(macroexpand-all)))
462 (`(,_ load-with-code-conversion ,name . ,_)
463 `(load ,(file-name-nondirectory name)))))
465 (defvar macroexp--pending-eager-loads nil
466 "Stack of files currently undergoing eager macro-expansion.")
468 (defun internal-macroexpand-for-load (form full-p)
469 ;; Called from the eager-macroexpansion in readevalloop.
470 (cond
471 ;; Don't repeat the same warning for every top-level element.
472 ((eq 'skip (car macroexp--pending-eager-loads)) form)
473 ;; If we detect a cycle, skip macro-expansion for now, and output a warning
474 ;; with a trimmed backtrace.
475 ((and load-file-name (member load-file-name macroexp--pending-eager-loads))
476 (let* ((bt (delq nil
477 (mapcar #'macroexp--trim-backtrace-frame
478 (macroexp--backtrace))))
479 (elem `(load ,(file-name-nondirectory load-file-name)))
480 (tail (member elem (cdr (member elem bt)))))
481 (if tail (setcdr tail (list ')))
482 (if (eq (car-safe (car bt)) 'macroexpand-all) (setq bt (cdr bt)))
483 (message "Warning: Eager macro-expansion skipped due to cycle:\n %s"
484 (mapconcat #'prin1-to-string (nreverse bt) " => "))
485 (push 'skip macroexp--pending-eager-loads)
486 form))
488 (condition-case err
489 (let ((macroexp--pending-eager-loads
490 (cons load-file-name macroexp--pending-eager-loads)))
491 (if full-p
492 (macroexpand-all form)
493 (macroexpand form)))
494 (error
495 ;; Hopefully this shouldn't happen thanks to the cycle detection,
496 ;; but in case it does happen, let's catch the error and give the
497 ;; code a chance to macro-expand later.
498 (message "Eager macro-expansion failure: %S" err)
499 form)))))
501 ;; ¡¡¡ Big Ugly Hack !!!
502 ;; src/bootstrap-emacs is mostly used to compile .el files, so it needs
503 ;; macroexp, bytecomp, cconv, and byte-opt to be fast. Generally this is done
504 ;; by compiling those files first, but this only makes a difference if those
505 ;; files are not preloaded. But macroexp.el is preloaded so we reload it if
506 ;; the current version is interpreted and there's a compiled version available.
507 (eval-when-compile
508 (add-hook 'emacs-startup-hook
509 (lambda ()
510 (and (not (byte-code-function-p
511 (symbol-function 'macroexpand-all)))
512 (locate-library "macroexp.elc")
513 (load "macroexp.elc")))))
515 (provide 'macroexp)
517 ;;; macroexp.el ends here