Use curved quotes in core elisp diagnostics
[emacs.git] / lisp / emacs-lisp / macroexp.el
blobcc461c81cdd27b22bfab8f24b07eadec8d110ff5
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))
122 (defvar macroexp--warned (make-hash-table :test #'equal :weakness 'key))
124 (defun macroexp--warn-and-return (msg form &optional compile-only)
125 (let ((when-compiled (lambda () (byte-compile-log-warning msg t))))
126 (cond
127 ((null msg) form)
128 ((macroexp--compiling-p)
129 (if (gethash form macroexp--warned)
130 ;; Already wrapped this exp with a warning: avoid inf-looping
131 ;; where we keep adding the same warning onto `form' because
132 ;; macroexpand-all gets right back to macroexpanding `form'.
133 form
134 (puthash form form macroexp--warned)
135 `(progn
136 (macroexp--funcall-if-compiled ',when-compiled)
137 ,form)))
139 (unless compile-only
140 (message "%s%s" (if (stringp load-file-name)
141 (concat (file-relative-name load-file-name) ": ")
143 msg))
144 form))))
146 (defun macroexp--obsolete-warning (fun obsolescence-data type)
147 (let ((instead (car obsolescence-data))
148 (asof (nth 2 obsolescence-data)))
149 (format "‘%s’ is an obsolete %s%s%s" fun type
150 (if asof (concat " (as of " asof ")") "")
151 (cond ((stringp instead) (concat "; " instead))
152 (instead (format "; use ‘%s’ instead." instead))
153 (t ".")))))
155 (defun macroexpand-1 (form &optional environment)
156 "Perform (at most) one step of macroexpansion."
157 (cond
158 ((consp form)
159 (let* ((head (car form))
160 (env-expander (assq head environment)))
161 (if env-expander
162 (if (cdr env-expander)
163 (apply (cdr env-expander) (cdr form))
164 form)
165 (if (not (and (symbolp head) (fboundp head)))
166 form
167 (let ((def (autoload-do-load (symbol-function head) head 'macro)))
168 (cond
169 ;; Follow alias, but only for macros, otherwise we may end up
170 ;; skipping an important compiler-macro (e.g. cl--block-wrapper).
171 ((and (symbolp def) (macrop def)) (cons def (cdr form)))
172 ((not (consp def)) form)
174 (if (eq 'macro (car def))
175 (apply (cdr def) (cdr form))
176 form))))))))
177 (t form)))
179 (defun macroexp-macroexpand (form env)
180 "Like `macroexpand' but checking obsolescence."
181 (let ((new-form
182 (macroexpand form env)))
183 (if (and (not (eq form new-form)) ;It was a macro call.
184 (car-safe form)
185 (symbolp (car form))
186 (get (car form) 'byte-obsolete-info)
187 (or (not (fboundp 'byte-compile-warning-enabled-p))
188 (byte-compile-warning-enabled-p 'obsolete)))
189 (let* ((fun (car form))
190 (obsolete (get fun 'byte-obsolete-info)))
191 (macroexp--warn-and-return
192 (macroexp--obsolete-warning
193 fun obsolete
194 (if (symbolp (symbol-function fun))
195 "alias" "macro"))
196 new-form))
197 new-form)))
199 (defun macroexp--expand-all (form)
200 "Expand all macros in FORM.
201 This is an internal version of `macroexpand-all'.
202 Assumes the caller has bound `macroexpand-all-environment'."
203 (if (eq (car-safe form) 'backquote-list*)
204 ;; Special-case `backquote-list*', as it is normally a macro that
205 ;; generates exceedingly deep expansions from relatively shallow input
206 ;; forms. We just process it `in reverse' -- first we expand all the
207 ;; arguments, _then_ we expand the top-level definition.
208 (macroexpand (macroexp--all-forms form 1)
209 macroexpand-all-environment)
210 ;; Normal form; get its expansion, and then expand arguments.
211 (setq form (macroexp-macroexpand form macroexpand-all-environment))
212 (pcase form
213 (`(cond . ,clauses)
214 (macroexp--cons 'cond (macroexp--all-clauses clauses) form))
215 (`(condition-case . ,(or `(,err ,body . ,handlers) dontcare))
216 (macroexp--cons
217 'condition-case
218 (macroexp--cons err
219 (macroexp--cons (macroexp--expand-all body)
220 (macroexp--all-clauses handlers 1)
221 (cddr form))
222 (cdr form))
223 form))
224 (`(,(or `defvar `defconst) . ,_) (macroexp--all-forms form 2))
225 (`(function ,(and f `(lambda . ,_)))
226 (macroexp--cons 'function
227 (macroexp--cons (macroexp--all-forms f 2)
229 (cdr form))
230 form))
231 (`(,(or `function `quote) . ,_) form)
232 (`(,(and fun (or `let `let*)) . ,(or `(,bindings . ,body) dontcare))
233 (macroexp--cons fun
234 (macroexp--cons (macroexp--all-clauses bindings 1)
235 (macroexp--all-forms body)
236 (cdr form))
237 form))
238 (`(,(and fun `(lambda . ,_)) . ,args)
239 ;; Embedded lambda in function position.
240 (macroexp--cons (macroexp--all-forms fun 2)
241 (macroexp--all-forms args)
242 form))
243 ;; The following few cases are for normal function calls that
244 ;; are known to funcall one of their arguments. The byte
245 ;; compiler has traditionally handled these functions specially
246 ;; by treating a lambda expression quoted by `quote' as if it
247 ;; were quoted by `function'. We make the same transformation
248 ;; here, so that any code that cares about the difference will
249 ;; see the same transformation.
250 ;; First arg is a function:
251 (`(,(and fun (or `funcall `apply `mapcar `mapatoms `mapconcat `mapc))
252 ',(and f `(lambda . ,_)) . ,args)
253 (macroexp--warn-and-return
254 (format "%s quoted with ' rather than with #'"
255 (list 'lambda (nth 1 f) '...))
256 (macroexp--expand-all `(,fun ,f . ,args))))
257 ;; Second arg is a function:
258 (`(,(and fun (or `sort)) ,arg1 ',(and f `(lambda . ,_)) . ,args)
259 (macroexp--warn-and-return
260 (format "%s quoted with ' rather than with #'"
261 (list 'lambda (nth 1 f) '...))
262 (macroexp--expand-all `(,fun ,arg1 ,f . ,args))))
263 (`(funcall (,(or 'quote 'function) ,(and f (pred symbolp)) . ,_) . ,args)
264 ;; Rewrite (funcall #'foo bar) to (foo bar), in case `foo'
265 ;; has a compiler-macro.
266 (macroexp--expand-all `(,f . ,args)))
267 (`(,func . ,_)
268 ;; Macro expand compiler macros. This cannot be delayed to
269 ;; byte-optimize-form because the output of the compiler-macro can
270 ;; use macros.
271 (let ((handler (function-get func 'compiler-macro)))
272 (if (null handler)
273 ;; No compiler macro. We just expand each argument (for
274 ;; setq/setq-default this works alright because the variable names
275 ;; are symbols).
276 (macroexp--all-forms form 1)
277 ;; If the handler is not loaded yet, try (auto)loading the
278 ;; function itself, which may in turn load the handler.
279 (unless (functionp handler)
280 (with-demoted-errors "macroexp--expand-all: %S"
281 (autoload-do-load (indirect-function func) func)))
282 (let ((newform (macroexp--compiler-macro handler form)))
283 (if (eq form newform)
284 ;; The compiler macro did not find anything to do.
285 (if (equal form (setq newform (macroexp--all-forms form 1)))
286 form
287 ;; Maybe after processing the args, some new opportunities
288 ;; appeared, so let's try the compiler macro again.
289 (setq form (macroexp--compiler-macro handler newform))
290 (if (eq newform form)
291 newform
292 (macroexp--expand-all newform)))
293 (macroexp--expand-all newform))))))
295 (_ form))))
297 ;;;###autoload
298 (defun macroexpand-all (form &optional environment)
299 "Return result of expanding macros at all levels in FORM.
300 If no macros are expanded, FORM is returned unchanged.
301 The second optional arg ENVIRONMENT specifies an environment of macro
302 definitions to shadow the loaded ones for use in file byte-compilation."
303 (let ((macroexpand-all-environment environment))
304 (macroexp--expand-all form)))
306 ;;; Handy functions to use in macros.
308 (defun macroexp-parse-body (body)
309 "Parse a function BODY into (DECLARATIONS . EXPS)."
310 (let ((decls ()))
311 (while (and (cdr body)
312 (let ((e (car body)))
313 (or (stringp e)
314 (memq (car-safe e)
315 '(:documentation declare interactive cl-declare)))))
316 (push (pop body) decls))
317 (cons (nreverse decls) body)))
319 (defun macroexp-progn (exps)
320 "Return an expression equivalent to `(progn ,@EXPS)."
321 (if (cdr exps) `(progn ,@exps) (car exps)))
323 (defun macroexp-unprogn (exp)
324 "Turn EXP into a list of expressions to execute in sequence."
325 (if (eq (car-safe exp) 'progn) (cdr exp) (list exp)))
327 (defun macroexp-let* (bindings exp)
328 "Return an expression equivalent to `(let* ,bindings ,exp)."
329 (cond
330 ((null bindings) exp)
331 ((eq 'let* (car-safe exp)) `(let* (,@bindings ,@(cadr exp)) ,@(cddr exp)))
332 (t `(let* ,bindings ,exp))))
334 (defun macroexp-if (test then else)
335 "Return an expression equivalent to `(if ,test ,then ,else)."
336 (cond
337 ((eq (car-safe else) 'if)
338 (if (equal test (nth 1 else))
339 ;; Doing a test a second time: get rid of the redundancy.
340 `(if ,test ,then ,@(nthcdr 3 else))
341 `(cond (,test ,then)
342 (,(nth 1 else) ,(nth 2 else))
343 (t ,@(nthcdr 3 else)))))
344 ((eq (car-safe else) 'cond)
345 `(cond (,test ,then)
346 ;; Doing a test a second time: get rid of the redundancy, as above.
347 ,@(remove (assoc test else) (cdr else))))
348 ;; Invert the test if that lets us reduce the depth of the tree.
349 ((memq (car-safe then) '(if cond)) (macroexp-if `(not ,test) else then))
350 (t `(if ,test ,then ,else))))
352 (defmacro macroexp-let2 (test sym exp &rest body)
353 "Evaluate BODY with SYM bound to an expression for EXP's value.
354 The intended usage is that BODY generates an expression that
355 will refer to EXP's value multiple times, but will evaluate
356 EXP only once. As BODY generates that expression, it should
357 use SYM to stand for the value of EXP.
359 If EXP is a simple, safe expression, then SYM's value is EXP itself.
360 Otherwise, SYM's value is a symbol which holds the value produced by
361 evaluating EXP. The return value incorporates the value of BODY, plus
362 additional code to evaluate EXP once and save the result so SYM can
363 refer to it.
365 If BODY consists of multiple forms, they are all evaluated
366 but only the last one's value matters.
368 TEST is a predicate to determine whether EXP qualifies as simple and
369 safe; if TEST is nil, only constant expressions qualify.
371 Example:
372 (macroexp-let2 nil foo EXP
373 \\=`(* ,foo ,foo))
374 generates an expression that evaluates EXP once,
375 then returns the square of that value.
376 You could do this with
377 (let ((foovar EXP))
378 (* foovar foovar))
379 but using `macroexp-let2' produces more efficient code in
380 cases where EXP is a constant."
381 (declare (indent 3) (debug (sexp sexp form body)))
382 (let ((bodysym (make-symbol "body"))
383 (expsym (make-symbol "exp")))
384 `(let* ((,expsym ,exp)
385 (,sym (if (funcall #',(or test #'macroexp-const-p) ,expsym)
386 ,expsym (make-symbol ,(symbol-name sym))))
387 (,bodysym ,(macroexp-progn body)))
388 (if (eq ,sym ,expsym) ,bodysym
389 (macroexp-let* (list (list ,sym ,expsym))
390 ,bodysym)))))
392 (defmacro macroexp-let2* (test bindings &rest body)
393 "Bind each binding in BINDINGS as `macroexp-let2' does."
394 (declare (indent 2) (debug (sexp (&rest (sexp form)) body)))
395 (pcase-exhaustive bindings
396 (`nil (macroexp-progn body))
397 (`((,var ,exp) . ,tl)
398 `(macroexp-let2 ,test ,var ,exp
399 (macroexp-let2* ,test ,tl ,@body)))))
401 (defun macroexp--maxsize (exp size)
402 (cond ((< size 0) size)
403 ((symbolp exp) (1- size))
404 ((stringp exp) (- size (/ (length exp) 16)))
405 ((vectorp exp)
406 (dotimes (i (length exp))
407 (setq size (macroexp--maxsize (aref exp i) size)))
408 (1- size))
409 ((consp exp)
410 ;; We could try to be more clever with quote&function,
411 ;; but it is difficult to do so correctly, and it's not obvious that
412 ;; it would be worth the effort.
413 (dolist (e exp)
414 (setq size (macroexp--maxsize e size)))
415 (1- size))
416 (t -1)))
418 (defun macroexp-small-p (exp)
419 "Return non-nil if EXP can be considered small."
420 (> (macroexp--maxsize exp 10) 0))
422 (defsubst macroexp--const-symbol-p (symbol &optional any-value)
423 "Non-nil if SYMBOL is constant.
424 If ANY-VALUE is nil, only return non-nil if the value of the symbol is the
425 symbol itself."
426 (or (memq symbol '(nil t))
427 (keywordp symbol)
428 (if any-value
429 (or (memq symbol byte-compile-const-variables)
430 ;; FIXME: We should provide a less intrusive way to find out
431 ;; if a variable is "constant".
432 (and (boundp symbol)
433 (condition-case nil
434 (progn (set symbol (symbol-value symbol)) nil)
435 (setting-constant t)))))))
437 (defun macroexp-const-p (exp)
438 "Return non-nil if EXP will always evaluate to the same value."
439 (cond ((consp exp) (or (eq (car exp) 'quote)
440 (and (eq (car exp) 'function)
441 (symbolp (cadr exp)))))
442 ;; It would sometimes make sense to pass `any-value', but it's not
443 ;; always safe since a "constant" variable may not actually always have
444 ;; the same value.
445 ((symbolp exp) (macroexp--const-symbol-p exp))
446 (t t)))
448 (defun macroexp-copyable-p (exp)
449 "Return non-nil if EXP can be copied without extra cost."
450 (or (symbolp exp) (macroexp-const-p exp)))
452 (defun macroexp-quote (v)
453 "Return an expression E such that `(eval E)' is V.
455 E is either V or (quote V) depending on whether V evaluates to
456 itself or not."
457 (if (and (not (consp v))
458 (or (keywordp v)
459 (not (symbolp v))
460 (memq v '(nil t))))
462 (list 'quote v)))
464 ;;; Load-time macro-expansion.
466 ;; Because macro-expansion used to be more lazy, eager macro-expansion
467 ;; tends to bump into previously harmless/unnoticeable cyclic-dependencies.
468 ;; So, we have to delay macro-expansion like we used to when we detect
469 ;; such a cycle, and we also want to help coders resolve those cycles (since
470 ;; they can be non-obvious) by providing a usefully trimmed backtrace
471 ;; (hopefully) highlighting the problem.
473 (defun macroexp--backtrace ()
474 "Return the Elisp backtrace, more recent frames first."
475 (let ((bt ())
476 (i 0))
477 (while
478 (let ((frame (backtrace-frame i)))
479 (when frame
480 (push frame bt)
481 (setq i (1+ i)))))
482 (nreverse bt)))
484 (defun macroexp--trim-backtrace-frame (frame)
485 (pcase frame
486 (`(,_ macroexpand (,head . ,_) . ,_) `(macroexpand (,head …)))
487 (`(,_ internal-macroexpand-for-load (,head ,second . ,_) . ,_)
488 (if (or (symbolp second)
489 (and (eq 'quote (car-safe second))
490 (symbolp (cadr second))))
491 `(macroexpand-all (,head ,second …))
492 '(macroexpand-all)))
493 (`(,_ load-with-code-conversion ,name . ,_)
494 `(load ,(file-name-nondirectory name)))))
496 (defvar macroexp--pending-eager-loads nil
497 "Stack of files currently undergoing eager macro-expansion.")
499 (defvar macroexp--debug-eager nil)
501 (defun internal-macroexpand-for-load (form full-p)
502 ;; Called from the eager-macroexpansion in readevalloop.
503 (cond
504 ;; Don't repeat the same warning for every top-level element.
505 ((eq 'skip (car macroexp--pending-eager-loads)) form)
506 ;; If we detect a cycle, skip macro-expansion for now, and output a warning
507 ;; with a trimmed backtrace.
508 ((and load-file-name (member load-file-name macroexp--pending-eager-loads))
509 (let* ((bt (delq nil
510 (mapcar #'macroexp--trim-backtrace-frame
511 (macroexp--backtrace))))
512 (elem `(load ,(file-name-nondirectory load-file-name)))
513 (tail (member elem (cdr (member elem bt)))))
514 (if tail (setcdr tail (list ')))
515 (if (eq (car-safe (car bt)) 'macroexpand-all) (setq bt (cdr bt)))
516 (if macroexp--debug-eager
517 (debug 'eager-macroexp-cycle)
518 (message "Warning: Eager macro-expansion skipped due to cycle:\n %s"
519 (mapconcat #'prin1-to-string (nreverse bt) " => ")))
520 (push 'skip macroexp--pending-eager-loads)
521 form))
523 (condition-case err
524 (let ((macroexp--pending-eager-loads
525 (cons load-file-name macroexp--pending-eager-loads)))
526 (if full-p
527 (macroexpand-all form)
528 (macroexpand form)))
529 (error
530 ;; Hopefully this shouldn't happen thanks to the cycle detection,
531 ;; but in case it does happen, let's catch the error and give the
532 ;; code a chance to macro-expand later.
533 (message "Eager macro-expansion failure: %S" err)
534 form)))))
536 ;; ¡¡¡ Big Ugly Hack !!!
537 ;; src/bootstrap-emacs is mostly used to compile .el files, so it needs
538 ;; macroexp, bytecomp, cconv, and byte-opt to be fast. Generally this is done
539 ;; by compiling those files first, but this only makes a difference if those
540 ;; files are not preloaded. But macroexp.el is preloaded so we reload it if
541 ;; the current version is interpreted and there's a compiled version available.
542 (eval-when-compile
543 (add-hook 'emacs-startup-hook
544 (lambda ()
545 (and (not (byte-code-function-p
546 (symbol-function 'macroexpand-all)))
547 (locate-library "macroexp.elc")
548 (load "macroexp.elc")))))
550 (provide 'macroexp)
552 ;;; macroexp.el ends here