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