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