* progmodes/python.el (python-shell-send-string):
[emacs.git] / lisp / emacs-lisp / nadvice.el
blob8dc1f19784c1e7fe34b49414181a382fd62710c4
1 ;;; nadvice.el --- Light-weight advice primitives for Elisp functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: extensions, lisp, tools
7 ;; Package: emacs
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/>.
22 ;;; Commentary:
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
30 ;; holds a function.
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'.
37 ;;; Code:
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--cd*r (f)
71 (while (advice--p f)
72 (setq f (advice--cdr f)))
75 (defun advice--make-docstring (function)
76 "Build the raw docstring for FUNCTION, presumably advised."
77 (let ((flist (indirect-function function))
78 (docstring nil))
79 (if (eq 'macro (car-safe flist)) (setq flist (cdr flist)))
80 (while (advice--p flist)
81 (let ((bytecode (aref flist 1))
82 (where nil))
83 (dolist (elem advice--where-alist)
84 (if (eq bytecode (cadr elem)) (setq where (car elem))))
85 (setq docstring
86 (concat
87 docstring
88 (propertize (format "%s advice: " where)
89 'face 'warning)
90 (let ((fun (advice--car flist)))
91 (if (symbolp fun) (format "`%S'" fun)
92 (let* ((name (cdr (assq 'name (advice--props flist))))
93 (doc (documentation fun t))
94 (usage (help-split-fundoc doc function)))
95 (if usage (setq doc (cdr usage)))
96 (if name
97 (if doc
98 (format "%s\n%s" name doc)
99 (format "%s" name))
100 (or doc "No documentation")))))
101 "\n")))
102 (setq flist (advice--cdr flist)))
103 (if docstring (setq docstring (concat docstring "\n")))
104 (let* ((origdoc (unless (eq function flist) ;Avoid inf-loops.
105 (documentation flist t)))
106 (usage (help-split-fundoc origdoc function)))
107 (setq usage (if (null usage)
108 (let ((arglist (help-function-arglist flist)))
109 (format "%S" (help-make-usage function arglist)))
110 (setq origdoc (cdr usage)) (car usage)))
111 (help-add-fundoc-usage (concat docstring origdoc) usage))))
113 (defun advice-eval-interactive-spec (spec)
114 "Evaluate the interactive spec SPEC."
115 (cond
116 ((stringp spec)
117 ;; There's no direct access to the C code (in call-interactively) that
118 ;; processes those specs, but that shouldn't stop us, should it?
119 ;; FIXME: Despite appearances, this is not faithful: SPEC and
120 ;; (advice-eval-interactive-spec SPEC) will behave subtly differently w.r.t
121 ;; command-history (and maybe a few other details).
122 (call-interactively `(lambda (&rest args) (interactive ,spec) args)))
123 ;; ((functionp spec) (funcall spec))
124 (t (eval spec))))
126 (defun advice--make-interactive-form (function main)
127 ;; TODO: make it so that interactive spec can be a constant which
128 ;; dynamically checks the advice--car/cdr to do its job.
129 ;; For that, advice-eval-interactive-spec needs to be more faithful.
130 (let ((fspec (cadr (interactive-form function))))
131 (when (eq 'function (car-safe fspec)) ;; Macroexpanded lambda?
132 (setq fspec (nth 1 fspec)))
133 (if (functionp fspec)
134 `(funcall ',fspec
135 ',(cadr (interactive-form main)))
136 (cadr (or (interactive-form function)
137 (interactive-form main))))))
139 (defsubst advice--make-1 (byte-code stack-depth function main props)
140 "Build a function value that adds FUNCTION to MAIN."
141 (let ((adv-sig (gethash main advertised-signature-table))
142 (advice
143 (apply #'make-byte-code 128 byte-code
144 (vector #'apply function main props) stack-depth
146 (and (or (commandp function) (commandp main))
147 (not (and (symbolp main) ;; Don't autoload too eagerly!
148 (autoloadp (symbol-function main))))
149 (list (advice--make-interactive-form
150 function main))))))
151 (when adv-sig (puthash advice adv-sig advertised-signature-table))
152 advice))
154 (defun advice--make (where function main props)
155 "Build a function value that adds FUNCTION to MAIN at WHERE.
156 WHERE is a symbol to select an entry in `advice--where-alist'."
157 (let ((fd (or (cdr (assq 'depth props)) 0))
158 (md (if (advice--p main)
159 (or (cdr (assq 'depth (advice--props main))) 0))))
160 (if (and md (> fd md))
161 ;; `function' should go deeper.
162 (let ((rest (advice--make where function (advice--cdr main) props)))
163 (advice--make-1 (aref main 1) (aref main 3)
164 (advice--car main) rest (advice--props main)))
165 (let ((desc (assq where advice--where-alist)))
166 (unless desc (error "Unknown add-function location `%S'" where))
167 (advice--make-1 (nth 1 desc) (nth 2 desc)
168 function main props)))))
170 (defun advice--member-p (function name definition)
171 (let ((found nil))
172 (while (and (not found) (advice--p definition))
173 (if (or (equal function (advice--car definition))
174 (when name
175 (equal name (cdr (assq 'name (advice--props definition))))))
176 (setq found definition)
177 (setq definition (advice--cdr definition))))
178 found))
180 (defun advice--tweak (flist tweaker)
181 (if (not (advice--p flist))
182 (funcall tweaker nil flist nil)
183 (let ((first (advice--car flist))
184 (rest (advice--cdr flist))
185 (props (advice--props flist)))
186 (let ((val (funcall tweaker first rest props)))
187 (if val (car val)
188 (let ((nrest (advice--tweak rest tweaker)))
189 (if (eq rest nrest) flist
190 (advice--make-1 (aref flist 1) (aref flist 3)
191 first nrest props))))))))
193 ;;;###autoload
194 (defun advice--remove-function (flist function)
195 (advice--tweak flist
196 (lambda (first rest props)
197 (cond ((not first) rest)
198 ((or (equal function first)
199 (equal function (cdr (assq 'name props))))
200 (list rest))))))
202 (defvar advice--buffer-local-function-sample nil
203 "keeps an example of the special \"run the default value\" functions.
204 These functions play the same role as t in buffer-local hooks, and to recognize
205 them, we keep a sample here against which to compare. Each instance is
206 different, but `function-equal' will hopefully ignore those differences.")
208 (defun advice--set-buffer-local (var val)
209 (if (function-equal val advice--buffer-local-function-sample)
210 (kill-local-variable var)
211 (set (make-local-variable var) val)))
213 ;;;###autoload
214 (defun advice--buffer-local (var)
215 "Buffer-local value of VAR, presumed to contain a function."
216 (declare (gv-setter advice--set-buffer-local))
217 (if (local-variable-p var) (symbol-value var)
218 (setq advice--buffer-local-function-sample
219 ;; This function acts like the t special value in buffer-local hooks.
220 (lambda (&rest args) (apply (default-value var) args)))))
222 ;;;###autoload
223 (defmacro add-function (where place function &optional props)
224 ;; TODO:
225 ;; - maybe let `where' specify some kind of predicate and use it
226 ;; to implement things like mode-local or eieio-defmethod.
227 ;; Of course, that only makes sense if the predicates of all advices can
228 ;; be combined and made more efficient.
229 ;; :before is like a normal add-hook on a normal hook.
230 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
231 ;; :before-until is like add-hook on run-hook-with-args-until-success.
232 ;; Same with :after-* but for (add-hook ... 'append).
233 "Add a piece of advice on the function stored at PLACE.
234 FUNCTION describes the code to add. WHERE describes where to add it.
235 WHERE can be explained by showing the resulting new function, as the
236 result of combining FUNCTION and the previous value of PLACE, which we
237 call OLDFUN here:
238 `:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
239 `:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
240 `:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
241 `:override' (lambda (&rest r) (apply FUNCTION r))
242 `:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
243 `:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
244 `:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
245 `:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
246 `:filter-args' (lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))
247 `:filter-return'(lambda (&rest r) (funcall FUNCTION (apply OLDFUN r)))
248 If FUNCTION was already added, do nothing.
249 PROPS is an alist of additional properties, among which the following have
250 a special meaning:
251 - `name': a string or symbol. It can be used to refer to this piece of advice.
252 - `depth': a number indicating a preference w.r.t ordering.
253 The default depth is 0. By convention, a depth of 100 means that
254 the advice should be innermost (i.e. at the end of the list),
255 whereas a depth of -100 means that the advice should be outermost.
257 If PLACE is a simple variable, only its global value will be affected.
258 Use (local 'VAR) if you want to apply FUNCTION to VAR buffer-locally.
260 If one of FUNCTION or OLDFUN is interactive, then the resulting function
261 is also interactive. There are 3 cases:
262 - FUNCTION is not interactive: the interactive spec of OLDFUN is used.
263 - The interactive spec of FUNCTION is itself a function: it should take one
264 argument (the interactive spec of OLDFUN, which it can pass to
265 `advice-eval-interactive-spec') and return the list of arguments to use.
266 - Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
267 (declare (debug t)) ;;(indent 2)
268 (cond ((eq 'local (car-safe place))
269 (setq place `(advice--buffer-local ,@(cdr place))))
270 ((symbolp place)
271 (setq place `(default-value ',place))))
272 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
274 ;;;###autoload
275 (defun advice--add-function (where ref function props)
276 (let ((a (advice--member-p function (cdr (assq 'name props))
277 (gv-deref ref))))
278 (when a
279 ;; The advice is already present. Remove the old one, first.
280 (setf (gv-deref ref)
281 (advice--remove-function (gv-deref ref) (advice--car a))))
282 (setf (gv-deref ref)
283 (advice--make where function (gv-deref ref) props))))
285 ;;;###autoload
286 (defmacro remove-function (place function)
287 "Remove the FUNCTION piece of advice from PLACE.
288 If FUNCTION was not added to PLACE, do nothing.
289 Instead of FUNCTION being the actual function, it can also be the `name'
290 of the piece of advice."
291 (declare (debug t))
292 (cond ((eq 'local (car-safe place))
293 (setq place `(advice--buffer-local ,@(cdr place))))
294 ((symbolp place)
295 (setq place `(default-value ',place))))
296 (gv-letplace (getter setter) place
297 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
298 `(unless (eq ,new ,getter) ,(funcall setter new)))))
300 (defun advice-function-mapc (f function-def)
301 "Apply F to every advice function in FUNCTION-DEF.
302 F is called with two arguments: the function that was added, and the
303 properties alist that was specified when it was added."
304 (while (advice--p function-def)
305 (funcall f (advice--car function-def) (advice--props function-def))
306 (setq function-def (advice--cdr function-def))))
308 (defun advice-function-member-p (advice function-def)
309 "Return non-nil if ADVICE is already in FUNCTION-DEF.
310 Instead of ADVICE being the actual function, it can also be the `name'
311 of the piece of advice."
312 (advice--member-p advice advice function-def))
314 ;;;; Specific application of add-function to `symbol-function' for advice.
316 (defun advice--subst-main (old new)
317 (advice--tweak old
318 (lambda (first _rest _props) (if (not first) new))))
320 (defun advice--normalize (symbol def)
321 (cond
322 ((special-form-p def)
323 ;; Not worth the trouble trying to handle this, I think.
324 (error "Advice impossible: %S is a special form" symbol))
325 ((and (symbolp def) (macrop def))
326 (let ((newval `(macro . ,(lambda (&rest r) (macroexpand `(,def . ,r))))))
327 (put symbol 'advice--saved-rewrite (cons def (cdr newval)))
328 newval))
329 ;; `f' might be a pure (hence read-only) cons!
330 ((and (eq 'macro (car-safe def))
331 (not (ignore-errors (setcdr def (cdr def)) t)))
332 (cons 'macro (cdr def)))
333 (t def)))
335 (defsubst advice--strip-macro (x)
336 (if (eq 'macro (car-safe x)) (cdr x) x))
338 (defun advice--symbol-function (symbol)
339 ;; The value conceptually stored in `symbol-function' is split into two
340 ;; parts:
341 ;; - the normal function definition.
342 ;; - the list of advice applied to it.
343 ;; `advice--symbol-function' is intended to return the second part (i.e. the
344 ;; list of advice, which includes a hole at the end which typically holds the
345 ;; first part, but this function doesn't care much which value is found
346 ;; there).
347 ;; In the "normal" state both parts are combined into a single value stored
348 ;; in the "function slot" of the symbol. But the way they are combined is
349 ;; different depending on whether the definition is a function or a macro.
350 ;; Also if the function definition is nil (i.e. unbound) or is an autoload,
351 ;; the second part is stashed away temporarily in the `advice--pending'
352 ;; symbol property.
353 (or (get symbol 'advice--pending)
354 (advice--strip-macro (symbol-function symbol))))
356 (defun advice--defalias-fset (fsetfun symbol newdef)
357 (unless fsetfun (setq fsetfun #'fset))
358 (when (get symbol 'advice--saved-rewrite)
359 (put symbol 'advice--saved-rewrite nil))
360 (setq newdef (advice--normalize symbol newdef))
361 (let ((oldadv (advice--symbol-function symbol)))
362 (if (and newdef (not (autoloadp newdef)))
363 (let* ((snewdef (advice--strip-macro newdef))
364 (snewadv (advice--subst-main oldadv snewdef)))
365 (put symbol 'advice--pending nil)
366 (funcall fsetfun symbol
367 (if (eq snewdef newdef) snewadv (cons 'macro snewadv))))
368 (unless (eq oldadv (get symbol 'advice--pending))
369 (put symbol 'advice--pending (advice--subst-main oldadv nil)))
370 (funcall fsetfun symbol newdef))))
372 ;;;###autoload
373 (defun advice-add (symbol where function &optional props)
374 "Like `add-function' but for the function named SYMBOL.
375 Contrary to `add-function', this will properly handle the cases where SYMBOL
376 is defined as a macro, alias, command, ..."
377 ;; TODO:
378 ;; - record the advice location, to display in describe-function.
379 ;; - change all defadvice in lisp/**/*.el.
380 ;; - obsolete advice.el.
381 (let* ((f (symbol-function symbol))
382 (nf (advice--normalize symbol f)))
383 (unless (eq f nf) (fset symbol nf))
384 (add-function where (cond
385 ((eq (car-safe nf) 'macro) (cdr nf))
386 ;; Reasons to delay installation of the advice:
387 ;; - If the function is not yet defined, installing
388 ;; the advice would affect `fboundp'ness.
389 ;; - If it's an autoloaded command,
390 ;; advice--make-interactive-form would end up
391 ;; loading the command eagerly.
392 ;; - `autoload' does nothing if the function is
393 ;; not an autoload or undefined.
394 ((or (not nf) (autoloadp nf))
395 (get symbol 'advice--pending))
396 (t (symbol-function symbol)))
397 function props)
398 (put symbol 'function-documentation `(advice--make-docstring ',symbol))
399 (add-function :around (get symbol 'defalias-fset-function)
400 #'advice--defalias-fset))
401 nil)
403 ;;;###autoload
404 (defun advice-remove (symbol function)
405 "Like `remove-function' but for the function named SYMBOL.
406 Contrary to `remove-function', this also works when SYMBOL is a macro
407 or an autoload and it preserves `fboundp'.
408 Instead of the actual function to remove, FUNCTION can also be the `name'
409 of the piece of advice."
410 (let ((f (symbol-function symbol)))
411 (remove-function (cond ;This is `advice--symbol-function' but as a "place".
412 ((get symbol 'advice--pending)
413 (get symbol 'advice--pending))
414 ((eq (car-safe f) 'macro) (cdr f))
415 (t (symbol-function symbol)))
416 function)
417 (unless (advice--p (advice--symbol-function symbol))
418 ;; Not advised any more.
419 (remove-function (get symbol 'defalias-fset-function)
420 #'advice--defalias-fset)
421 (let ((asr (get symbol 'advice--saved-rewrite)))
422 (and asr (eq (cdr-safe (symbol-function symbol))
423 (cdr asr))
424 (fset symbol (car (get symbol 'advice--saved-rewrite)))))))
425 nil)
427 (defun advice-mapc (fun symbol)
428 "Apply FUN to every advice function in SYMBOL.
429 FUN is called with a two arguments: the function that was added, and the
430 properties alist that was specified when it was added."
431 (advice-function-mapc fun (advice--symbol-function symbol)))
433 ;;;###autoload
434 (defun advice-member-p (advice symbol)
435 "Return non-nil if ADVICE has been added to SYMBOL.
436 Instead of ADVICE being the actual function, it can also be the `name'
437 of the piece of advice."
438 (advice-function-member-p advice (advice--symbol-function symbol)))
440 ;; When code is advised, called-interactively-p needs to be taught to skip
441 ;; the advising frames.
442 ;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
443 ;; done from the advised function if the deepest advice is an around advice!
444 ;; In other cases (calls from an advice or calls from the advised function when
445 ;; the deepest advice is not an around advice), it should hopefully get
446 ;; it right.
447 (add-hook 'called-interactively-p-functions
448 #'advice--called-interactively-skip)
449 (defun advice--called-interactively-skip (origi frame1 frame2)
450 (let* ((i origi)
451 (get-next-frame
452 (lambda ()
453 (setq frame1 frame2)
454 (setq frame2 (backtrace-frame i #'called-interactively-p))
455 ;; (message "Advice Frame %d = %S" i frame2)
456 (setq i (1+ i)))))
457 (when (and (eq (nth 1 frame2) 'apply)
458 (progn
459 (funcall get-next-frame)
460 (advice--p (indirect-function (nth 1 frame2)))))
461 (funcall get-next-frame)
462 ;; If we now have the symbol, this was the head advice and
463 ;; we're done.
464 (while (advice--p (nth 1 frame1))
465 ;; This was an inner advice called from some earlier advice.
466 ;; The stack frames look different depending on the particular
467 ;; kind of the earlier advice.
468 (let ((inneradvice (nth 1 frame1)))
469 (if (and (eq (nth 1 frame2) 'apply)
470 (progn
471 (funcall get-next-frame)
472 (advice--p (indirect-function
473 (nth 1 frame2)))))
474 ;; The earlier advice was something like a before/after
475 ;; advice where the "next" code is called directly by the
476 ;; advice--p object.
477 (funcall get-next-frame)
478 ;; It's apparently an around advice, where the "next" is
479 ;; called by the body of the advice in any way it sees fit,
480 ;; so we need to skip the frames of that body.
481 (while
482 (progn
483 (funcall get-next-frame)
484 (not (and (eq (nth 1 frame2) 'apply)
485 (eq (nth 3 frame2) inneradvice)))))
486 (funcall get-next-frame)
487 (funcall get-next-frame))))
488 (- i origi 1))))
491 (provide 'nadvice)
492 ;;; nadvice.el ends here