]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/macroexp.el
Partial fix for bug#12371
[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-2012 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
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
36 (defun macroexp--cons (car cdr original-cons)
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
44 ;; `macroexp--cons' results in excessively deep recursion for very long
45 ;; input forms.
46 (defmacro macroexp--accumulate (var+list &rest body)
47 "Return a list of the results of evaluating BODY for each element of LIST.
48 Evaluate BODY with VAR bound to each `car' from LIST, in turn.
49 Return a list of the values of the final form in BODY.
50 The list structure of the result will share as much with LIST as
51 possible (for instance, when BODY just returns VAR unchanged, the
52 result will be eq to LIST).
53
54 \(fn (VAR LIST) BODY...)"
55 (declare (indent 1))
56 (let ((var (car var+list))
57 (list (cadr var+list))
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)
66 (while (consp ,tail)
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))))
76
77 (defun macroexp--all-forms (forms &optional skip)
78 "Return FORMS with macros expanded. FORMS is a list of forms.
79 If SKIP is non-nil, then don't expand that many elements at the start of
80 FORMS."
81 (macroexp--accumulate (form forms)
82 (if (or (null skip) (zerop skip))
83 (macroexp--expand-all form)
84 (setq skip (1- skip))
85 form)))
86
87 (defun macroexp--all-clauses (clauses &optional skip)
88 "Return CLAUSES with macros expanded.
89 CLAUSES is a list of lists of forms; any clause that's not a list is ignored.
90 If SKIP is non-nil, then don't expand that many elements at the start of
91 each clause."
92 (macroexp--accumulate (clause clauses)
93 (if (listp clause)
94 (macroexp--all-forms clause skip)
95 clause)))
96
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)
101 form)))
102
103 (defun macroexp--eval-if-compile (&rest _forms)
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--eval-if-compile 'byte-compile
110 (lambda (form)
111 (mapc (lambda (x) (funcall (eval x))) (cdr form))
112 (byte-compile-constant nil)))
113
114 (autoload 'byte-compile-warn-obsolete "bytecomp")
115 (autoload 'byte-compile-log-warning "bytecomp")
116
117 (defun macroexp--expand-all (form)
118 "Expand all macros in FORM.
119 This is an internal version of `macroexpand-all'.
120 Assumes the caller has bound `macroexpand-all-environment'."
121 (if (and (listp form) (eq (car form) 'backquote-list*))
122 ;; Special-case `backquote-list*', as it is normally a macro that
123 ;; generates exceedingly deep expansions from relatively shallow input
124 ;; forms. We just process it `in reverse' -- first we expand all the
125 ;; arguments, _then_ we expand the top-level definition.
126 (macroexpand (macroexp--all-forms form 1)
127 macroexpand-all-environment)
128 ;; Normal form; get its expansion, and then expand arguments.
129 (let ((new-form
130 (macroexpand form macroexpand-all-environment)))
131 (setq form
132 (if (and (not (eq form new-form)) ;It was a macro call.
133 (car-safe form)
134 (symbolp (car form))
135 (get (car form) 'byte-obsolete-info))
136 `(progn (macroexp--eval-if-compile
137 (lambda () (byte-compile-warn-obsolete ',(car form))))
138 ,new-form)
139 new-form)))
140 (pcase form
141 (`(cond . ,clauses)
142 (macroexp--cons 'cond (macroexp--all-clauses clauses) form))
143 (`(condition-case . ,(or `(,err ,body . ,handlers) dontcare))
144 (macroexp--cons
145 'condition-case
146 (macroexp--cons err
147 (macroexp--cons (macroexp--expand-all body)
148 (macroexp--all-clauses handlers 1)
149 (cddr form))
150 (cdr form))
151 form))
152 (`(,(or `defvar `defconst) . ,_) (macroexp--all-forms form 2))
153 (`(function ,(and f `(lambda . ,_)))
154 (macroexp--cons 'function
155 (macroexp--cons (macroexp--all-forms f 2)
156 nil
157 (cdr form))
158 form))
159 (`(,(or `function `quote) . ,_) form)
160 (`(,(and fun (or `let `let*)) . ,(or `(,bindings . ,body) dontcare))
161 (macroexp--cons fun
162 (macroexp--cons (macroexp--all-clauses bindings 1)
163 (macroexp--all-forms body)
164 (cdr form))
165 form))
166 (`(,(and fun `(lambda . ,_)) . ,args)
167 ;; Embedded lambda in function position.
168 (macroexp--cons (macroexp--all-forms fun 2)
169 (macroexp--all-forms args)
170 form))
171 ;; The following few cases are for normal function calls that
172 ;; are known to funcall one of their arguments. The byte
173 ;; compiler has traditionally handled these functions specially
174 ;; by treating a lambda expression quoted by `quote' as if it
175 ;; were quoted by `function'. We make the same transformation
176 ;; here, so that any code that cares about the difference will
177 ;; see the same transformation.
178 ;; First arg is a function:
179 (`(,(and fun (or `funcall `apply `mapcar `mapatoms `mapconcat `mapc))
180 ',(and f `(lambda . ,_)) . ,args)
181 (byte-compile-log-warning
182 (format "%s quoted with ' rather than with #'"
183 (list 'lambda (nth 1 f) '...))
184 t)
185 ;; We don't use `macroexp--cons' since there's clearly a change.
186 (cons fun
187 (cons (macroexp--expand-all (list 'function f))
188 (macroexp--all-forms args))))
189 ;; Second arg is a function:
190 (`(,(and fun (or `sort)) ,arg1 ',(and f `(lambda . ,_)) . ,args)
191 (byte-compile-log-warning
192 (format "%s quoted with ' rather than with #'"
193 (list 'lambda (nth 1 f) '...))
194 t)
195 ;; We don't use `macroexp--cons' since there's clearly a change.
196 (cons fun
197 (cons (macroexp--expand-all arg1)
198 (cons (macroexp--expand-all
199 (list 'function f))
200 (macroexp--all-forms args)))))
201 (`(,func . ,_)
202 ;; Macro expand compiler macros. This cannot be delayed to
203 ;; byte-optimize-form because the output of the compiler-macro can
204 ;; use macros.
205 (let ((handler (function-get func 'compiler-macro)))
206 (if (null handler)
207 ;; No compiler macro. We just expand each argument (for
208 ;; setq/setq-default this works alright because the variable names
209 ;; are symbols).
210 (macroexp--all-forms form 1)
211 ;; If the handler is not loaded yet, try (auto)loading the
212 ;; function itself, which may in turn load the handler.
213 (unless (functionp handler)
214 (ignore-errors
215 (autoload-do-load (indirect-function func) func)))
216 (let ((newform (macroexp--compiler-macro handler form)))
217 (if (eq form newform)
218 ;; The compiler macro did not find anything to do.
219 (if (equal form (setq newform (macroexp--all-forms form 1)))
220 form
221 ;; Maybe after processing the args, some new opportunities
222 ;; appeared, so let's try the compiler macro again.
223 (setq form (macroexp--compiler-macro handler newform))
224 (if (eq newform form)
225 newform
226 (macroexp--expand-all newform)))
227 (macroexp--expand-all newform))))))
228
229 (t form))))
230
231 ;;;###autoload
232 (defun macroexpand-all (form &optional environment)
233 "Return result of expanding macros at all levels in FORM.
234 If no macros are expanded, FORM is returned unchanged.
235 The second optional arg ENVIRONMENT specifies an environment of macro
236 definitions to shadow the loaded ones for use in file byte-compilation."
237 (let ((macroexpand-all-environment environment))
238 (macroexp--expand-all form)))
239
240 ;;; Handy functions to use in macros.
241
242 (defun macroexp-progn (exps)
243 "Return an expression equivalent to `(progn ,@EXPS)."
244 (if (cdr exps) `(progn ,@exps) (car exps)))
245
246 (defun macroexp-unprogn (exp)
247 "Turn EXP into a list of expressions to execute in sequence."
248 (if (eq (car-safe exp) 'progn) (cdr exp) (list exp)))
249
250 (defun macroexp-let* (bindings exp)
251 "Return an expression equivalent to `(let* ,bindings ,exp)."
252 (cond
253 ((null bindings) exp)
254 ((eq 'let* (car-safe exp)) `(let* (,@bindings ,@(cadr exp)) ,@(cddr exp)))
255 (t `(let* ,bindings ,exp))))
256
257 (defun macroexp-if (test then else)
258 "Return an expression equivalent to `(if ,test ,then ,else)."
259 (cond
260 ((eq (car-safe else) 'if)
261 (if (equal test (nth 1 else))
262 ;; Doing a test a second time: get rid of the redundancy.
263 `(if ,test ,then ,@(nthcdr 3 else))
264 `(cond (,test ,then)
265 (,(nth 1 else) ,(nth 2 else))
266 (t ,@(nthcdr 3 else)))))
267 ((eq (car-safe else) 'cond)
268 `(cond (,test ,then)
269 ;; Doing a test a second time: get rid of the redundancy, as above.
270 ,@(remove (assoc test else) (cdr else))))
271 ;; Invert the test if that lets us reduce the depth of the tree.
272 ((memq (car-safe then) '(if cond)) (macroexp-if `(not ,test) else then))
273 (t `(if ,test ,then ,else))))
274
275 (defmacro macroexp-let2 (test var exp &rest exps)
276 "Bind VAR to a copyable expression that returns the value of EXP.
277 This is like `(let ((v ,EXP)) ,EXPS) except that `v' is a new generated
278 symbol which EXPS can find in VAR.
279 TEST should be the name of a predicate on EXP checking whether the `let' can
280 be skipped; if nil, as is usual, `macroexp-const-p' is used."
281 (declare (indent 3) (debug (sexp sexp form body)))
282 (let ((bodysym (make-symbol "body"))
283 (expsym (make-symbol "exp")))
284 `(let* ((,expsym ,exp)
285 (,var (if (funcall #',(or test #'macroexp-const-p) ,expsym)
286 ,expsym (make-symbol ,(symbol-name var))))
287 (,bodysym ,(macroexp-progn exps)))
288 (if (eq ,var ,expsym) ,bodysym
289 (macroexp-let* (list (list ,var ,expsym))
290 ,bodysym)))))
291
292 (defun macroexp--maxsize (exp size)
293 (cond ((< size 0) size)
294 ((symbolp exp) (1- size))
295 ((stringp exp) (- size (/ (length exp) 16)))
296 ((vectorp exp)
297 (dotimes (i (length exp))
298 (setq size (macroexp--maxsize (aref exp i) size)))
299 (1- size))
300 ((consp exp)
301 ;; We could try to be more clever with quote&function,
302 ;; but it is difficult to do so correctly, and it's not obvious that
303 ;; it would be worth the effort.
304 (dolist (e exp)
305 (setq size (macroexp--maxsize e size)))
306 (1- size))
307 (t -1)))
308
309 (defun macroexp-small-p (exp)
310 "Return non-nil if EXP can be considered small."
311 (> (macroexp--maxsize exp 10) 0))
312
313 (defsubst macroexp--const-symbol-p (symbol &optional any-value)
314 "Non-nil if SYMBOL is constant.
315 If ANY-VALUE is nil, only return non-nil if the value of the symbol is the
316 symbol itself."
317 (or (memq symbol '(nil t))
318 (keywordp symbol)
319 (if any-value
320 (or (memq symbol byte-compile-const-variables)
321 ;; FIXME: We should provide a less intrusive way to find out
322 ;; if a variable is "constant".
323 (and (boundp symbol)
324 (condition-case nil
325 (progn (set symbol (symbol-value symbol)) nil)
326 (setting-constant t)))))))
327
328 (defun macroexp-const-p (exp)
329 "Return non-nil if EXP will always evaluate to the same value."
330 (cond ((consp exp) (or (eq (car exp) 'quote)
331 (and (eq (car exp) 'function)
332 (symbolp (cadr exp)))))
333 ;; It would sometimes make sense to pass `any-value', but it's not
334 ;; always safe since a "constant" variable may not actually always have
335 ;; the same value.
336 ((symbolp exp) (macroexp--const-symbol-p exp))
337 (t t)))
338
339 (defun macroexp-copyable-p (exp)
340 "Return non-nil if EXP can be copied without extra cost."
341 (or (symbolp exp) (macroexp-const-p exp)))
342
343 ;;; Load-time macro-expansion.
344
345 ;; Because macro-expansion used to be more lazy, eager macro-expansion
346 ;; tends to bump into previously harmless/unnoticeable cyclic-dependencies.
347 ;; So, we have to delay macro-expansion like we used to when we detect
348 ;; such a cycle, and we also want to help coders resolve those cycles (since
349 ;; they can be non-obvious) by providing a usefully trimmed backtrace
350 ;; (hopefully) highlighting the problem.
351
352 (defun macroexp--backtrace ()
353 "Return the Elisp backtrace, more recent frames first."
354 (let ((bt ())
355 (i 0))
356 (while
357 (let ((frame (backtrace-frame i)))
358 (when frame
359 (push frame bt)
360 (setq i (1+ i)))))
361 (nreverse bt)))
362
363 (defun macroexp--trim-backtrace-frame (frame)
364 (pcase frame
365 (`(,_ macroexpand (,head . ,_) . ,_) `(macroexpand (,head …)))
366 (`(,_ internal-macroexpand-for-load (,head ,second . ,_) . ,_)
367 (if (or (symbolp second)
368 (and (eq 'quote (car-safe second))
369 (symbolp (cadr second))))
370 `(macroexpand-all (,head ,second …))
371 '(macroexpand-all …)))
372 (`(,_ load-with-code-conversion ,name . ,_)
373 `(load ,(file-name-nondirectory name)))))
374
375 (defvar macroexp--pending-eager-loads nil
376 "Stack of files currently undergoing eager macro-expansion.")
377
378 (defun internal-macroexpand-for-load (form)
379 ;; Called from the eager-macroexpansion in readevalloop.
380 (cond
381 ;; Don't repeat the same warning for every top-level element.
382 ((eq 'skip (car macroexp--pending-eager-loads)) form)
383 ;; If we detect a cycle, skip macro-expansion for now, and output a warning
384 ;; with a trimmed backtrace.
385 ((and load-file-name (member load-file-name macroexp--pending-eager-loads))
386 (let* ((bt (delq nil
387 (mapcar #'macroexp--trim-backtrace-frame
388 (macroexp--backtrace))))
389 (elem `(load ,(file-name-nondirectory load-file-name)))
390 (tail (member elem (cdr (member elem bt)))))
391 (if tail (setcdr tail (list '…)))
392 (if (eq (car-safe (car bt)) 'macroexpand-all) (setq bt (cdr bt)))
393 (message "Warning: Eager macro-expansion skipped due to cycle:\n %s"
394 (mapconcat #'prin1-to-string (nreverse bt) " => "))
395 (push 'skip macroexp--pending-eager-loads)
396 form))
397 (t
398 (condition-case err
399 (let ((macroexp--pending-eager-loads
400 (cons load-file-name macroexp--pending-eager-loads)))
401 (macroexpand-all form))
402 (error
403 ;; Hopefully this shouldn't happen thanks to the cycle detection,
404 ;; but in case it does happen, let's catch the error and give the
405 ;; code a chance to macro-expand later.
406 (message "Eager macro-expansion failure: %S" err)
407 form)))))
408
409 ;; ¡¡¡ Big Ugly Hack !!!
410 ;; src/bootstrap-emacs is mostly used to compile .el files, so it needs
411 ;; macroexp, bytecomp, cconv, and byte-opt to be fast. Generally this is done
412 ;; by compiling those files first, but this only makes a difference if those
413 ;; files are not preloaded. But macroexp.el is preloaded so we reload it if
414 ;; the current version is interpreted and there's a compiled version available.
415 (eval-when-compile
416 (add-hook 'emacs-startup-hook
417 (lambda ()
418 (and (not (byte-code-function-p
419 (symbol-function 'macroexpand-all)))
420 (locate-library "macroexp.elc")
421 (load "macroexp.elc")))))
422
423 (provide 'macroexp)
424
425 ;;; macroexp.el ends here