Merge from trunk after a lot of time.
[bpt/emacs.git] / lisp / emacs-lisp / nadvice.el
CommitLineData
231d8498
SM
1;;; nadvice.el --- Light-weight advice primitives for Elisp functions -*- lexical-binding: t -*-
2
09b8afb6 3;; Copyright (C) 2012-2013 Free Software Foundation, Inc.
231d8498
SM
4
5;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6;; Keywords: extensions, lisp, tools
7;; Package: emacs
8
9;; This program is free software; you can redistribute it and/or modify
10;; it under the terms of the GNU General Public License as published by
11;; the Free Software Foundation, either version 3 of the License, or
12;; (at your option) any later version.
13
14;; This program is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17;; GNU General Public License for more details.
18
19;; You should have received a copy of the GNU General Public License
20;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22;;; Commentary:
23
24;; This package lets you add behavior (which we call "piece of advice") to
25;; existing functions, like the old `advice.el' package, but with much fewer
8725b746 26;; bells and whistles. It comes in 2 parts:
231d8498
SM
27;;
28;; - The first part lets you add/remove functions, similarly to
29;; add/remove-hook, from any "place" (i.e. as accepted by `setf') that
30;; holds a function.
31;; This part provides mainly 2 macros: `add-function' and `remove-function'.
32;;
a77b8d5e 33;; - The second part provides `advice-add' and `advice-remove' which are
231d8498
SM
34;; refined version of the previous macros specially tailored for the case
35;; where the place that we want to modify is a `symbol-function'.
36
37;;; Code:
38
39;;;; Lightweight advice/hook
40(defvar advice--where-alist
41 '((:around "\300\301\302\003#\207" 5)
42 (:before "\300\301\002\"\210\300\302\002\"\207" 4)
43 (:after "\300\302\002\"\300\301\003\"\210\207" 5)
bcd7a0a4 44 (:override "\300\301\ 2\"\207" 4)
231d8498
SM
45 (:after-until "\300\302\002\"\206\013\000\300\301\002\"\207" 4)
46 (:after-while "\300\302\002\"\205\013\000\300\301\002\"\207" 4)
47 (:before-until "\300\301\002\"\206\013\000\300\302\002\"\207" 4)
d36ed1c8
SM
48 (:before-while "\300\301\002\"\205\013\000\300\302\002\"\207" 4)
49 (:filter-args "\300\302\301\ 3!\"\207" 5)
50 (:filter-return "\301\300\302\ 3\"!\207" 5))
231d8498
SM
51 "List of descriptions of how to add a function.
52Each element has the form (WHERE BYTECODE STACK) where:
53 WHERE is a keyword indicating where the function is added.
54 BYTECODE is the corresponding byte-code that will be used.
55 STACK is the amount of stack space needed by the byte-code.")
56
57(defvar advice--bytecodes (mapcar #'cadr advice--where-alist))
58
59(defun advice--p (object)
60 (and (byte-code-function-p object)
61 (eq 128 (aref object 0))
62 (memq (length object) '(5 6))
63 (memq (aref object 1) advice--bytecodes)
64 (eq #'apply (aref (aref object 2) 0))))
65
66(defsubst advice--car (f) (aref (aref f 2) 1))
67(defsubst advice--cdr (f) (aref (aref f 2) 2))
68(defsubst advice--props (f) (aref (aref f 2) 3))
69
70(defun advice--make-docstring (_string function)
71 "Build the raw doc-string of SYMBOL, presumably advised."
72 (let ((flist (indirect-function function))
73 (docstring nil))
74 (if (eq 'macro (car-safe flist)) (setq flist (cdr flist)))
75 (while (advice--p flist)
76 (let ((bytecode (aref flist 1))
77 (where nil))
78 (dolist (elem advice--where-alist)
79 (if (eq bytecode (cadr elem)) (setq where (car elem))))
80 (setq docstring
81 (concat
82 docstring
83 (propertize (format "%s advice: " where)
84 'face 'warning)
85 (let ((fun (advice--car flist)))
86 (if (symbolp fun) (format "`%S'" fun)
87 (let* ((name (cdr (assq 'name (advice--props flist))))
88 (doc (documentation fun t))
89 (usage (help-split-fundoc doc function)))
90 (if usage (setq doc (cdr usage)))
91 (if name
92 (if doc
93 (format "%s\n%s" name doc)
94 (format "%s" name))
95 (or doc "No documentation")))))
96 "\n")))
97 (setq flist (advice--cdr flist)))
98 (if docstring (setq docstring (concat docstring "\n")))
99 (let* ((origdoc (unless (eq function flist) ;Avoid inf-loops.
100 (documentation flist t)))
101 (usage (help-split-fundoc origdoc function)))
102 (setq usage (if (null usage)
103 (let ((arglist (help-function-arglist flist)))
104 (format "%S" (help-make-usage function arglist)))
105 (setq origdoc (cdr usage)) (car usage)))
106 (help-add-fundoc-usage (concat docstring origdoc) usage))))
107
108(defvar advice--docstring
109 ;; Can't eval-when-compile nor use defconst because it then gets pure-copied,
110 ;; which drops the text-properties.
111 ;;(eval-when-compile
112 (propertize "Advised function"
113 'dynamic-docstring-function #'advice--make-docstring)) ;; )
114
1668ea90
SM
115(defun advice-eval-interactive-spec (spec)
116 "Evaluate the interactive spec SPEC."
117 (cond
118 ((stringp spec)
119 ;; There's no direct access to the C code (in call-interactively) that
120 ;; processes those specs, but that shouldn't stop us, should it?
121 ;; FIXME: Despite appearances, this is not faithful: SPEC and
122 ;; (advice-eval-interactive-spec SPEC) will behave subtly differently w.r.t
123 ;; command-history (and maybe a few other details).
124 (call-interactively `(lambda (&rest args) (interactive ,spec) args)))
125 ;; ((functionp spec) (funcall spec))
126 (t (eval spec))))
127
231d8498 128(defun advice--make-interactive-form (function main)
231d8498
SM
129 ;; TODO: make it so that interactive spec can be a constant which
130 ;; dynamically checks the advice--car/cdr to do its job.
1668ea90
SM
131 ;; For that, advice-eval-interactive-spec needs to be more faithful.
132 ;; FIXME: The calls to interactive-form below load autoloaded functions
133 ;; too eagerly.
134 (let ((fspec (cadr (interactive-form function))))
47f01a8a 135 (when (eq 'function (car-safe fspec)) ;; Macroexpanded lambda?
1668ea90
SM
136 (setq fspec (nth 1 fspec)))
137 (if (functionp fspec)
138 `(funcall ',fspec
139 ',(cadr (interactive-form main)))
231d8498 140 (cadr (or (interactive-form function)
1668ea90 141 (interactive-form main))))))
231d8498
SM
142
143(defsubst advice--make-1 (byte-code stack-depth function main props)
144 "Build a function value that adds FUNCTION to MAIN."
145 (let ((adv-sig (gethash main advertised-signature-table))
146 (advice
147 (apply #'make-byte-code 128 byte-code
148 (vector #'apply function main props) stack-depth
149 advice--docstring
150 (when (or (commandp function) (commandp main))
151 (list (advice--make-interactive-form
152 function main))))))
153 (when adv-sig (puthash advice adv-sig advertised-signature-table))
154 advice))
155
156(defun advice--make (where function main props)
157 "Build a function value that adds FUNCTION to MAIN at WHERE.
158WHERE is a symbol to select an entry in `advice--where-alist'."
159 (let ((desc (assq where advice--where-alist)))
160 (unless desc (error "Unknown add-function location `%S'" where))
161 (advice--make-1 (nth 1 desc) (nth 2 desc)
162 function main props)))
163
dabefae5 164(defun advice--member-p (function name definition)
231d8498
SM
165 (let ((found nil))
166 (while (and (not found) (advice--p definition))
167 (if (or (equal function (advice--car definition))
dabefae5
SM
168 (when name
169 (equal name (cdr (assq 'name (advice--props definition))))))
c67c0839 170 (setq found definition)
231d8498
SM
171 (setq definition (advice--cdr definition))))
172 found))
173
a731fc1b 174(defun advice--tweak (flist tweaker)
231d8498 175 (if (not (advice--p flist))
a731fc1b 176 (funcall tweaker nil flist nil)
231d8498 177 (let ((first (advice--car flist))
a731fc1b 178 (rest (advice--cdr flist))
231d8498 179 (props (advice--props flist)))
cb9c0a53
SM
180 (let ((val (funcall tweaker first rest props)))
181 (if val (car val)
a731fc1b
SM
182 (let ((nrest (advice--tweak rest tweaker)))
183 (if (eq rest nrest) flist
184 (advice--make-1 (aref flist 1) (aref flist 3)
cb9c0a53 185 first nrest props))))))))
a731fc1b
SM
186
187;;;###autoload
188(defun advice--remove-function (flist function)
189 (advice--tweak flist
190 (lambda (first rest props)
cb9c0a53
SM
191 (cond ((not first) rest)
192 ((or (equal function first)
a731fc1b 193 (equal function (cdr (assq 'name props))))
cb9c0a53 194 (list rest))))))
231d8498 195
1d44e9dc
SM
196(defvar advice--buffer-local-function-sample nil
197 "keeps an example of the special \"run the default value\" functions.
198These functions play the same role as t in buffer-local hooks, and to recognize
199them, we keep a sample here against which to compare. Each instance is
200different, but `function-equal' will hopefully ignore those differences.")
a61428c4
SM
201
202(defun advice--set-buffer-local (var val)
203 (if (function-equal val advice--buffer-local-function-sample)
204 (kill-local-variable var)
205 (set (make-local-variable var) val)))
206
207;;;###autoload
208(defun advice--buffer-local (var)
209 "Buffer-local value of VAR, presumed to contain a function."
210 (declare (gv-setter advice--set-buffer-local))
211 (if (local-variable-p var) (symbol-value var)
212 (setq advice--buffer-local-function-sample
1d44e9dc 213 ;; This function acts like the t special value in buffer-local hooks.
a61428c4
SM
214 (lambda (&rest args) (apply (default-value var) args)))))
215
231d8498
SM
216;;;###autoload
217(defmacro add-function (where place function &optional props)
218 ;; TODO:
231d8498
SM
219 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
220 ;; and tracing want to stay first.
a61428c4 221 ;; - maybe let `where' specify some kind of predicate and use it
231d8498 222 ;; to implement things like mode-local or eieio-defmethod.
a61428c4
SM
223 ;; Of course, that only makes sense if the predicates of all advices can
224 ;; be combined and made more efficient.
231d8498
SM
225 ;; :before is like a normal add-hook on a normal hook.
226 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
227 ;; :before-until is like add-hook on run-hook-with-args-until-success.
228 ;; Same with :after-* but for (add-hook ... 'append).
229 "Add a piece of advice on the function stored at PLACE.
230FUNCTION describes the code to add. WHERE describes where to add it.
231WHERE can be explained by showing the resulting new function, as the
232result of combining FUNCTION and the previous value of PLACE, which we
233call OLDFUN here:
234`:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
235`:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
236`:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
bcd7a0a4 237`:override' (lambda (&rest r) (apply FUNCTION r))
231d8498
SM
238`:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
239`:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
240`:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
241`:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
d36ed1c8
SM
242`:filter-args' (lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))
243`:filter-return'(lambda (&rest r) (funcall FUNCTION (apply OLDFUN r)))
231d8498
SM
244If FUNCTION was already added, do nothing.
245PROPS is an alist of additional properties, among which the following have
246a special meaning:
1668ea90
SM
247- `name': a string or symbol. It can be used to refer to this piece of advice.
248
36c0a301
SM
249If PLACE is a simple variable, only its global value will be affected.
250Use (local 'VAR) if you want to apply FUNCTION to VAR buffer-locally.
a61428c4 251
1668ea90
SM
252If one of FUNCTION or OLDFUN is interactive, then the resulting function
253is also interactive. There are 3 cases:
254- FUNCTION is not interactive: the interactive spec of OLDFUN is used.
255- The interactive spec of FUNCTION is itself a function: it should take one
256 argument (the interactive spec of OLDFUN, which it can pass to
257 `advice-eval-interactive-spec') and return the list of arguments to use.
258- Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
231d8498 259 (declare (debug t)) ;;(indent 2)
a61428c4
SM
260 (cond ((eq 'local (car-safe place))
261 (setq place `(advice--buffer-local ,@(cdr place))))
262 ((symbolp place)
36c0a301 263 (setq place `(default-value ',place))))
231d8498
SM
264 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
265
266;;;###autoload
267(defun advice--add-function (where ref function props)
c67c0839
SM
268 (let ((a (advice--member-p function (cdr (assq 'name props))
269 (gv-deref ref))))
270 (when a
271 ;; The advice is already present. Remove the old one, first.
272 (setf (gv-deref ref)
273 (advice--remove-function (gv-deref ref) (advice--car a))))
231d8498
SM
274 (setf (gv-deref ref)
275 (advice--make where function (gv-deref ref) props))))
276
bcd7a0a4 277;;;###autoload
231d8498
SM
278(defmacro remove-function (place function)
279 "Remove the FUNCTION piece of advice from PLACE.
280If FUNCTION was not added to PLACE, do nothing.
281Instead of FUNCTION being the actual function, it can also be the `name'
282of the piece of advice."
283 (declare (debug t))
a61428c4
SM
284 (cond ((eq 'local (car-safe place))
285 (setq place `(advice--buffer-local ,@(cdr place))))
286 ((symbolp place)
287 (error "Use (default-value '%S) or (local '%S)" place place)))
231d8498
SM
288 (gv-letplace (getter setter) place
289 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
290 `(unless (eq ,new ,getter) ,(funcall setter new)))))
291
1d44e9dc
SM
292(defun advice-function-mapc (f function-def)
293 "Apply F to every advice function in FUNCTION-DEF.
294F is called with two arguments: the function that was added, and the
295properties alist that was specified when it was added."
296 (while (advice--p function-def)
297 (funcall f (advice--car function-def) (advice--props function-def))
298 (setq function-def (advice--cdr function-def))))
299
300(defun advice-function-member-p (advice function-def)
301 "Return non-nil if ADVICE is already in FUNCTION-DEF.
302Instead of ADVICE being the actual function, it can also be the `name'
303of the piece of advice."
304 (advice--member-p advice advice function-def))
305
231d8498
SM
306;;;; Specific application of add-function to `symbol-function' for advice.
307
308(defun advice--subst-main (old new)
a731fc1b
SM
309 (advice--tweak old
310 (lambda (first _rest _props) (if (not first) new))))
231d8498 311
413d4689
SM
312(defun advice--normalize (symbol def)
313 (cond
314 ((special-form-p def)
315 ;; Not worth the trouble trying to handle this, I think.
1d44e9dc 316 (error "Advice impossible: %S is a special form" symbol))
671d5c16
SM
317 ((and (symbolp def) (macrop def))
318 (let ((newval `(macro . ,(lambda (&rest r) (macroexpand `(,def . ,r))))))
1d44e9dc 319 (put symbol 'advice--saved-rewrite (cons def (cdr newval)))
413d4689
SM
320 newval))
321 ;; `f' might be a pure (hence read-only) cons!
322 ((and (eq 'macro (car-safe def))
323 (not (ignore-errors (setcdr def (cdr def)) t)))
324 (cons 'macro (cdr def)))
325 (t def)))
326
327(defsubst advice--strip-macro (x)
328 (if (eq 'macro (car-safe x)) (cdr x) x))
329
1d44e9dc
SM
330(defun advice--symbol-function (symbol)
331 ;; The value conceptually stored in `symbol-function' is split into two
332 ;; parts:
333 ;; - the normal function definition.
334 ;; - the list of advice applied to it.
335 ;; `advice--symbol-function' is intended to return the second part (i.e. the
336 ;; list of advice, which includes a hole at the end which typically holds the
337 ;; first part, but this function doesn't care much which value is found
338 ;; there).
339 ;; In the "normal" state both parts are combined into a single value stored
340 ;; in the "function slot" of the symbol. But the way they are combined is
341 ;; different depending on whether the definition is a function or a macro.
342 ;; Also if the function definition is nil (i.e. unbound) or is an autoload,
343 ;; the second part is stashed away temporarily in the `advice--pending'
344 ;; symbol property.
345 (or (get symbol 'advice--pending)
346 (advice--strip-macro (symbol-function symbol))))
347
231d8498 348(defun advice--defalias-fset (fsetfun symbol newdef)
1d44e9dc 349 (unless fsetfun (setq fsetfun #'fset))
413d4689
SM
350 (when (get symbol 'advice--saved-rewrite)
351 (put symbol 'advice--saved-rewrite nil))
352 (setq newdef (advice--normalize symbol newdef))
671d5c16 353 (let ((oldadv (advice--symbol-function symbol)))
539f75f4
SM
354 (if (and newdef (not (autoloadp newdef)))
355 (let* ((snewdef (advice--strip-macro newdef))
356 (snewadv (advice--subst-main oldadv snewdef)))
357 (put symbol 'advice--pending nil)
1d44e9dc 358 (funcall fsetfun symbol
539f75f4
SM
359 (if (eq snewdef newdef) snewadv (cons 'macro snewadv))))
360 (unless (eq oldadv (get symbol 'advice--pending))
361 (put symbol 'advice--pending (advice--subst-main oldadv nil)))
1d44e9dc 362 (funcall fsetfun symbol newdef))))
231d8498
SM
363
364
365;;;###autoload
366(defun advice-add (symbol where function &optional props)
367 "Like `add-function' but for the function named SYMBOL.
368Contrary to `add-function', this will properly handle the cases where SYMBOL
369is defined as a macro, alias, command, ..."
370 ;; TODO:
371 ;; - record the advice location, to display in describe-function.
372 ;; - change all defadvice in lisp/**/*.el.
231d8498 373 ;; - obsolete advice.el.
539f75f4 374 (let* ((f (symbol-function symbol))
413d4689 375 (nf (advice--normalize symbol f)))
1d44e9dc 376 (unless (eq f nf) (fset symbol nf))
231d8498 377 (add-function where (cond
413d4689 378 ((eq (car-safe nf) 'macro) (cdr nf))
1668ea90
SM
379 ;; Reasons to delay installation of the advice:
380 ;; - If the function is not yet defined, installing
381 ;; the advice would affect `fboundp'ness.
382 ;; - If it's an autoloaded command,
383 ;; advice--make-interactive-form would end up
384 ;; loading the command eagerly.
385 ;; - `autoload' does nothing if the function is
386 ;; not an autoload or undefined.
387 ((or (not nf) (autoloadp nf))
231d8498
SM
388 (get symbol 'advice--pending))
389 (t (symbol-function symbol)))
390 function props)
391 (add-function :around (get symbol 'defalias-fset-function)
392 #'advice--defalias-fset))
393 nil)
394
395;;;###autoload
396(defun advice-remove (symbol function)
397 "Like `remove-function' but for the function named SYMBOL.
539f75f4
SM
398Contrary to `remove-function', this also works when SYMBOL is a macro
399or an autoload and it preserves `fboundp'.
231d8498
SM
400Instead of the actual function to remove, FUNCTION can also be the `name'
401of the piece of advice."
539f75f4 402 (let ((f (symbol-function symbol)))
1d44e9dc
SM
403 (remove-function (cond ;This is `advice--symbol-function' but as a "place".
404 ((get symbol 'advice--pending)
405 (get symbol 'advice--pending))
406 ((eq (car-safe f) 'macro) (cdr f))
407 (t (symbol-function symbol)))
539f75f4 408 function)
671d5c16 409 (unless (advice--p (advice--symbol-function symbol))
539f75f4
SM
410 ;; Not advised any more.
411 (remove-function (get symbol 'defalias-fset-function)
412 #'advice--defalias-fset)
1d44e9dc
SM
413 (let ((asr (get symbol 'advice--saved-rewrite)))
414 (and asr (eq (cdr-safe (symbol-function symbol))
415 (cdr asr))
416 (fset symbol (car (get symbol 'advice--saved-rewrite)))))))
539f75f4
SM
417 nil)
418
1d44e9dc
SM
419(defun advice-mapc (fun symbol)
420 "Apply FUN to every advice function in SYMBOL.
539f75f4
SM
421FUN is called with a two arguments: the function that was added, and the
422properties alist that was specified when it was added."
1d44e9dc 423 (advice-function-mapc fun (advice--symbol-function symbol)))
231d8498
SM
424
425;;;###autoload
1d44e9dc
SM
426(defun advice-member-p (advice symbol)
427 "Return non-nil if ADVICE has been added to SYMBOL.
413d4689 428Instead of ADVICE being the actual function, it can also be the `name'
231d8498 429of the piece of advice."
1d44e9dc 430 (advice-function-member-p advice (advice--symbol-function symbol)))
231d8498 431
23ba2705
SM
432;; When code is advised, called-interactively-p needs to be taught to skip
433;; the advising frames.
434;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
435;; done from the advised function if the deepest advice is an around advice!
436;; In other cases (calls from an advice or calls from the advised function when
437;; the deepest advice is not an around advice), it should hopefully get
438;; it right.
439(add-hook 'called-interactively-p-functions
440 #'advice--called-interactively-skip)
441(defun advice--called-interactively-skip (origi frame1 frame2)
442 (let* ((i origi)
443 (get-next-frame
444 (lambda ()
445 (setq frame1 frame2)
7ced0d04 446 (setq frame2 (backtrace-frame i #'called-interactively-p))
23ba2705
SM
447 ;; (message "Advice Frame %d = %S" i frame2)
448 (setq i (1+ i)))))
449 (when (and (eq (nth 1 frame2) 'apply)
450 (progn
451 (funcall get-next-frame)
452 (advice--p (indirect-function (nth 1 frame2)))))
453 (funcall get-next-frame)
454 ;; If we now have the symbol, this was the head advice and
455 ;; we're done.
456 (while (advice--p (nth 1 frame1))
457 ;; This was an inner advice called from some earlier advice.
458 ;; The stack frames look different depending on the particular
459 ;; kind of the earlier advice.
460 (let ((inneradvice (nth 1 frame1)))
461 (if (and (eq (nth 1 frame2) 'apply)
462 (progn
463 (funcall get-next-frame)
464 (advice--p (indirect-function
465 (nth 1 frame2)))))
466 ;; The earlier advice was something like a before/after
467 ;; advice where the "next" code is called directly by the
468 ;; advice--p object.
469 (funcall get-next-frame)
470 ;; It's apparently an around advice, where the "next" is
471 ;; called by the body of the advice in any way it sees fit,
472 ;; so we need to skip the frames of that body.
473 (while
474 (progn
475 (funcall get-next-frame)
476 (not (and (eq (nth 1 frame2) 'apply)
477 (eq (nth 3 frame2) inneradvice)))))
478 (funcall get-next-frame)
479 (funcall get-next-frame))))
480 (- i origi 1))))
481
231d8498
SM
482
483(provide 'nadvice)
484;;; nadvice.el ends here