Merge from emacs-24; up to 2012-12-25T17:37:29Z!eliz@gnu.org
[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-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 and 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 (let ((val (funcall tweaker first rest props)))
177 (if val (car val)
178 (let ((nrest (advice--tweak rest tweaker)))
179 (if (eq rest nrest) flist
180 (advice--make-1 (aref flist 1) (aref flist 3)
181 first nrest props))))))))
182
183 ;;;###autoload
184 (defun advice--remove-function (flist function)
185 (advice--tweak flist
186 (lambda (first rest props)
187 (cond ((not first) rest)
188 ((or (equal function first)
189 (equal function (cdr (assq 'name props))))
190 (list rest))))))
191
192 (defvar advice--buffer-local-function-sample nil)
193
194 (defun advice--set-buffer-local (var val)
195 (if (function-equal val advice--buffer-local-function-sample)
196 (kill-local-variable var)
197 (set (make-local-variable var) val)))
198
199 ;;;###autoload
200 (defun advice--buffer-local (var)
201 "Buffer-local value of VAR, presumed to contain a function."
202 (declare (gv-setter advice--set-buffer-local))
203 (if (local-variable-p var) (symbol-value var)
204 (setq advice--buffer-local-function-sample
205 (lambda (&rest args) (apply (default-value var) args)))))
206
207 ;;;###autoload
208 (defmacro add-function (where place function &optional props)
209 ;; TODO:
210 ;; - obsolete with-wrapper-hook (mostly requires buffer-local support).
211 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
212 ;; and tracing want to stay first.
213 ;; - maybe let `where' specify some kind of predicate and use it
214 ;; to implement things like mode-local or eieio-defmethod.
215 ;; Of course, that only makes sense if the predicates of all advices can
216 ;; be combined and made more efficient.
217 ;; :before is like a normal add-hook on a normal hook.
218 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
219 ;; :before-until is like add-hook on run-hook-with-args-until-success.
220 ;; Same with :after-* but for (add-hook ... 'append).
221 "Add a piece of advice on the function stored at PLACE.
222 FUNCTION describes the code to add. WHERE describes where to add it.
223 WHERE can be explained by showing the resulting new function, as the
224 result of combining FUNCTION and the previous value of PLACE, which we
225 call OLDFUN here:
226 `:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
227 `:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
228 `:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
229 `:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
230 `:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
231 `:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
232 `:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
233 If FUNCTION was already added, do nothing.
234 PROPS is an alist of additional properties, among which the following have
235 a special meaning:
236 - `name': a string or symbol. It can be used to refer to this piece of advice.
237
238 PLACE cannot be a simple variable. Instead it should either be
239 \(default-value 'VAR) or (local 'VAR) depending on whether FUNCTION
240 should be applied to VAR buffer-locally or globally.
241
242 If one of FUNCTION or OLDFUN is interactive, then the resulting function
243 is also interactive. There are 3 cases:
244 - FUNCTION is not interactive: the interactive spec of OLDFUN is used.
245 - The interactive spec of FUNCTION is itself a function: it should take one
246 argument (the interactive spec of OLDFUN, which it can pass to
247 `advice-eval-interactive-spec') and return the list of arguments to use.
248 - Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
249 (declare (debug t)) ;;(indent 2)
250 (cond ((eq 'local (car-safe place))
251 (setq place `(advice--buffer-local ,@(cdr place))))
252 ((symbolp place)
253 (error "Use (default-value '%S) or (local '%S)" place place)))
254 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
255
256 ;;;###autoload
257 (defun advice--add-function (where ref function props)
258 (unless (advice--member-p function (gv-deref ref))
259 (setf (gv-deref ref)
260 (advice--make where function (gv-deref ref) props))))
261
262 (defmacro remove-function (place function)
263 "Remove the FUNCTION piece of advice from PLACE.
264 If FUNCTION was not added to PLACE, do nothing.
265 Instead of FUNCTION being the actual function, it can also be the `name'
266 of the piece of advice."
267 (declare (debug t))
268 (cond ((eq 'local (car-safe place))
269 (setq place `(advice--buffer-local ,@(cdr place))))
270 ((symbolp place)
271 (error "Use (default-value '%S) or (local '%S)" place place)))
272 (gv-letplace (getter setter) place
273 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
274 `(unless (eq ,new ,getter) ,(funcall setter new)))))
275
276 ;;;; Specific application of add-function to `symbol-function' for advice.
277
278 (defun advice--subst-main (old new)
279 (advice--tweak old
280 (lambda (first _rest _props) (if (not first) new))))
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 ;; 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
455
456 (provide 'nadvice)
457 ;;; nadvice.el ends here