Merge from emacs-24; up to 2012-11-09T14:45:15Z!dmantipov@yandex.ru
[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 `add-advice' and `remove-advice' 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--make-interactive-form (function main)
113 ;; TODO: Make it possible to do around-like advising on the
114 ;; interactive forms (bug#12844).
115 ;; TODO: make it so that interactive spec can be a constant which
116 ;; dynamically checks the advice--car/cdr to do its job.
117 ;; TODO: Implement interactive-read-args:
118 ;;(when (or (commandp function) (commandp main))
119 ;; `(interactive-read-args
120 ;; (cadr (or (interactive-form function) (interactive-form main)))))
121 ;; FIXME: This loads autoloaded functions too eagerly.
122 (cadr (or (interactive-form function)
123 (interactive-form main))))
124
125 (defsubst advice--make-1 (byte-code stack-depth function main props)
126 "Build a function value that adds FUNCTION to MAIN."
127 (let ((adv-sig (gethash main advertised-signature-table))
128 (advice
129 (apply #'make-byte-code 128 byte-code
130 (vector #'apply function main props) stack-depth
131 advice--docstring
132 (when (or (commandp function) (commandp main))
133 (list (advice--make-interactive-form
134 function main))))))
135 (when adv-sig (puthash advice adv-sig advertised-signature-table))
136 advice))
137
138 (defun advice--make (where function main props)
139 "Build a function value that adds FUNCTION to MAIN at WHERE.
140 WHERE is a symbol to select an entry in `advice--where-alist'."
141 (let ((desc (assq where advice--where-alist)))
142 (unless desc (error "Unknown add-function location `%S'" where))
143 (advice--make-1 (nth 1 desc) (nth 2 desc)
144 function main props)))
145
146 (defun advice--member-p (function definition)
147 (let ((found nil))
148 (while (and (not found) (advice--p definition))
149 (if (or (equal function (advice--car definition))
150 (equal function (cdr (assq 'name (advice--props definition)))))
151 (setq found t)
152 (setq definition (advice--cdr definition))))
153 found))
154
155 ;;;###autoload
156 (defun advice--remove-function (flist function)
157 (if (not (advice--p flist))
158 flist
159 (let ((first (advice--car flist))
160 (props (advice--props flist)))
161 (if (or (equal function first)
162 (equal function (cdr (assq 'name props))))
163 (advice--cdr flist)
164 (let* ((rest (advice--cdr flist))
165 (nrest (advice--remove-function rest function)))
166 (if (eq rest nrest) flist
167 (advice--make-1 (aref flist 1) (aref flist 3)
168 first nrest props)))))))
169
170 ;;;###autoload
171 (defmacro add-function (where place function &optional props)
172 ;; TODO:
173 ;; - provide something like `around' for interactive forms.
174 ;; - provide some kind of buffer-local functionality at least when `place'
175 ;; is a variable.
176 ;; - obsolete with-wrapper-hook (mostly requires buffer-local support).
177 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
178 ;; and tracing want to stay first.
179 ;; - maybe also let `where' specify some kind of predicate and use it
180 ;; to implement things like mode-local or eieio-defmethod.
181 ;; :before is like a normal add-hook on a normal hook.
182 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
183 ;; :before-until is like add-hook on run-hook-with-args-until-success.
184 ;; Same with :after-* but for (add-hook ... 'append).
185 "Add a piece of advice on the function stored at PLACE.
186 FUNCTION describes the code to add. WHERE describes where to add it.
187 WHERE can be explained by showing the resulting new function, as the
188 result of combining FUNCTION and the previous value of PLACE, which we
189 call OLDFUN here:
190 `:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
191 `:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
192 `:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
193 `:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
194 `:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
195 `:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
196 `:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
197 If FUNCTION was already added, do nothing.
198 PROPS is an alist of additional properties, among which the following have
199 a special meaning:
200 - `name': a string or symbol. It can be used to refer to this piece of advice."
201 (declare (debug t)) ;;(indent 2)
202 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
203
204 ;;;###autoload
205 (defun advice--add-function (where ref function props)
206 (unless (advice--member-p function (gv-deref ref))
207 (setf (gv-deref ref)
208 (advice--make where function (gv-deref ref) props))))
209
210 (defmacro remove-function (place function)
211 "Remove the FUNCTION piece of advice from PLACE.
212 If FUNCTION was not added to PLACE, do nothing.
213 Instead of FUNCTION being the actual function, it can also be the `name'
214 of the piece of advice."
215 (declare (debug t))
216 (gv-letplace (getter setter) place
217 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
218 `(unless (eq ,new ,getter) ,(funcall setter new)))))
219
220 ;;;; Specific application of add-function to `symbol-function' for advice.
221
222 (defun advice--subst-main (old new)
223 (if (not (advice--p old))
224 new
225 (let* ((first (advice--car old))
226 (rest (advice--cdr old))
227 (props (advice--props old))
228 (nrest (advice--subst-main rest new)))
229 (if (equal rest nrest) old
230 (advice--make-1 (aref old 1) (aref old 3)
231 first nrest props)))))
232
233 (defun advice--defalias-fset (fsetfun symbol newdef)
234 (let* ((olddef (if (fboundp symbol) (symbol-function symbol)))
235 (oldadv
236 (cond
237 ((null (get symbol 'advice--pending))
238 (or olddef
239 (progn
240 (message "Delayed advice activation failed for %s: no data"
241 symbol)
242 nil)))
243 ((or (not olddef) (autoloadp olddef))
244 (prog1 (get symbol 'advice--pending)
245 (put symbol 'advice--pending nil)))
246 (t (message "Dropping left-over advice--pending for %s" symbol)
247 (put symbol 'advice--pending nil)
248 olddef))))
249 (funcall (or fsetfun #'fset) symbol (advice--subst-main oldadv newdef))))
250
251
252 ;;;###autoload
253 (defun advice-add (symbol where function &optional props)
254 "Like `add-function' but for the function named SYMBOL.
255 Contrary to `add-function', this will properly handle the cases where SYMBOL
256 is defined as a macro, alias, command, ..."
257 ;; TODO:
258 ;; - record the advice location, to display in describe-function.
259 ;; - change all defadvice in lisp/**/*.el.
260 ;; - rewrite advice.el on top of this.
261 ;; - obsolete advice.el.
262 ;; To make advice.el and nadvice.el interoperate properly I see 2 different
263 ;; ways:
264 ;; - keep them separate: complete the defalias-fset-function setter with
265 ;; a matching accessor which both nadvice.el and advice.el will have to use
266 ;; in place of symbol-function. This can probably be made to work, but
267 ;; they have to agree on a "protocol".
268 ;; - layer advice.el on top of nadvice.el. I prefer this approach. the
269 ;; simplest way is to make advice.el build one ad-Advice-foo function for
270 ;; each advised function which is advice-added/removed whenever ad-activate
271 ;; ad-deactivate is called.
272 (let ((f (and (fboundp symbol) (symbol-function symbol))))
273 (cond
274 ((special-form-p f)
275 ;; Not worth the trouble trying to handle this, I think.
276 (error "add-advice failure: %S is a special form" symbol))
277 ((and (symbolp f)
278 (eq 'macro (car-safe (ignore-errors (indirect-function f)))))
279 (let ((newval (cons 'macro (cdr (indirect-function f)))))
280 (put symbol 'advice--saved-rewrite (cons f newval))
281 (fset symbol newval)))
282 ;; `f' might be a pure (hence read-only) cons!
283 ((and (eq 'macro (car-safe f)) (not (ignore-errors (setcdr f (cdr f)) t)))
284 (fset symbol (cons 'macro (cdr f))))
285 ))
286 (let ((f (and (fboundp symbol) (symbol-function symbol))))
287 (add-function where (cond
288 ((eq (car-safe f) 'macro) (cdr f))
289 ;; If the function is not yet defined, we can't yet
290 ;; install the advice.
291 ;; FIXME: If it's an autoloaded command, we also
292 ;; have a problem because we need to load the
293 ;; command to build the interactive-form.
294 ((or (not f) (and (autoloadp f))) ;; (commandp f)
295 (get symbol 'advice--pending))
296 (t (symbol-function symbol)))
297 function props)
298 (add-function :around (get symbol 'defalias-fset-function)
299 #'advice--defalias-fset))
300 nil)
301
302 ;;;###autoload
303 (defun advice-remove (symbol function)
304 "Like `remove-function' but for the function named SYMBOL.
305 Contrary to `remove-function', this will work also when SYMBOL is a macro
306 and it will not signal an error if SYMBOL is not `fboundp'.
307 Instead of the actual function to remove, FUNCTION can also be the `name'
308 of the piece of advice."
309 (when (fboundp symbol)
310 (let ((f (symbol-function symbol)))
311 ;; Can't use the `if' place here, because the body is too large,
312 ;; resulting in use of code that only works with lexical-scoping.
313 (remove-function (if (eq (car-safe f) 'macro)
314 (cdr f)
315 (symbol-function symbol))
316 function)
317 (unless (advice--p
318 (if (eq (car-safe f) 'macro) (cdr f) (symbol-function symbol)))
319 ;; Not adviced any more.
320 (remove-function (get symbol 'defalias-fset-function)
321 #'advice--defalias-fset)
322 (if (eq (symbol-function symbol)
323 (cdr (get symbol 'advice--saved-rewrite)))
324 (fset symbol (car (get symbol 'advice--saved-rewrite))))))
325 nil))
326
327 ;; (defun advice-mapc (fun symbol)
328 ;; "Apply FUN to every function added as advice to SYMBOL.
329 ;; FUN is called with a two arguments: the function that was added, and the
330 ;; properties alist that was specified when it was added."
331 ;; (let ((def (or (get symbol 'advice--pending)
332 ;; (if (fboundp symbol) (symbol-function symbol)))))
333 ;; (while (advice--p def)
334 ;; (funcall fun (advice--car def) (advice--props def))
335 ;; (setq def (advice--cdr def)))))
336
337 ;;;###autoload
338 (defun advice-member-p (function symbol)
339 "Return non-nil if advice FUNCTION has been added to function SYMBOL.
340 Instead of FUNCTION being the actual function, it can also be the `name'
341 of the piece of advice."
342 (advice--member-p function
343 (or (get symbol 'advice--pending)
344 (if (fboundp symbol) (symbol-function symbol)))))
345
346
347 (provide 'nadvice)
348 ;;; nadvice.el ends here