* lisp/emacs-lisp/nadvice.el: Add buffer-local support to add-function.
[bpt/emacs.git] / lisp / emacs-lisp / nadvice.el
1 ;;; nadvice.el --- Light-weight advice primitives for Elisp functions -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2012 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 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 ;;;###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
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
200 ;;;###autoload
201 (defmacro add-function (where place function &optional props)
202 ;; TODO:
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.
206 ;; - maybe let `where' specify some kind of predicate and use it
207 ;; to implement things like mode-local or eieio-defmethod.
208 ;; Of course, that only makes sense if the predicates of all advices can
209 ;; be combined and made more efficient.
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.
215 FUNCTION describes the code to add. WHERE describes where to add it.
216 WHERE can be explained by showing the resulting new function, as the
217 result of combining FUNCTION and the previous value of PLACE, which we
218 call 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)))
226 If FUNCTION was already added, do nothing.
227 PROPS is an alist of additional properties, among which the following have
228 a special meaning:
229 - `name': a string or symbol. It can be used to refer to this piece of advice.
230
231 PLACE cannot be a simple variable. Instead it should either be
232 \(default-value 'VAR) or (local 'VAR) depending on whether FUNCTION
233 should be applied to VAR buffer-locally or globally.
234
235 If one of FUNCTION or OLDFUN is interactive, then the resulting function
236 is 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."
242 (declare (debug t)) ;;(indent 2)
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)))
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.
257 If FUNCTION was not added to PLACE, do nothing.
258 Instead of FUNCTION being the actual function, it can also be the `name'
259 of the piece of advice."
260 (declare (debug t))
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)))
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
282 (defun advice--normalize (symbol def)
283 (cond
284 ((special-form-p def)
285 ;; Not worth the trouble trying to handle this, I think.
286 (error "advice-add failure: %S is a special form" symbol))
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
301 (defun advice--defalias-fset (fsetfun symbol newdef)
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))))
307 (oldadv
308 (cond
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)))
318 (t (message "Dropping left-over advice--pending for %s" symbol)
319 (put symbol 'advice--pending nil)
320 olddef))))
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))))))
325
326
327 ;;;###autoload
328 (defun advice-add (symbol where function &optional props)
329 "Like `add-function' but for the function named SYMBOL.
330 Contrary to `add-function', this will properly handle the cases where SYMBOL
331 is 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.
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))
341 (add-function where (cond
342 ((eq (car-safe nf) 'macro) (cdr nf))
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))
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.
362 Contrary to `remove-function', this will work also when SYMBOL is a macro
363 and it will not signal an error if SYMBOL is not `fboundp'.
364 Instead of the actual function to remove, FUNCTION can also be the `name'
365 of 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)))
376 ;; Not advised any more.
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
395 (defun advice-member-p (advice function-name)
396 "Return non-nil if ADVICE has been added to FUNCTION-NAME.
397 Instead of ADVICE being the actual function, it can also be the `name'
398 of the piece of advice."
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))))))
404
405
406 (provide 'nadvice)
407 ;;; nadvice.el ends here