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