1 ;;; nadvice.el --- Light-weight advice primitives for Elisp functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2012-2013 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: extensions, lisp, tools
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.
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.
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/>.
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 and whistles. It comes in 2 parts:
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
31 ;; This part provides mainly 2 macros: `add-function' and `remove-function'.
33 ;; - The second part provides `advice-add' and `advice-remove' which are
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'.
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 (:override
"\300\301\x02\"\207" 4)
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)
48 (:before-while
"\300\301\002\"\205\013\000\300\302\002\"\207" 4)
49 (:filter-args
"\300\302\301\x03!\"\207" 5)
50 (:filter-return
"\301\300\302\x03\"!\207" 5))
51 "List of descriptions of how to add a function.
52 Each 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.")
57 (defvar advice--bytecodes
(mapcar #'cadr advice--where-alist
))
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))))
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))
70 (defun advice--make-docstring (_string function
)
71 "Build the raw doc-string of SYMBOL, presumably advised."
72 (let ((flist (indirect-function function
))
74 (if (eq 'macro
(car-safe flist
)) (setq flist
(cdr flist
)))
75 (while (advice--p flist
)
76 (let ((bytecode (aref flist
1))
78 (dolist (elem advice--where-alist
)
79 (if (eq bytecode
(cadr elem
)) (setq where
(car elem
))))
83 (propertize (format "%s advice: " where
)
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
)))
93 (format "%s\n%s" name doc
)
95 (or doc
"No documentation")))))
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
))))
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.
112 (propertize "Advised function"
113 'dynamic-docstring-function
#'advice--make-docstring
)) ;; )
115 (defun advice-eval-interactive-spec (spec)
116 "Evaluate the interactive spec 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))
128 (defun advice--make-interactive-form (function main
)
129 ;; TODO: make it so that interactive spec can be a constant which
130 ;; dynamically checks the advice--car/cdr to do its job.
131 ;; For that, advice-eval-interactive-spec needs to be more faithful.
132 ;; FIXME: The calls to interactive-form below load autoloaded functions
134 (let ((fspec (cadr (interactive-form function
))))
135 (when (eq 'function
(car-safe fspec
)) ;; Macroexpanded lambda?
136 (setq fspec
(nth 1 fspec
)))
137 (if (functionp fspec
)
139 ',(cadr (interactive-form main
)))
140 (cadr (or (interactive-form function
)
141 (interactive-form main
))))))
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
))
147 (apply #'make-byte-code
128 byte-code
148 (vector #'apply function main props
) stack-depth
150 (when (or (commandp function
) (commandp main
))
151 (list (advice--make-interactive-form
153 (when adv-sig
(puthash advice adv-sig advertised-signature-table
))
156 (defun advice--make (where function main props
)
157 "Build a function value that adds FUNCTION to MAIN at WHERE.
158 WHERE 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
)))
164 (defun advice--member-p (function name definition
)
166 (while (and (not found
) (advice--p definition
))
167 (if (or (equal function
(advice--car definition
))
169 (equal name
(cdr (assq 'name
(advice--props definition
))))))
170 (setq found definition
)
171 (setq definition
(advice--cdr definition
))))
174 (defun advice--tweak (flist tweaker
)
175 (if (not (advice--p flist
))
176 (funcall tweaker nil flist nil
)
177 (let ((first (advice--car flist
))
178 (rest (advice--cdr flist
))
179 (props (advice--props flist
)))
180 (let ((val (funcall tweaker first rest props
)))
182 (let ((nrest (advice--tweak rest tweaker
)))
183 (if (eq rest nrest
) flist
184 (advice--make-1 (aref flist
1) (aref flist
3)
185 first nrest props
))))))))
188 (defun advice--remove-function (flist function
)
190 (lambda (first rest props
)
191 (cond ((not first
) rest
)
192 ((or (equal function first
)
193 (equal function
(cdr (assq 'name props
))))
196 (defvar advice--buffer-local-function-sample nil
)
198 (defun advice--set-buffer-local (var val
)
199 (if (function-equal val advice--buffer-local-function-sample
)
200 (kill-local-variable var
)
201 (set (make-local-variable var
) val
)))
204 (defun advice--buffer-local (var)
205 "Buffer-local value of VAR, presumed to contain a function."
206 (declare (gv-setter advice--set-buffer-local
))
207 (if (local-variable-p var
) (symbol-value var
)
208 (setq advice--buffer-local-function-sample
209 (lambda (&rest args
) (apply (default-value var
) args
)))))
212 (defmacro add-function
(where place function
&optional props
)
214 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
215 ;; and tracing want to stay first.
216 ;; - maybe let `where' specify some kind of predicate and use it
217 ;; to implement things like mode-local or eieio-defmethod.
218 ;; Of course, that only makes sense if the predicates of all advices can
219 ;; be combined and made more efficient.
220 ;; :before is like a normal add-hook on a normal hook.
221 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
222 ;; :before-until is like add-hook on run-hook-with-args-until-success.
223 ;; Same with :after-* but for (add-hook ... 'append).
224 "Add a piece of advice on the function stored at PLACE.
225 FUNCTION describes the code to add. WHERE describes where to add it.
226 WHERE can be explained by showing the resulting new function, as the
227 result of combining FUNCTION and the previous value of PLACE, which we
229 `:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
230 `:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
231 `:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
232 `:override' (lambda (&rest r) (apply FUNCTION r))
233 `:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
234 `:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
235 `:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
236 `:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
237 `:filter-args' (lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))
238 `:filter-return'(lambda (&rest r) (funcall FUNCTION (apply OLDFUN r)))
239 If FUNCTION was already added, do nothing.
240 PROPS is an alist of additional properties, among which the following have
242 - `name': a string or symbol. It can be used to refer to this piece of advice.
244 If PLACE is a simple variable, only its global value will be affected.
245 Use (local 'VAR) if you want to apply FUNCTION to VAR buffer-locally.
247 If one of FUNCTION or OLDFUN is interactive, then the resulting function
248 is also interactive. There are 3 cases:
249 - FUNCTION is not interactive: the interactive spec of OLDFUN is used.
250 - The interactive spec of FUNCTION is itself a function: it should take one
251 argument (the interactive spec of OLDFUN, which it can pass to
252 `advice-eval-interactive-spec') and return the list of arguments to use.
253 - Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
254 (declare (debug t
)) ;;(indent 2)
255 (cond ((eq 'local
(car-safe place
))
256 (setq place
`(advice--buffer-local ,@(cdr place
))))
258 (setq place
`(default-value ',place
))))
259 `(advice--add-function ,where
(gv-ref ,place
) ,function
,props
))
262 (defun advice--add-function (where ref function props
)
263 (let ((a (advice--member-p function
(cdr (assq 'name props
))
266 ;; The advice is already present. Remove the old one, first.
268 (advice--remove-function (gv-deref ref
) (advice--car a
))))
270 (advice--make where function
(gv-deref ref
) props
))))
273 (defmacro remove-function
(place function
)
274 "Remove the FUNCTION piece of advice from PLACE.
275 If FUNCTION was not added to PLACE, do nothing.
276 Instead of FUNCTION being the actual function, it can also be the `name'
277 of the piece of advice."
279 (cond ((eq 'local
(car-safe place
))
280 (setq place
`(advice--buffer-local ,@(cdr place
))))
282 (error "Use (default-value '%S) or (local '%S)" place place
)))
283 (gv-letplace (getter setter
) place
284 (macroexp-let2 nil new
`(advice--remove-function ,getter
,function
)
285 `(unless (eq ,new
,getter
) ,(funcall setter new
)))))
287 ;;;; Specific application of add-function to `symbol-function' for advice.
289 (defun advice--subst-main (old new
)
291 (lambda (first _rest _props
) (if (not first
) new
))))
293 (defun advice--normalize (symbol def
)
295 ((special-form-p def
)
296 ;; Not worth the trouble trying to handle this, I think.
297 (error "advice-add failure: %S is a special form" symbol
))
299 (eq 'macro
(car-safe (ignore-errors (indirect-function def
)))))
300 (let ((newval (cons 'macro
(cdr (indirect-function def
)))))
301 (put symbol
'advice--saved-rewrite
(cons def newval
))
303 ;; `f' might be a pure (hence read-only) cons!
304 ((and (eq 'macro
(car-safe def
))
305 (not (ignore-errors (setcdr def
(cdr def
)) t
)))
306 (cons 'macro
(cdr def
)))
309 (defsubst advice--strip-macro
(x)
310 (if (eq 'macro
(car-safe x
)) (cdr x
) x
))
312 (defun advice--defalias-fset (fsetfun symbol newdef
)
313 (when (get symbol
'advice--saved-rewrite
)
314 (put symbol
'advice--saved-rewrite nil
))
315 (setq newdef
(advice--normalize symbol newdef
))
316 (let* ((olddef (advice--strip-macro (symbol-function symbol
)))
319 ((null (get symbol
'advice--pending
))
322 (message "Delayed advice activation failed for %s: no data"
325 ((or (not olddef
) (autoloadp olddef
))
326 (get symbol
'advice--pending
))
327 (t (message "Dropping left-over advice--pending for %s" symbol
)
329 (if (and newdef
(not (autoloadp newdef
)))
330 (let* ((snewdef (advice--strip-macro newdef
))
331 (snewadv (advice--subst-main oldadv snewdef
)))
332 (put symbol
'advice--pending nil
)
333 (funcall (or fsetfun
#'fset
) symbol
334 (if (eq snewdef newdef
) snewadv
(cons 'macro snewadv
))))
335 (unless (eq oldadv
(get symbol
'advice--pending
))
336 (put symbol
'advice--pending
(advice--subst-main oldadv nil
)))
337 (funcall (or fsetfun
#'fset
) symbol newdef
))))
341 (defun advice-add (symbol where function
&optional props
)
342 "Like `add-function' but for the function named SYMBOL.
343 Contrary to `add-function', this will properly handle the cases where SYMBOL
344 is defined as a macro, alias, command, ..."
346 ;; - record the advice location, to display in describe-function.
347 ;; - change all defadvice in lisp/**/*.el.
348 ;; - rewrite advice.el on top of this.
349 ;; - obsolete advice.el.
350 (let* ((f (symbol-function symbol
))
351 (nf (advice--normalize symbol f
)))
352 (unless (eq f nf
) ;; Most importantly, if nf == nil!
354 (add-function where
(cond
355 ((eq (car-safe nf
) 'macro
) (cdr nf
))
356 ;; Reasons to delay installation of the advice:
357 ;; - If the function is not yet defined, installing
358 ;; the advice would affect `fboundp'ness.
359 ;; - If it's an autoloaded command,
360 ;; advice--make-interactive-form would end up
361 ;; loading the command eagerly.
362 ;; - `autoload' does nothing if the function is
363 ;; not an autoload or undefined.
364 ((or (not nf
) (autoloadp nf
))
365 (get symbol
'advice--pending
))
366 (t (symbol-function symbol
)))
368 (add-function :around
(get symbol
'defalias-fset-function
)
369 #'advice--defalias-fset
))
373 (defun advice-remove (symbol function
)
374 "Like `remove-function' but for the function named SYMBOL.
375 Contrary to `remove-function', this also works when SYMBOL is a macro
376 or an autoload and it preserves `fboundp'.
377 Instead of the actual function to remove, FUNCTION can also be the `name'
378 of the piece of advice."
379 (let ((f (symbol-function symbol
)))
380 ;; Can't use the `if' place here, because the body is too large,
381 ;; resulting in use of code that only works with lexical-scoping.
382 (remove-function (if (eq (car-safe f
) 'macro
)
384 (symbol-function symbol
))
387 (if (eq (car-safe f
) 'macro
) (cdr f
) (symbol-function symbol
)))
388 ;; Not advised any more.
389 (remove-function (get symbol
'defalias-fset-function
)
390 #'advice--defalias-fset
)
391 (if (eq (symbol-function symbol
)
392 (cdr (get symbol
'advice--saved-rewrite
)))
393 (fset symbol
(car (get symbol
'advice--saved-rewrite
))))))
396 (defun advice-mapc (fun def
)
397 "Apply FUN to every advice function in DEF.
398 FUN is called with a two arguments: the function that was added, and the
399 properties alist that was specified when it was added."
400 (while (advice--p def
)
401 (funcall fun
(advice--car def
) (advice--props def
))
402 (setq def
(advice--cdr def
))))
405 (defun advice-member-p (advice function-name
)
406 "Return non-nil if ADVICE has been added to FUNCTION-NAME.
407 Instead of ADVICE being the actual function, it can also be the `name'
408 of the piece of advice."
409 (advice--member-p advice advice
410 (or (get function-name
'advice--pending
)
412 (symbol-function function-name
)))))
414 ;; When code is advised, called-interactively-p needs to be taught to skip
415 ;; the advising frames.
416 ;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
417 ;; done from the advised function if the deepest advice is an around advice!
418 ;; In other cases (calls from an advice or calls from the advised function when
419 ;; the deepest advice is not an around advice), it should hopefully get
421 (add-hook 'called-interactively-p-functions
422 #'advice--called-interactively-skip
)
423 (defun advice--called-interactively-skip (origi frame1 frame2
)
428 (setq frame2
(internal--called-interactively-p--get-frame i
))
429 ;; (message "Advice Frame %d = %S" i frame2)
431 (when (and (eq (nth 1 frame2
) 'apply
)
433 (funcall get-next-frame
)
434 (advice--p (indirect-function (nth 1 frame2
)))))
435 (funcall get-next-frame
)
436 ;; If we now have the symbol, this was the head advice and
438 (while (advice--p (nth 1 frame1
))
439 ;; This was an inner advice called from some earlier advice.
440 ;; The stack frames look different depending on the particular
441 ;; kind of the earlier advice.
442 (let ((inneradvice (nth 1 frame1
)))
443 (if (and (eq (nth 1 frame2
) 'apply
)
445 (funcall get-next-frame
)
446 (advice--p (indirect-function
448 ;; The earlier advice was something like a before/after
449 ;; advice where the "next" code is called directly by the
451 (funcall get-next-frame
)
452 ;; It's apparently an around advice, where the "next" is
453 ;; called by the body of the advice in any way it sees fit,
454 ;; so we need to skip the frames of that body.
457 (funcall get-next-frame
)
458 (not (and (eq (nth 1 frame2
) 'apply
)
459 (eq (nth 3 frame2
) inneradvice
)))))
460 (funcall get-next-frame
)
461 (funcall get-next-frame
))))
466 ;;; nadvice.el ends here