]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/nadvice.el
1715763d48224c9d46c0d3f0d3defa46d3bc891b
[gnu-emacs] / lisp / emacs-lisp / nadvice.el
1 ;;; nadvice.el --- Light-weight advice primitives for Elisp functions -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2012-2013 Free Software Foundation, Inc.
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 ;;
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'.
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.
49 Each 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
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
125 (defun advice--make-interactive-form (function main)
126 ;; TODO: make it so that interactive spec can be a constant which
127 ;; dynamically checks the advice--car/cdr to do its job.
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))))
132 (when (eq 'function (car-safe fspec)) ;; Macroexpanded lambda?
133 (setq fspec (nth 1 fspec)))
134 (if (functionp fspec)
135 `(funcall ',fspec
136 ',(cadr (interactive-form main)))
137 (cadr (or (interactive-form function)
138 (interactive-form main))))))
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.
155 WHERE 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 (defun advice--tweak (flist tweaker)
171 (if (not (advice--p flist))
172 (funcall tweaker nil flist nil)
173 (let ((first (advice--car flist))
174 (rest (advice--cdr flist))
175 (props (advice--props flist)))
176 (or (funcall tweaker first rest props)
177 (let ((nrest (advice--tweak rest tweaker)))
178 (if (eq rest nrest) flist
179 (advice--make-1 (aref flist 1) (aref flist 3)
180 first nrest props)))))))
181
182 ;;;###autoload
183 (defun advice--remove-function (flist function)
184 (advice--tweak flist
185 (lambda (first rest props)
186 (if (or (not first)
187 (equal function first)
188 (equal function (cdr (assq 'name props))))
189 rest))))
190
191 (defvar advice--buffer-local-function-sample nil)
192
193 (defun advice--set-buffer-local (var val)
194 (if (function-equal val advice--buffer-local-function-sample)
195 (kill-local-variable var)
196 (set (make-local-variable var) val)))
197
198 ;;;###autoload
199 (defun advice--buffer-local (var)
200 "Buffer-local value of VAR, presumed to contain a function."
201 (declare (gv-setter advice--set-buffer-local))
202 (if (local-variable-p var) (symbol-value var)
203 (setq advice--buffer-local-function-sample
204 (lambda (&rest args) (apply (default-value var) args)))))
205
206 ;;;###autoload
207 (defmacro add-function (where place function &optional props)
208 ;; TODO:
209 ;; - obsolete with-wrapper-hook (mostly requires buffer-local support).
210 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
211 ;; and tracing want to stay first.
212 ;; - maybe let `where' specify some kind of predicate and use it
213 ;; to implement things like mode-local or eieio-defmethod.
214 ;; Of course, that only makes sense if the predicates of all advices can
215 ;; be combined and made more efficient.
216 ;; :before is like a normal add-hook on a normal hook.
217 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
218 ;; :before-until is like add-hook on run-hook-with-args-until-success.
219 ;; Same with :after-* but for (add-hook ... 'append).
220 "Add a piece of advice on the function stored at PLACE.
221 FUNCTION describes the code to add. WHERE describes where to add it.
222 WHERE can be explained by showing the resulting new function, as the
223 result of combining FUNCTION and the previous value of PLACE, which we
224 call OLDFUN here:
225 `:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
226 `:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
227 `:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
228 `:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
229 `:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
230 `:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
231 `:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
232 If FUNCTION was already added, do nothing.
233 PROPS is an alist of additional properties, among which the following have
234 a special meaning:
235 - `name': a string or symbol. It can be used to refer to this piece of advice.
236
237 PLACE cannot be a simple variable. Instead it should either be
238 \(default-value 'VAR) or (local 'VAR) depending on whether FUNCTION
239 should be applied to VAR buffer-locally or globally.
240
241 If one of FUNCTION or OLDFUN is interactive, then the resulting function
242 is also interactive. There are 3 cases:
243 - FUNCTION is not interactive: the interactive spec of OLDFUN is used.
244 - The interactive spec of FUNCTION is itself a function: it should take one
245 argument (the interactive spec of OLDFUN, which it can pass to
246 `advice-eval-interactive-spec') and return the list of arguments to use.
247 - Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
248 (declare (debug t)) ;;(indent 2)
249 (cond ((eq 'local (car-safe place))
250 (setq place `(advice--buffer-local ,@(cdr place))))
251 ((symbolp place)
252 (error "Use (default-value '%S) or (local '%S)" place place)))
253 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
254
255 ;;;###autoload
256 (defun advice--add-function (where ref function props)
257 (unless (advice--member-p function (gv-deref ref))
258 (setf (gv-deref ref)
259 (advice--make where function (gv-deref ref) props))))
260
261 (defmacro remove-function (place function)
262 "Remove the FUNCTION piece of advice from PLACE.
263 If FUNCTION was not added to PLACE, do nothing.
264 Instead of FUNCTION being the actual function, it can also be the `name'
265 of the piece of advice."
266 (declare (debug t))
267 (cond ((eq 'local (car-safe place))
268 (setq place `(advice--buffer-local ,@(cdr place))))
269 ((symbolp place)
270 (error "Use (default-value '%S) or (local '%S)" place place)))
271 (gv-letplace (getter setter) place
272 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
273 `(unless (eq ,new ,getter) ,(funcall setter new)))))
274
275 ;;;; Specific application of add-function to `symbol-function' for advice.
276
277 (defun advice--subst-main (old new)
278 (advice--tweak old
279 (lambda (first _rest _props) (if (not first) new))))
280
281 (defun advice--normalize (symbol def)
282 (cond
283 ((special-form-p def)
284 ;; Not worth the trouble trying to handle this, I think.
285 (error "advice-add failure: %S is a special form" symbol))
286 ((and (symbolp def)
287 (eq 'macro (car-safe (ignore-errors (indirect-function def)))))
288 (let ((newval (cons 'macro (cdr (indirect-function def)))))
289 (put symbol 'advice--saved-rewrite (cons def newval))
290 newval))
291 ;; `f' might be a pure (hence read-only) cons!
292 ((and (eq 'macro (car-safe def))
293 (not (ignore-errors (setcdr def (cdr def)) t)))
294 (cons 'macro (cdr def)))
295 (t def)))
296
297 (defsubst advice--strip-macro (x)
298 (if (eq 'macro (car-safe x)) (cdr x) x))
299
300 (defun advice--defalias-fset (fsetfun symbol newdef)
301 (when (get symbol 'advice--saved-rewrite)
302 (put symbol 'advice--saved-rewrite nil))
303 (setq newdef (advice--normalize symbol newdef))
304 (let* ((olddef (advice--strip-macro
305 (if (fboundp symbol) (symbol-function symbol))))
306 (oldadv
307 (cond
308 ((null (get symbol 'advice--pending))
309 (or olddef
310 (progn
311 (message "Delayed advice activation failed for %s: no data"
312 symbol)
313 nil)))
314 ((or (not olddef) (autoloadp olddef))
315 (prog1 (get symbol 'advice--pending)
316 (put symbol 'advice--pending nil)))
317 (t (message "Dropping left-over advice--pending for %s" symbol)
318 (put symbol 'advice--pending nil)
319 olddef))))
320 (let* ((snewdef (advice--strip-macro newdef))
321 (snewadv (advice--subst-main oldadv snewdef)))
322 (funcall (or fsetfun #'fset) symbol
323 (if (eq snewdef newdef) snewadv (cons 'macro snewadv))))))
324
325
326 ;;;###autoload
327 (defun advice-add (symbol where function &optional props)
328 "Like `add-function' but for the function named SYMBOL.
329 Contrary to `add-function', this will properly handle the cases where SYMBOL
330 is defined as a macro, alias, command, ..."
331 ;; TODO:
332 ;; - record the advice location, to display in describe-function.
333 ;; - change all defadvice in lisp/**/*.el.
334 ;; - rewrite advice.el on top of this.
335 ;; - obsolete advice.el.
336 (let* ((f (and (fboundp symbol) (symbol-function symbol)))
337 (nf (advice--normalize symbol f)))
338 (unless (eq f nf) ;; Most importantly, if nf == nil!
339 (fset symbol nf))
340 (add-function where (cond
341 ((eq (car-safe nf) 'macro) (cdr nf))
342 ;; Reasons to delay installation of the advice:
343 ;; - If the function is not yet defined, installing
344 ;; the advice would affect `fboundp'ness.
345 ;; - If it's an autoloaded command,
346 ;; advice--make-interactive-form would end up
347 ;; loading the command eagerly.
348 ;; - `autoload' does nothing if the function is
349 ;; not an autoload or undefined.
350 ((or (not nf) (autoloadp nf))
351 (get symbol 'advice--pending))
352 (t (symbol-function symbol)))
353 function props)
354 (add-function :around (get symbol 'defalias-fset-function)
355 #'advice--defalias-fset))
356 nil)
357
358 ;;;###autoload
359 (defun advice-remove (symbol function)
360 "Like `remove-function' but for the function named SYMBOL.
361 Contrary to `remove-function', this will work also when SYMBOL is a macro
362 and it will not signal an error if SYMBOL is not `fboundp'.
363 Instead of the actual function to remove, FUNCTION can also be the `name'
364 of the piece of advice."
365 (when (fboundp symbol)
366 (let ((f (symbol-function symbol)))
367 ;; Can't use the `if' place here, because the body is too large,
368 ;; resulting in use of code that only works with lexical-scoping.
369 (remove-function (if (eq (car-safe f) 'macro)
370 (cdr f)
371 (symbol-function symbol))
372 function)
373 (unless (advice--p
374 (if (eq (car-safe f) 'macro) (cdr f) (symbol-function symbol)))
375 ;; Not advised any more.
376 (remove-function (get symbol 'defalias-fset-function)
377 #'advice--defalias-fset)
378 (if (eq (symbol-function symbol)
379 (cdr (get symbol 'advice--saved-rewrite)))
380 (fset symbol (car (get symbol 'advice--saved-rewrite))))))
381 nil))
382
383 ;; (defun advice-mapc (fun symbol)
384 ;; "Apply FUN to every function added as advice to SYMBOL.
385 ;; FUN is called with a two arguments: the function that was added, and the
386 ;; properties alist that was specified when it was added."
387 ;; (let ((def (or (get symbol 'advice--pending)
388 ;; (if (fboundp symbol) (symbol-function symbol)))))
389 ;; (while (advice--p def)
390 ;; (funcall fun (advice--car def) (advice--props def))
391 ;; (setq def (advice--cdr def)))))
392
393 ;;;###autoload
394 (defun advice-member-p (advice function-name)
395 "Return non-nil if ADVICE has been added to FUNCTION-NAME.
396 Instead of ADVICE being the actual function, it can also be the `name'
397 of the piece of advice."
398 (advice--member-p advice
399 (or (get function-name 'advice--pending)
400 (advice--strip-macro
401 (if (fboundp function-name)
402 (symbol-function function-name))))))
403
404 ;; When code is advised, called-interactively-p needs to be taught to skip
405 ;; the advising frames.
406 ;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
407 ;; done from the advised function if the deepest advice is an around advice!
408 ;; In other cases (calls from an advice or calls from the advised function when
409 ;; the deepest advice is not an around advice), it should hopefully get
410 ;; it right.
411 (add-hook 'called-interactively-p-functions
412 #'advice--called-interactively-skip)
413 (defun advice--called-interactively-skip (origi frame1 frame2)
414 (let* ((i origi)
415 (get-next-frame
416 (lambda ()
417 (setq frame1 frame2)
418 (setq frame2 (internal--called-interactively-p--get-frame i))
419 ;; (message "Advice Frame %d = %S" i frame2)
420 (setq i (1+ i)))))
421 (when (and (eq (nth 1 frame2) 'apply)
422 (progn
423 (funcall get-next-frame)
424 (advice--p (indirect-function (nth 1 frame2)))))
425 (funcall get-next-frame)
426 ;; If we now have the symbol, this was the head advice and
427 ;; we're done.
428 (while (advice--p (nth 1 frame1))
429 ;; This was an inner advice called from some earlier advice.
430 ;; The stack frames look different depending on the particular
431 ;; kind of the earlier advice.
432 (let ((inneradvice (nth 1 frame1)))
433 (if (and (eq (nth 1 frame2) 'apply)
434 (progn
435 (funcall get-next-frame)
436 (advice--p (indirect-function
437 (nth 1 frame2)))))
438 ;; The earlier advice was something like a before/after
439 ;; advice where the "next" code is called directly by the
440 ;; advice--p object.
441 (funcall get-next-frame)
442 ;; It's apparently an around advice, where the "next" is
443 ;; called by the body of the advice in any way it sees fit,
444 ;; so we need to skip the frames of that body.
445 (while
446 (progn
447 (funcall get-next-frame)
448 (not (and (eq (nth 1 frame2) 'apply)
449 (eq (nth 3 frame2) inneradvice)))))
450 (funcall get-next-frame)
451 (funcall get-next-frame))))
452 (- i origi 1))))
453
454
455 (provide 'nadvice)
456 ;;; nadvice.el ends here