* net/tramp-adb.el (tramp-adb-file-name-handler-alist): Remove
[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
26;; bells ans whistles. It comes in 2 parts:
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)
44 (:after-until "\300\302\002\"\206\013\000\300\301\002\"\207" 4)
45 (:after-while "\300\302\002\"\205\013\000\300\301\002\"\207" 4)
46 (:before-until "\300\301\002\"\206\013\000\300\302\002\"\207" 4)
47 (:before-while "\300\301\002\"\205\013\000\300\302\002\"\207" 4))
48 "List of descriptions of how to add a function.
49Each element has the form (WHERE BYTECODE STACK) where:
50 WHERE is a keyword indicating where the function is added.
51 BYTECODE is the corresponding byte-code that will be used.
52 STACK is the amount of stack space needed by the byte-code.")
53
54(defvar advice--bytecodes (mapcar #'cadr advice--where-alist))
55
56(defun advice--p (object)
57 (and (byte-code-function-p object)
58 (eq 128 (aref object 0))
59 (memq (length object) '(5 6))
60 (memq (aref object 1) advice--bytecodes)
61 (eq #'apply (aref (aref object 2) 0))))
62
63(defsubst advice--car (f) (aref (aref f 2) 1))
64(defsubst advice--cdr (f) (aref (aref f 2) 2))
65(defsubst advice--props (f) (aref (aref f 2) 3))
66
67(defun advice--make-docstring (_string function)
68 "Build the raw doc-string of SYMBOL, presumably advised."
69 (let ((flist (indirect-function function))
70 (docstring nil))
71 (if (eq 'macro (car-safe flist)) (setq flist (cdr flist)))
72 (while (advice--p flist)
73 (let ((bytecode (aref flist 1))
74 (where nil))
75 (dolist (elem advice--where-alist)
76 (if (eq bytecode (cadr elem)) (setq where (car elem))))
77 (setq docstring
78 (concat
79 docstring
80 (propertize (format "%s advice: " where)
81 'face 'warning)
82 (let ((fun (advice--car flist)))
83 (if (symbolp fun) (format "`%S'" fun)
84 (let* ((name (cdr (assq 'name (advice--props flist))))
85 (doc (documentation fun t))
86 (usage (help-split-fundoc doc function)))
87 (if usage (setq doc (cdr usage)))
88 (if name
89 (if doc
90 (format "%s\n%s" name doc)
91 (format "%s" name))
92 (or doc "No documentation")))))
93 "\n")))
94 (setq flist (advice--cdr flist)))
95 (if docstring (setq docstring (concat docstring "\n")))
96 (let* ((origdoc (unless (eq function flist) ;Avoid inf-loops.
97 (documentation flist t)))
98 (usage (help-split-fundoc origdoc function)))
99 (setq usage (if (null usage)
100 (let ((arglist (help-function-arglist flist)))
101 (format "%S" (help-make-usage function arglist)))
102 (setq origdoc (cdr usage)) (car usage)))
103 (help-add-fundoc-usage (concat docstring origdoc) usage))))
104
105(defvar advice--docstring
106 ;; Can't eval-when-compile nor use defconst because it then gets pure-copied,
107 ;; which drops the text-properties.
108 ;;(eval-when-compile
109 (propertize "Advised function"
110 'dynamic-docstring-function #'advice--make-docstring)) ;; )
111
1668ea90
SM
112(defun advice-eval-interactive-spec (spec)
113 "Evaluate the interactive spec SPEC."
114 (cond
115 ((stringp spec)
116 ;; There's no direct access to the C code (in call-interactively) that
117 ;; processes those specs, but that shouldn't stop us, should it?
118 ;; FIXME: Despite appearances, this is not faithful: SPEC and
119 ;; (advice-eval-interactive-spec SPEC) will behave subtly differently w.r.t
120 ;; command-history (and maybe a few other details).
121 (call-interactively `(lambda (&rest args) (interactive ,spec) args)))
122 ;; ((functionp spec) (funcall spec))
123 (t (eval spec))))
124
231d8498 125(defun advice--make-interactive-form (function main)
231d8498
SM
126 ;; TODO: make it so that interactive spec can be a constant which
127 ;; dynamically checks the advice--car/cdr to do its job.
1668ea90
SM
128 ;; For that, advice-eval-interactive-spec needs to be more faithful.
129 ;; FIXME: The calls to interactive-form below load autoloaded functions
130 ;; too eagerly.
131 (let ((fspec (cadr (interactive-form function))))
47f01a8a 132 (when (eq 'function (car-safe fspec)) ;; Macroexpanded lambda?
1668ea90
SM
133 (setq fspec (nth 1 fspec)))
134 (if (functionp fspec)
135 `(funcall ',fspec
136 ',(cadr (interactive-form main)))
231d8498 137 (cadr (or (interactive-form function)
1668ea90 138 (interactive-form main))))))
231d8498
SM
139
140(defsubst advice--make-1 (byte-code stack-depth function main props)
141 "Build a function value that adds FUNCTION to MAIN."
142 (let ((adv-sig (gethash main advertised-signature-table))
143 (advice
144 (apply #'make-byte-code 128 byte-code
145 (vector #'apply function main props) stack-depth
146 advice--docstring
147 (when (or (commandp function) (commandp main))
148 (list (advice--make-interactive-form
149 function main))))))
150 (when adv-sig (puthash advice adv-sig advertised-signature-table))
151 advice))
152
153(defun advice--make (where function main props)
154 "Build a function value that adds FUNCTION to MAIN at WHERE.
155WHERE is a symbol to select an entry in `advice--where-alist'."
156 (let ((desc (assq where advice--where-alist)))
157 (unless desc (error "Unknown add-function location `%S'" where))
158 (advice--make-1 (nth 1 desc) (nth 2 desc)
159 function main props)))
160
161(defun advice--member-p (function definition)
162 (let ((found nil))
163 (while (and (not found) (advice--p definition))
164 (if (or (equal function (advice--car definition))
165 (equal function (cdr (assq 'name (advice--props definition)))))
166 (setq found t)
167 (setq definition (advice--cdr definition))))
168 found))
169
170;;;###autoload
171(defun advice--remove-function (flist function)
172 (if (not (advice--p flist))
173 flist
174 (let ((first (advice--car flist))
175 (props (advice--props flist)))
176 (if (or (equal function first)
177 (equal function (cdr (assq 'name props))))
178 (advice--cdr flist)
179 (let* ((rest (advice--cdr flist))
180 (nrest (advice--remove-function rest function)))
181 (if (eq rest nrest) flist
182 (advice--make-1 (aref flist 1) (aref flist 3)
183 first nrest props)))))))
184
a61428c4
SM
185(defvar advice--buffer-local-function-sample nil)
186
187(defun advice--set-buffer-local (var val)
188 (if (function-equal val advice--buffer-local-function-sample)
189 (kill-local-variable var)
190 (set (make-local-variable var) val)))
191
192;;;###autoload
193(defun advice--buffer-local (var)
194 "Buffer-local value of VAR, presumed to contain a function."
195 (declare (gv-setter advice--set-buffer-local))
196 (if (local-variable-p var) (symbol-value var)
197 (setq advice--buffer-local-function-sample
198 (lambda (&rest args) (apply (default-value var) args)))))
199
231d8498
SM
200;;;###autoload
201(defmacro add-function (where place function &optional props)
202 ;; TODO:
231d8498
SM
203 ;; - obsolete with-wrapper-hook (mostly requires buffer-local support).
204 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
205 ;; and tracing want to stay first.
a61428c4 206 ;; - maybe let `where' specify some kind of predicate and use it
231d8498 207 ;; to implement things like mode-local or eieio-defmethod.
a61428c4
SM
208 ;; Of course, that only makes sense if the predicates of all advices can
209 ;; be combined and made more efficient.
231d8498
SM
210 ;; :before is like a normal add-hook on a normal hook.
211 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
212 ;; :before-until is like add-hook on run-hook-with-args-until-success.
213 ;; Same with :after-* but for (add-hook ... 'append).
214 "Add a piece of advice on the function stored at PLACE.
215FUNCTION describes the code to add. WHERE describes where to add it.
216WHERE can be explained by showing the resulting new function, as the
217result of combining FUNCTION and the previous value of PLACE, which we
218call OLDFUN here:
219`:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
220`:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
221`:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
222`:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
223`:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
224`:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
225`:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
226If FUNCTION was already added, do nothing.
227PROPS is an alist of additional properties, among which the following have
228a special meaning:
1668ea90
SM
229- `name': a string or symbol. It can be used to refer to this piece of advice.
230
a61428c4
SM
231PLACE cannot be a simple variable. Instead it should either be
232\(default-value 'VAR) or (local 'VAR) depending on whether FUNCTION
233should be applied to VAR buffer-locally or globally.
234
1668ea90
SM
235If one of FUNCTION or OLDFUN is interactive, then the resulting function
236is also interactive. There are 3 cases:
237- FUNCTION is not interactive: the interactive spec of OLDFUN is used.
238- The interactive spec of FUNCTION is itself a function: it should take one
239 argument (the interactive spec of OLDFUN, which it can pass to
240 `advice-eval-interactive-spec') and return the list of arguments to use.
241- Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
231d8498 242 (declare (debug t)) ;;(indent 2)
a61428c4
SM
243 (cond ((eq 'local (car-safe place))
244 (setq place `(advice--buffer-local ,@(cdr place))))
245 ((symbolp place)
246 (error "Use (default-value '%S) or (local '%S)" place place)))
231d8498
SM
247 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
248
249;;;###autoload
250(defun advice--add-function (where ref function props)
251 (unless (advice--member-p function (gv-deref ref))
252 (setf (gv-deref ref)
253 (advice--make where function (gv-deref ref) props))))
254
255(defmacro remove-function (place function)
256 "Remove the FUNCTION piece of advice from PLACE.
257If FUNCTION was not added to PLACE, do nothing.
258Instead of FUNCTION being the actual function, it can also be the `name'
259of the piece of advice."
260 (declare (debug t))
a61428c4
SM
261 (cond ((eq 'local (car-safe place))
262 (setq place `(advice--buffer-local ,@(cdr place))))
263 ((symbolp place)
264 (error "Use (default-value '%S) or (local '%S)" place place)))
231d8498
SM
265 (gv-letplace (getter setter) place
266 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
267 `(unless (eq ,new ,getter) ,(funcall setter new)))))
268
269;;;; Specific application of add-function to `symbol-function' for advice.
270
271(defun advice--subst-main (old new)
272 (if (not (advice--p old))
273 new
274 (let* ((first (advice--car old))
275 (rest (advice--cdr old))
276 (props (advice--props old))
277 (nrest (advice--subst-main rest new)))
278 (if (equal rest nrest) old
279 (advice--make-1 (aref old 1) (aref old 3)
280 first nrest props)))))
281
413d4689
SM
282(defun advice--normalize (symbol def)
283 (cond
284 ((special-form-p def)
285 ;; Not worth the trouble trying to handle this, I think.
a77b8d5e 286 (error "advice-add failure: %S is a special form" symbol))
413d4689
SM
287 ((and (symbolp def)
288 (eq 'macro (car-safe (ignore-errors (indirect-function def)))))
289 (let ((newval (cons 'macro (cdr (indirect-function def)))))
290 (put symbol 'advice--saved-rewrite (cons def newval))
291 newval))
292 ;; `f' might be a pure (hence read-only) cons!
293 ((and (eq 'macro (car-safe def))
294 (not (ignore-errors (setcdr def (cdr def)) t)))
295 (cons 'macro (cdr def)))
296 (t def)))
297
298(defsubst advice--strip-macro (x)
299 (if (eq 'macro (car-safe x)) (cdr x) x))
300
231d8498 301(defun advice--defalias-fset (fsetfun symbol newdef)
413d4689
SM
302 (when (get symbol 'advice--saved-rewrite)
303 (put symbol 'advice--saved-rewrite nil))
304 (setq newdef (advice--normalize symbol newdef))
305 (let* ((olddef (advice--strip-macro
306 (if (fboundp symbol) (symbol-function symbol))))
231d8498
SM
307 (oldadv
308 (cond
413d4689
SM
309 ((null (get symbol 'advice--pending))
310 (or olddef
311 (progn
312 (message "Delayed advice activation failed for %s: no data"
313 symbol)
314 nil)))
315 ((or (not olddef) (autoloadp olddef))
316 (prog1 (get symbol 'advice--pending)
317 (put symbol 'advice--pending nil)))
231d8498
SM
318 (t (message "Dropping left-over advice--pending for %s" symbol)
319 (put symbol 'advice--pending nil)
320 olddef))))
413d4689
SM
321 (let* ((snewdef (advice--strip-macro newdef))
322 (snewadv (advice--subst-main oldadv snewdef)))
323 (funcall (or fsetfun #'fset) symbol
324 (if (eq snewdef newdef) snewadv (cons 'macro snewadv))))))
231d8498
SM
325
326
327;;;###autoload
328(defun advice-add (symbol where function &optional props)
329 "Like `add-function' but for the function named SYMBOL.
330Contrary to `add-function', this will properly handle the cases where SYMBOL
331is defined as a macro, alias, command, ..."
332 ;; TODO:
333 ;; - record the advice location, to display in describe-function.
334 ;; - change all defadvice in lisp/**/*.el.
335 ;; - rewrite advice.el on top of this.
336 ;; - obsolete advice.el.
413d4689
SM
337 (let* ((f (and (fboundp symbol) (symbol-function symbol)))
338 (nf (advice--normalize symbol f)))
339 (unless (eq f nf) ;; Most importantly, if nf == nil!
340 (fset symbol nf))
231d8498 341 (add-function where (cond
413d4689 342 ((eq (car-safe nf) 'macro) (cdr nf))
1668ea90
SM
343 ;; Reasons to delay installation of the advice:
344 ;; - If the function is not yet defined, installing
345 ;; the advice would affect `fboundp'ness.
346 ;; - If it's an autoloaded command,
347 ;; advice--make-interactive-form would end up
348 ;; loading the command eagerly.
349 ;; - `autoload' does nothing if the function is
350 ;; not an autoload or undefined.
351 ((or (not nf) (autoloadp nf))
231d8498
SM
352 (get symbol 'advice--pending))
353 (t (symbol-function symbol)))
354 function props)
355 (add-function :around (get symbol 'defalias-fset-function)
356 #'advice--defalias-fset))
357 nil)
358
359;;;###autoload
360(defun advice-remove (symbol function)
361 "Like `remove-function' but for the function named SYMBOL.
362Contrary to `remove-function', this will work also when SYMBOL is a macro
363and it will not signal an error if SYMBOL is not `fboundp'.
364Instead of the actual function to remove, FUNCTION can also be the `name'
365of the piece of advice."
366 (when (fboundp symbol)
367 (let ((f (symbol-function symbol)))
368 ;; Can't use the `if' place here, because the body is too large,
369 ;; resulting in use of code that only works with lexical-scoping.
370 (remove-function (if (eq (car-safe f) 'macro)
371 (cdr f)
372 (symbol-function symbol))
373 function)
374 (unless (advice--p
375 (if (eq (car-safe f) 'macro) (cdr f) (symbol-function symbol)))
413d4689 376 ;; Not advised any more.
231d8498
SM
377 (remove-function (get symbol 'defalias-fset-function)
378 #'advice--defalias-fset)
379 (if (eq (symbol-function symbol)
380 (cdr (get symbol 'advice--saved-rewrite)))
381 (fset symbol (car (get symbol 'advice--saved-rewrite))))))
382 nil))
383
384;; (defun advice-mapc (fun symbol)
385;; "Apply FUN to every function added as advice to SYMBOL.
386;; FUN is called with a two arguments: the function that was added, and the
387;; properties alist that was specified when it was added."
388;; (let ((def (or (get symbol 'advice--pending)
389;; (if (fboundp symbol) (symbol-function symbol)))))
390;; (while (advice--p def)
391;; (funcall fun (advice--car def) (advice--props def))
392;; (setq def (advice--cdr def)))))
393
394;;;###autoload
413d4689
SM
395(defun advice-member-p (advice function-name)
396 "Return non-nil if ADVICE has been added to FUNCTION-NAME.
397Instead of ADVICE being the actual function, it can also be the `name'
231d8498 398of the piece of advice."
413d4689
SM
399 (advice--member-p advice
400 (or (get function-name 'advice--pending)
401 (advice--strip-macro
402 (if (fboundp function-name)
403 (symbol-function function-name))))))
231d8498 404
23ba2705
SM
405;; When code is advised, called-interactively-p needs to be taught to skip
406;; the advising frames.
407;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
408;; done from the advised function if the deepest advice is an around advice!
409;; In other cases (calls from an advice or calls from the advised function when
410;; the deepest advice is not an around advice), it should hopefully get
411;; it right.
412(add-hook 'called-interactively-p-functions
413 #'advice--called-interactively-skip)
414(defun advice--called-interactively-skip (origi frame1 frame2)
415 (let* ((i origi)
416 (get-next-frame
417 (lambda ()
418 (setq frame1 frame2)
419 (setq frame2 (internal--called-interactively-p--get-frame i))
420 ;; (message "Advice Frame %d = %S" i frame2)
421 (setq i (1+ i)))))
422 (when (and (eq (nth 1 frame2) 'apply)
423 (progn
424 (funcall get-next-frame)
425 (advice--p (indirect-function (nth 1 frame2)))))
426 (funcall get-next-frame)
427 ;; If we now have the symbol, this was the head advice and
428 ;; we're done.
429 (while (advice--p (nth 1 frame1))
430 ;; This was an inner advice called from some earlier advice.
431 ;; The stack frames look different depending on the particular
432 ;; kind of the earlier advice.
433 (let ((inneradvice (nth 1 frame1)))
434 (if (and (eq (nth 1 frame2) 'apply)
435 (progn
436 (funcall get-next-frame)
437 (advice--p (indirect-function
438 (nth 1 frame2)))))
439 ;; The earlier advice was something like a before/after
440 ;; advice where the "next" code is called directly by the
441 ;; advice--p object.
442 (funcall get-next-frame)
443 ;; It's apparently an around advice, where the "next" is
444 ;; called by the body of the advice in any way it sees fit,
445 ;; so we need to skip the frames of that body.
446 (while
447 (progn
448 (funcall get-next-frame)
449 (not (and (eq (nth 1 frame2) 'apply)
450 (eq (nth 3 frame2) inneradvice)))))
451 (funcall get-next-frame)
452 (funcall get-next-frame))))
453 (- i origi 1))))
454
231d8498
SM
455
456(provide 'nadvice)
457;;; nadvice.el ends here