* lisp/emacs-lisp/pcase.el: Use PAT rather than UPAT in docstring
[emacs.git] / lisp / emacs-lisp / cl-generic.el
blobb3c127f48f748c332dc1a13a458b36198c676e52
1 ;;; cl-generic.el --- CLOS-style generic functions for Elisp -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Version: 1.0
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This implements the most of CLOS's multiple-dispatch generic functions.
26 ;; To use it you need either (require 'cl-generic) or (require 'cl-lib).
27 ;; The main entry points are: `cl-defgeneric' and `cl-defmethod'.
29 ;; Missing elements:
30 ;; - We don't support make-method, call-method, define-method-combination.
31 ;; CLOS's define-method-combination is IMO overly complicated, and it suffers
32 ;; from a significant problem: the method-combination code returns a sexp
33 ;; that needs to be `eval'uated or compiled. IOW it requires run-time
34 ;; code generation. Given how rarely method-combinations are used,
35 ;; I just provided a cl-generic-combine-methods generic function, to which
36 ;; people can add methods if they are really desperate for such functionality.
37 ;; - In defgeneric we don't support the options:
38 ;; declare, :method-combination, :generic-function-class, :method-class.
39 ;; Added elements:
40 ;; - We support aliases to generic functions.
41 ;; - cl-generic-generalizers. This generic function lets you extend the kind
42 ;; of thing on which to dispatch. There is support in this file for
43 ;; dispatch on:
44 ;; - (eql <val>)
45 ;; - (head <val>) which checks that the arg is a cons with <val> as its head.
46 ;; - plain old types
47 ;; - type of CL structs
48 ;; eieio-core adds dispatch on:
49 ;; - class of eieio objects
50 ;; - actual class argument, using the syntax (subclass <class>).
51 ;; - cl-generic-combine-methods (i.s.o define-method-combination and
52 ;; compute-effective-method).
53 ;; - cl-generic-call-method (which replaces make-method and call-method).
54 ;; - The standard method combination supports ":extra STRING" qualifiers
55 ;; which simply allows adding more methods for the same
56 ;; specializers&qualifiers.
57 ;; - Methods can dispatch on the context. For that, a method needs to specify
58 ;; context arguments, introduced by `&context' (which need to come right
59 ;; after the mandatory arguments and before anything like
60 ;; &optional/&rest/&key). Each context argument is given as (EXP SPECIALIZER)
61 ;; which means that EXP is taken as an expression which computes some context
62 ;; and this value is then used to dispatch.
63 ;; E.g. (foo &context (major-mode (eql c-mode))) is an arglist specifying
64 ;; that this method will only be applicable when `major-mode' has value
65 ;; `c-mode'.
67 ;; Efficiency considerations: overall, I've made an effort to make this fairly
68 ;; efficient for the expected case (e.g. no constant redefinition of methods).
69 ;; - Generic functions which do not dispatch on any argument are implemented
70 ;; optimally (just as efficient as plain old functions).
71 ;; - Generic functions which only dispatch on one argument are fairly efficient
72 ;; (not a lot of room for improvement without changes to the byte-compiler,
73 ;; I think).
74 ;; - Multiple dispatch is implemented rather naively. There's an extra `apply'
75 ;; function call for every dispatch; we don't optimize each dispatch
76 ;; based on the set of candidate methods remaining; we don't optimize the
77 ;; order in which we performs the dispatches either;
78 ;; If/when this becomes a problem, we can try and optimize it.
79 ;; - call-next-method could be made more efficient, but isn't too terrible.
81 ;; TODO:
83 ;; - A generic "filter" generalizer (e.g. could be used to cleanly adds methods
84 ;; to cl-generic-combine-methods with a specializer that says it applies only
85 ;; when some particular qualifier is used).
86 ;; - A way to dispatch on the context (e.g. the major-mode, some global
87 ;; variable, you name it).
89 ;;; Code:
91 ;; Note: For generic functions that dispatch on several arguments (i.e. those
92 ;; which use the multiple-dispatch feature), we always use the same "tagcodes"
93 ;; and the same set of arguments on which to dispatch. This works, but is
94 ;; often suboptimal since after one dispatch, the remaining dispatches can
95 ;; usually be simplified, or even completely skipped.
97 (eval-when-compile (require 'cl-lib))
98 (eval-when-compile (require 'pcase))
100 (cl-defstruct (cl--generic-generalizer
101 (:constructor nil)
102 (:constructor cl-generic-make-generalizer
103 (priority tagcode-function specializers-function)))
104 (priority nil :type integer)
105 tagcode-function
106 specializers-function)
108 (defconst cl--generic-t-generalizer
109 (cl-generic-make-generalizer
110 0 (lambda (_name) nil) (lambda (_tag) '(t))))
112 (cl-defstruct (cl--generic-method
113 (:constructor nil)
114 (:constructor cl--generic-make-method
115 (specializers qualifiers uses-cnm function))
116 (:predicate nil))
117 (specializers nil :read-only t :type list)
118 (qualifiers nil :read-only t :type (list-of atom))
119 ;; USES-CNM is a boolean indicating if FUNCTION expects an extra argument
120 ;; holding the next-method.
121 (uses-cnm nil :read-only t :type boolean)
122 (function nil :read-only t :type function))
124 (cl-defstruct (cl--generic
125 (:constructor nil)
126 (:constructor cl--generic-make (name))
127 (:predicate nil))
128 (name nil :type symbol :read-only t) ;Pointer back to the symbol.
129 ;; `dispatches' holds a list of (ARGNUM . TAGCODES) where ARGNUM is the index
130 ;; of the corresponding argument and TAGCODES is a list of (PRIORITY . EXP)
131 ;; where the EXPs are expressions (to be `or'd together) to compute the tag
132 ;; on which to dispatch and PRIORITY is the priority of each expression to
133 ;; decide in which order to sort them.
134 ;; The most important dispatch is last in the list (and the least is first).
135 (dispatches nil :type (list-of (cons natnum (list-of generalizers))))
136 (method-table nil :type (list-of cl--generic-method))
137 (options nil :type list))
139 (defun cl-generic-function-options (generic)
140 "Return the options of the generic function GENERIC."
141 (cl--generic-options generic))
143 (defmacro cl--generic (name)
144 `(get ,name 'cl--generic))
146 (defun cl-generic-ensure-function (name)
147 (let (generic
148 (origname name))
149 (while (and (null (setq generic (cl--generic name)))
150 (fboundp name)
151 (symbolp (symbol-function name)))
152 (setq name (symbol-function name)))
153 (unless (or (not (fboundp name))
154 (autoloadp (symbol-function name))
155 (and (functionp name) generic))
156 (error "%s is already defined as something else than a generic function"
157 origname))
158 (if generic
159 (cl-assert (eq name (cl--generic-name generic)))
160 (setf (cl--generic name) (setq generic (cl--generic-make name)))
161 (defalias name (cl--generic-make-function generic)))
162 generic))
164 (defun cl--generic-setf-rewrite (name)
165 (let* ((setter (intern (format "cl-generic-setter--%s" name)))
166 (exp `(unless (eq ',setter (get ',name 'cl-generic-setter))
167 ;; (when (get ',name 'gv-expander)
168 ;; (error "gv-expander conflicts with (setf %S)" ',name))
169 (setf (get ',name 'cl-generic-setter) ',setter)
170 (gv-define-setter ,name (val &rest args)
171 (cons ',setter (cons val args))))))
172 ;; Make sure `setf' can be used right away, e.g. in the body of the method.
173 (eval exp t)
174 (cons setter exp)))
176 ;;;###autoload
177 (defmacro cl-defgeneric (name args &rest options-and-methods)
178 "Create a generic function NAME.
179 DOC-STRING is the base documentation for this class. A generic
180 function has no body, as its purpose is to decide which method body
181 is appropriate to use. Specific methods are defined with `cl-defmethod'.
182 With this implementation the ARGS are currently ignored.
183 OPTIONS-AND-METHODS currently understands:
184 - (:documentation DOCSTRING)
185 - (declare DECLARATIONS)
186 - (:argument-precedence-order &rest ARGS)
187 - (:method [QUALIFIERS...] ARGS &rest BODY)
188 BODY, if present, is used as the body of a default method.
190 \(fn NAME ARGS [DOC-STRING] [OPTIONS-AND-METHODS...] &rest BODY)"
191 (declare (indent 2) (doc-string 3))
192 (let* ((doc (if (stringp (car-safe options-and-methods))
193 (pop options-and-methods)))
194 (declarations nil)
195 (methods ())
196 (options ())
197 next-head)
198 (while (progn (setq next-head (car-safe (car options-and-methods)))
199 (or (keywordp next-head)
200 (eq next-head 'declare)))
201 (pcase next-head
202 (`:documentation
203 (when doc (error "Multiple doc strings for %S" name))
204 (setq doc (cadr (pop options-and-methods))))
205 (`declare
206 (when declarations (error "Multiple `declare' for %S" name))
207 (setq declarations (pop options-and-methods)))
208 (`:method (push (cdr (pop options-and-methods)) methods))
209 (_ (push (pop options-and-methods) options))))
210 (when options-and-methods
211 ;; Anything remaining is assumed to be a default method body.
212 (push `(,args ,@options-and-methods) methods))
213 `(progn
214 ,(when (eq 'setf (car-safe name))
215 (pcase-let ((`(,setter . ,code) (cl--generic-setf-rewrite
216 (cadr name))))
217 (setq name setter)
218 code))
219 ,@(mapcar (lambda (declaration)
220 (let ((f (cdr (assq (car declaration)
221 defun-declarations-alist))))
222 (cond
223 (f (apply (car f) name args (cdr declaration)))
224 (t (message "Warning: Unknown defun property `%S' in %S"
225 (car declaration) name)
226 nil))))
227 (cdr declarations))
228 (defalias ',name
229 (cl-generic-define ',name ',args ',(nreverse options))
230 ,(help-add-fundoc-usage doc args))
231 ,@(mapcar (lambda (method) `(cl-defmethod ,name ,@method))
232 (nreverse methods)))))
234 ;;;###autoload
235 (defun cl-generic-define (name args options)
236 (pcase-let* ((generic (cl-generic-ensure-function name))
237 (`(,spec-args . ,_) (cl--generic-split-args args))
238 (mandatory (mapcar #'car spec-args))
239 (apo (assq :argument-precedence-order options)))
240 (unless (fboundp name)
241 ;; If the generic function was fmakunbound, throw away previous methods.
242 (setf (cl--generic-dispatches generic) nil)
243 (setf (cl--generic-method-table generic) nil))
244 (when apo
245 (dolist (arg (cdr apo))
246 (let ((pos (memq arg mandatory)))
247 (unless pos (error "%S is not a mandatory argument" arg))
248 (let* ((argno (- (length mandatory) (length pos)))
249 (dispatches (cl--generic-dispatches generic))
250 (dispatch (or (assq argno dispatches) (list argno))))
251 (setf (cl--generic-dispatches generic)
252 (cons dispatch (delq dispatch dispatches)))))))
253 (setf (cl--generic-options generic) options)
254 (cl--generic-make-function generic)))
256 (defmacro cl-generic-current-method-specializers ()
257 "List of (VAR . TYPE) where TYPE is var's specializer.
258 This macro can only be used within the lexical scope of a cl-generic method."
259 (error "cl-generic-current-method-specializers used outside of a method"))
261 (eval-and-compile ;Needed while compiling the cl-defmethod calls below!
262 (defun cl--generic-fgrep (vars sexp) ;Copied from pcase.el.
263 "Check which of the symbols VARS appear in SEXP."
264 (let ((res '()))
265 (while (consp sexp)
266 (dolist (var (cl--generic-fgrep vars (pop sexp)))
267 (unless (memq var res) (push var res))))
268 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
269 res))
271 (defun cl--generic-split-args (args)
272 "Return (SPEC-ARGS . PLAIN-ARGS)."
273 (let ((plain-args ())
274 (specializers nil)
275 (mandatory t))
276 (dolist (arg args)
277 (push (pcase arg
278 ((or '&optional '&rest '&key) (setq mandatory nil) arg)
279 ('&context
280 (unless mandatory
281 (error "&context not immediately after mandatory args"))
282 (setq mandatory 'context) nil)
283 ((let 'nil mandatory) arg)
284 ((let 'context mandatory)
285 (unless (consp arg)
286 (error "Invalid &context arg: %S" arg))
287 (push `((&context . ,(car arg)) . ,(cadr arg)) specializers)
288 nil)
289 (`(,name . ,type)
290 (push (cons name (car type)) specializers)
291 name)
293 (push (cons arg t) specializers)
294 arg))
295 plain-args))
296 (cons (nreverse specializers)
297 (nreverse (delq nil plain-args)))))
299 (defun cl--generic-lambda (args body)
300 "Make the lambda expression for a method with ARGS and BODY."
301 (pcase-let* ((`(,spec-args . ,plain-args)
302 (cl--generic-split-args args))
303 (fun `(cl-function (lambda ,plain-args ,@body)))
304 (macroenv (cons `(cl-generic-current-method-specializers
305 . ,(lambda () spec-args))
306 macroexpand-all-environment)))
307 (require 'cl-lib) ;Needed to expand `cl-flet' and `cl-function'.
308 ;; First macroexpand away the cl-function stuff (e.g. &key and
309 ;; destructuring args, `declare' and whatnot).
310 (pcase (macroexpand fun macroenv)
311 (`#'(lambda ,args . ,body)
312 (let* ((parsed-body (macroexp-parse-body body))
313 (cnm (make-symbol "cl--cnm"))
314 (nmp (make-symbol "cl--nmp"))
315 (nbody (macroexpand-all
316 `(cl-flet ((cl-call-next-method ,cnm)
317 (cl-next-method-p ,nmp))
318 ,@(cdr parsed-body))
319 macroenv))
320 ;; FIXME: Rather than `grep' after the fact, the
321 ;; macroexpansion should directly set some flag when cnm
322 ;; is used.
323 ;; FIXME: Also, optimize the case where call-next-method is
324 ;; only called with explicit arguments.
325 (uses-cnm (cl--generic-fgrep (list cnm nmp) nbody)))
326 (cons (not (not uses-cnm))
327 `#'(lambda (,@(if uses-cnm (list cnm)) ,@args)
328 ,@(car parsed-body)
329 ,(if (not (memq nmp uses-cnm))
330 nbody
331 `(let ((,nmp (lambda ()
332 (cl--generic-isnot-nnm-p ,cnm))))
333 ,nbody))))))
334 (f (error "Unexpected macroexpansion result: %S" f))))))
337 ;;;###autoload
338 (defmacro cl-defmethod (name args &rest body)
339 "Define a new method for generic function NAME.
340 I.e. it defines the implementation of NAME to use for invocations where the
341 value of the dispatch argument matches the specified TYPE.
342 The dispatch argument has to be one of the mandatory arguments, and
343 all methods of NAME have to use the same argument for dispatch.
344 The dispatch argument and TYPE are specified in ARGS where the corresponding
345 formal argument appears as (VAR TYPE) rather than just VAR.
347 The optional second argument QUALIFIER is a specifier that
348 modifies how the method is combined with other methods, including:
349 :before - Method will be called before the primary
350 :after - Method will be called after the primary
351 :around - Method will be called around everything else
352 The absence of QUALIFIER means this is a \"primary\" method.
354 Other than a type, TYPE can also be of the form `(eql VAL)' in
355 which case this method will be invoked when the argument is `eql' to VAL.
357 \(fn NAME [QUALIFIER] ARGS &rest [DOCSTRING] BODY)"
358 (declare (doc-string 3) (indent 2)
359 (debug
360 (&define ; this means we are defining something
361 [&or name ("setf" :name setf name)]
362 ;; ^^ This is the methods symbol
363 [ &optional keywordp ] ; this is key :before etc
364 list ; arguments
365 [ &optional stringp ] ; documentation string
366 def-body))) ; part to be debugged
367 (let ((qualifiers nil)
368 (setfizer (if (eq 'setf (car-safe name))
369 ;; Call it before we call cl--generic-lambda.
370 (cl--generic-setf-rewrite (cadr name)))))
371 (while (not (listp args))
372 (push args qualifiers)
373 (setq args (pop body)))
374 (pcase-let* ((`(,uses-cnm . ,fun) (cl--generic-lambda args body)))
375 `(progn
376 ,(when setfizer
377 (setq name (car setfizer))
378 (cdr setfizer))
379 ,(and (get name 'byte-obsolete-info)
380 (or (not (fboundp 'byte-compile-warning-enabled-p))
381 (byte-compile-warning-enabled-p 'obsolete))
382 (let* ((obsolete (get name 'byte-obsolete-info)))
383 (macroexp--warn-and-return
384 (macroexp--obsolete-warning name obsolete "generic function")
385 nil)))
386 ;; You could argue that `defmethod' modifies rather than defines the
387 ;; function, so warnings like "not known to be defined" are fair game.
388 ;; But in practice, it's common to use `cl-defmethod'
389 ;; without a previous `cl-defgeneric'.
390 (declare-function ,name "")
391 (cl-generic-define-method ',name ',(nreverse qualifiers) ',args
392 ,uses-cnm ,fun)))))
394 (defun cl--generic-member-method (specializers qualifiers methods)
395 (while
396 (and methods
397 (let ((m (car methods)))
398 (not (and (equal (cl--generic-method-specializers m) specializers)
399 (equal (cl--generic-method-qualifiers m) qualifiers)))))
400 (setq methods (cdr methods)))
401 methods)
403 ;;;###autoload
404 (defun cl-generic-define-method (name qualifiers args uses-cnm function)
405 (pcase-let*
406 ((generic (cl-generic-ensure-function name))
407 (`(,spec-args . ,_) (cl--generic-split-args args))
408 (specializers (mapcar (lambda (spec-arg)
409 (if (eq '&context (car-safe (car spec-arg)))
410 spec-arg (cdr spec-arg)))
411 spec-args))
412 (method (cl--generic-make-method
413 specializers qualifiers uses-cnm function))
414 (mt (cl--generic-method-table generic))
415 (me (cl--generic-member-method specializers qualifiers mt))
416 (dispatches (cl--generic-dispatches generic))
417 (i 0))
418 (dolist (spec-arg spec-args)
419 (let* ((key (if (eq '&context (car-safe (car spec-arg)))
420 (car spec-arg) i))
421 (generalizers (cl-generic-generalizers (cdr spec-arg)))
422 (x (assoc key dispatches)))
423 (unless x
424 (setq x (cons key (cl-generic-generalizers t)))
425 (setf (cl--generic-dispatches generic)
426 (setq dispatches (cons x dispatches))))
427 (dolist (generalizer generalizers)
428 (unless (member generalizer (cdr x))
429 (setf (cdr x)
430 (sort (cons generalizer (cdr x))
431 (lambda (x y)
432 (> (cl--generic-generalizer-priority x)
433 (cl--generic-generalizer-priority y)))))))
434 (setq i (1+ i))))
435 (if me (setcar me method)
436 (setf (cl--generic-method-table generic) (cons method mt)))
437 (cl-pushnew `(cl-defmethod . (,(cl--generic-name generic) . ,specializers))
438 current-load-list :test #'equal)
439 ;; FIXME: Try to avoid re-constructing a new function if the old one
440 ;; is still valid (e.g. still empty method cache)?
441 (let ((gfun (cl--generic-make-function generic))
442 ;; Prevent `defalias' from recording this as the definition site of
443 ;; the generic function.
444 current-load-list)
445 ;; For aliases, cl--generic-name gives us the actual name.
446 (let ((purify-flag
447 ;; BEWARE! Don't purify this function definition, since that leads
448 ;; to memory corruption if the hash-tables it holds are modified
449 ;; (the GC doesn't trace those pointers).
450 nil))
451 ;; But do use `defalias', so that it interacts properly with nadvice,
452 ;; e.g. for tracing/debug-on-entry.
453 (defalias (cl--generic-name generic) gfun)))))
455 (defmacro cl--generic-with-memoization (place &rest code)
456 (declare (indent 1) (debug t))
457 (gv-letplace (getter setter) place
458 `(or ,getter
459 ,(macroexp-let2 nil val (macroexp-progn code)
460 `(progn
461 ,(funcall setter val)
462 ,val)))))
464 (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
466 (defun cl--generic-get-dispatcher (dispatch)
467 (cl--generic-with-memoization
468 (gethash dispatch cl--generic-dispatchers)
469 ;; (message "cl--generic-get-dispatcher (%S)" dispatch)
470 (let* ((dispatch-arg (car dispatch))
471 (generalizers (cdr dispatch))
472 (lexical-binding t)
473 (tagcodes
474 (mapcar (lambda (generalizer)
475 (funcall (cl--generic-generalizer-tagcode-function
476 generalizer)
477 'arg))
478 generalizers))
479 (typescodes
480 (mapcar
481 (lambda (generalizer)
482 `(funcall ',(cl--generic-generalizer-specializers-function
483 generalizer)
484 ,(funcall (cl--generic-generalizer-tagcode-function
485 generalizer)
486 'arg)))
487 generalizers))
488 (tag-exp
489 ;; Minor optimization: since this tag-exp is
490 ;; only used to lookup the method-cache, it
491 ;; doesn't matter if the default value is some
492 ;; constant or nil.
493 `(or ,@(if (macroexp-const-p (car (last tagcodes)))
494 (butlast tagcodes)
495 tagcodes)))
496 (fixedargs '(arg))
497 (dispatch-idx dispatch-arg)
498 (bindings nil))
499 (when (eq '&context (car-safe dispatch-arg))
500 (setq bindings `((arg ,(cdr dispatch-arg))))
501 (setq fixedargs nil)
502 (setq dispatch-idx 0))
503 (dotimes (i dispatch-idx)
504 (push (make-symbol (format "arg%d" (- dispatch-idx i 1))) fixedargs))
505 ;; FIXME: For generic functions with a single method (or with 2 methods,
506 ;; one of which always matches), using a tagcode + hash-table is
507 ;; overkill: better just use a `cl-typep' test.
508 (byte-compile
509 `(lambda (generic dispatches-left methods)
510 (let ((method-cache (make-hash-table :test #'eql)))
511 (lambda (,@fixedargs &rest args)
512 (let ,bindings
513 (apply (cl--generic-with-memoization
514 (gethash ,tag-exp method-cache)
515 (cl--generic-cache-miss
516 generic ',dispatch-arg dispatches-left methods
517 ,(if (cdr typescodes)
518 `(append ,@typescodes) (car typescodes))))
519 ,@fixedargs args)))))))))
521 (defun cl--generic-make-function (generic)
522 (cl--generic-make-next-function generic
523 (cl--generic-dispatches generic)
524 (cl--generic-method-table generic)))
526 (defun cl--generic-make-next-function (generic dispatches methods)
527 (let* ((dispatch
528 (progn
529 (while (and dispatches
530 (let ((x (nth 1 (car dispatches))))
531 ;; No need to dispatch for t specializers.
532 (or (null x) (equal x cl--generic-t-generalizer))))
533 (setq dispatches (cdr dispatches)))
534 (pop dispatches))))
535 (if (not (and dispatch
536 ;; If there's no method left, there's no point checking
537 ;; further arguments.
538 methods))
539 (cl--generic-build-combined-method generic methods)
540 (let ((dispatcher (cl--generic-get-dispatcher dispatch)))
541 (funcall dispatcher generic dispatches methods)))))
543 (defvar cl--generic-combined-method-memoization
544 (make-hash-table :test #'equal :weakness 'value)
545 "Table storing previously built combined-methods.
546 This is particularly useful when many different tags select the same set
547 of methods, since this table then allows us to share a single combined-method
548 for all those different tags in the method-cache.")
550 (define-error 'cl--generic-cyclic-definition "Cyclic definition: %S")
552 (defun cl--generic-build-combined-method (generic methods)
553 (if (null methods)
554 ;; Special case needed to fix a circularity during bootstrap.
555 (cl--generic-standard-method-combination generic methods)
556 (let ((f
557 (cl--generic-with-memoization
558 ;; FIXME: Since the fields of `generic' are modified, this
559 ;; hash-table won't work right, because the hashes will change!
560 ;; It's not terribly serious, but reduces the effectiveness of
561 ;; the table.
562 (gethash (cons generic methods)
563 cl--generic-combined-method-memoization)
564 (puthash (cons generic methods) :cl--generic--under-construction
565 cl--generic-combined-method-memoization)
566 (condition-case nil
567 (cl-generic-combine-methods generic methods)
568 ;; Special case needed to fix a circularity during bootstrap.
569 (cl--generic-cyclic-definition
570 (cl--generic-standard-method-combination generic methods))))))
571 (if (eq f :cl--generic--under-construction)
572 (signal 'cl--generic-cyclic-definition
573 (list (cl--generic-name generic)))
574 f))))
576 (defun cl--generic-no-next-method-function (generic method)
577 (lambda (&rest args)
578 (apply #'cl-no-next-method generic method args)))
580 (defun cl-generic-call-method (generic method &optional fun)
581 "Return a function that calls METHOD.
582 FUN is the function that should be called when METHOD calls
583 `call-next-method'."
584 (if (not (cl--generic-method-uses-cnm method))
585 (cl--generic-method-function method)
586 (let ((met-fun (cl--generic-method-function method))
587 (next (or fun (cl--generic-no-next-method-function
588 generic method))))
589 (lambda (&rest args)
590 (apply met-fun
591 ;; FIXME: This sucks: passing just `next' would
592 ;; be a lot more efficient than the lambda+apply
593 ;; quasi-η, but we need this to implement the
594 ;; "if call-next-method is called with no
595 ;; arguments, then use the previous arguments".
596 (lambda (&rest cnm-args)
597 (apply next (or cnm-args args)))
598 args)))))
600 ;; Standard CLOS name.
601 (defalias 'cl-method-qualifiers #'cl--generic-method-qualifiers)
603 (defun cl--generic-standard-method-combination (generic methods)
604 (let ((mets-by-qual ()))
605 (dolist (method methods)
606 (let ((qualifiers (cl-method-qualifiers method)))
607 (if (eq (car qualifiers) :extra) (setq qualifiers (cddr qualifiers)))
608 (unless (member qualifiers '(() (:after) (:before) (:around)))
609 (error "Unsupported qualifiers in function %S: %S"
610 (cl--generic-name generic) qualifiers))
611 (push method (alist-get (car qualifiers) mets-by-qual))))
612 (cond
613 ((null mets-by-qual)
614 (lambda (&rest args)
615 (apply #'cl-no-applicable-method generic args)))
616 ((null (alist-get nil mets-by-qual))
617 (lambda (&rest args)
618 (apply #'cl-no-primary-method generic args)))
620 (let* ((fun nil)
621 (ab-call (lambda (m) (cl-generic-call-method generic m)))
622 (before
623 (mapcar ab-call (reverse (cdr (assoc :before mets-by-qual)))))
624 (after (mapcar ab-call (cdr (assoc :after mets-by-qual)))))
625 (dolist (method (cdr (assoc nil mets-by-qual)))
626 (setq fun (cl-generic-call-method generic method fun)))
627 (when (or after before)
628 (let ((next fun))
629 (setq fun (lambda (&rest args)
630 (dolist (bf before)
631 (apply bf args))
632 (prog1
633 (apply next args)
634 (dolist (af after)
635 (apply af args)))))))
636 (dolist (method (cdr (assoc :around mets-by-qual)))
637 (setq fun (cl-generic-call-method generic method fun)))
638 fun)))))
640 (defun cl--generic-cache-miss (generic
641 dispatch-arg dispatches-left methods-left types)
642 (let ((methods '()))
643 (dolist (method methods-left)
644 (let* ((specializer (or (if (integerp dispatch-arg)
645 (nth dispatch-arg
646 (cl--generic-method-specializers method))
647 (cdr (assoc dispatch-arg
648 (cl--generic-method-specializers method))))
650 (m (member specializer types)))
651 (when m
652 (push (cons (length m) method) methods))))
653 ;; Sort the methods, most specific first.
654 ;; It would be tempting to sort them once and for all in the method-table
655 ;; rather than here, but the order might depend on the actual argument
656 ;; (e.g. for multiple inheritance with defclass).
657 (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
658 (cl--generic-make-next-function generic dispatches-left methods)))
660 (cl-defgeneric cl-generic-generalizers (specializer)
661 "Return a list of generalizers for a given SPECIALIZER.
662 To each kind of `specializer', corresponds a `generalizer' which describes
663 how to extract a \"tag\" from an object which will then let us check if this
664 object matches the specializer. A typical example of a \"tag\" would be the
665 type of an object. It's called a `generalizer' because it
666 takes a specific object and returns a more general approximation,
667 denoting a set of objects to which it belongs.
668 A generalizer gives us the chunk of code which the
669 dispatch function needs to use to extract the \"tag\" of an object, as well
670 as a function which turns this tag into an ordered list of
671 `specializers' that this object matches.
672 The code which extracts the tag should be as fast as possible.
673 The tags should be chosen according to the following rules:
674 - The tags should not be too specific: similar objects which match the
675 same list of specializers should ideally use the same (`eql') tag.
676 This insures that the cached computation of the applicable
677 methods for one object can be reused for other objects.
678 - Corollary: objects which don't match any of the relevant specializers
679 should ideally all use the same tag (typically nil).
680 This insures that this cache does not grow unnecessarily large.
681 - Two different generalizers G1 and G2 should not use the same tag
682 unless they use it for the same set of objects. IOW, if G1.tag(X1) =
683 G2.tag(X2) then G1.tag(X1) = G2.tag(X1) = G1.tag(X2) = G2.tag(X2).
684 - If G1.priority > G2.priority and G1.tag(X1) = G1.tag(X2) and this tag is
685 non-nil, then you have to make sure that the G2.tag(X1) = G2.tag(X2).
686 This is because the method-cache is only indexed with the first non-nil
687 tag (by order of decreasing priority).")
690 (cl-defgeneric cl-generic-combine-methods (generic methods)
691 "Build the effective method made of METHODS.
692 It should return a function that expects the same arguments as the methods, and
693 calls those methods in some appropriate order.
694 GENERIC is the generic function (mostly used for its name).
695 METHODS is the list of the selected methods.
696 The METHODS list is sorted from most specific first to most generic last.
697 The function can use `cl-generic-call-method' to create functions that call those
698 methods.")
700 ;; Temporary definition to let the next defmethod succeed.
701 (fset 'cl-generic-generalizers
702 (lambda (_specializer) (list cl--generic-t-generalizer)))
703 (fset 'cl-generic-combine-methods
704 #'cl--generic-standard-method-combination)
706 (cl-defmethod cl-generic-generalizers (specializer)
707 "Support for the catch-all t specializer."
708 (if (eq specializer t) (list cl--generic-t-generalizer)
709 (error "Unknown specializer %S" specializer)))
711 (eval-when-compile
712 ;; This macro is brittle and only really important in order to be
713 ;; able to preload cl-generic without also preloading the byte-compiler,
714 ;; So we use `eval-when-compile' so as not keep it available longer than
715 ;; strictly needed.
716 (defmacro cl--generic-prefill-dispatchers (arg-or-context specializer)
717 (unless (integerp arg-or-context)
718 (setq arg-or-context `(&context . ,arg-or-context)))
719 (unless (fboundp 'cl--generic-get-dispatcher)
720 (require 'cl-generic))
721 (let ((fun (cl--generic-get-dispatcher
722 `(,arg-or-context ,@(cl-generic-generalizers specializer)
723 ,cl--generic-t-generalizer))))
724 ;; Recompute dispatch at run-time, since the generalizers may be slightly
725 ;; different (e.g. byte-compiled rather than interpreted).
726 ;; FIXME: There is a risk that the run-time generalizer is not equivalent
727 ;; to the compile-time one, in which case `fun' may not be correct
728 ;; any more!
729 `(let ((dispatch `(,',arg-or-context
730 ,@(cl-generic-generalizers ',specializer)
731 ,cl--generic-t-generalizer)))
732 ;; (message "Prefilling for %S with \n%S" dispatch ',fun)
733 (puthash dispatch ',fun cl--generic-dispatchers)))))
735 (cl-defmethod cl-generic-combine-methods (generic methods)
736 "Standard support for :after, :before, :around, and `:extra NAME' qualifiers."
737 (cl--generic-standard-method-combination generic methods))
739 (defconst cl--generic-nnm-sample (cl--generic-no-next-method-function t t))
740 (defconst cl--generic-cnm-sample
741 (funcall (cl--generic-build-combined-method
742 nil (list (cl--generic-make-method () () t #'identity)))))
744 (defun cl--generic-isnot-nnm-p (cnm)
745 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
746 ;; ¡Big Gross Ugly Hack!
747 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
748 ;; it, and some packages use it, so we need to support it.
749 (catch 'found
750 (cl-assert (function-equal cnm cl--generic-cnm-sample))
751 (if (byte-code-function-p cnm)
752 (let ((cnm-constants (aref cnm 2))
753 (sample-constants (aref cl--generic-cnm-sample 2)))
754 (dotimes (i (length sample-constants))
755 (when (function-equal (aref sample-constants i)
756 cl--generic-nnm-sample)
757 (throw 'found
758 (not (function-equal (aref cnm-constants i)
759 cl--generic-nnm-sample))))))
760 (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
761 (let ((cnm-env (cadr cnm)))
762 (dolist (vb (cadr cl--generic-cnm-sample))
763 (when (function-equal (cdr vb) cl--generic-nnm-sample)
764 (throw 'found
765 (not (function-equal (cdar cnm-env)
766 cl--generic-nnm-sample))))
767 (setq cnm-env (cdr cnm-env)))))
768 (error "Haven't found no-next-method-sample in cnm-sample")))
770 ;;; Define some pre-defined generic functions, used internally.
772 (define-error 'cl-no-method "No method for %S")
773 (define-error 'cl-no-next-method "No next method for %S" 'cl-no-method)
774 (define-error 'cl-no-primary-method "No primary method for %S" 'cl-no-method)
775 (define-error 'cl-no-applicable-method "No applicable method for %S"
776 'cl-no-method)
778 (cl-defgeneric cl-no-next-method (generic method &rest args)
779 "Function called when `cl-call-next-method' finds no next method."
780 (signal 'cl-no-next-method `(,(cl--generic-name generic) ,method ,@args)))
782 (cl-defgeneric cl-no-applicable-method (generic &rest args)
783 "Function called when a method call finds no applicable method."
784 (signal 'cl-no-applicable-method `(,(cl--generic-name generic) ,@args)))
786 (cl-defgeneric cl-no-primary-method (generic &rest args)
787 "Function called when a method call finds no primary method."
788 (signal 'cl-no-primary-method `(,(cl--generic-name generic) ,@args)))
790 (defun cl-call-next-method (&rest _args)
791 "Function to call the next applicable method.
792 Can only be used from within the lexical body of a primary or around method."
793 (error "cl-call-next-method only allowed inside primary and around methods"))
795 (defun cl-next-method-p ()
796 "Return non-nil if there is a next method.
797 Can only be used from within the lexical body of a primary or around method."
798 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
799 (error "cl-next-method-p only allowed inside primary and around methods"))
801 ;;;###autoload
802 (defun cl-find-method (generic qualifiers specializers)
803 (car (cl--generic-member-method
804 specializers qualifiers
805 (cl--generic-method-table (cl--generic generic)))))
807 ;;; Add support for describe-function
809 (defun cl--generic-search-method (met-name)
810 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
811 (regexp-quote (format "%s" (car met-name)))
812 "\\_>")))
814 (re-search-forward
815 (concat base-re "[^&\"\n]*"
816 (mapconcat (lambda (specializer)
817 (regexp-quote
818 (format "%S" (if (consp specializer)
819 (nth 1 specializer) specializer))))
820 (remq t (cdr met-name))
821 "[ \t\n]*)[^&\"\n]*"))
822 nil t)
823 (re-search-forward base-re nil t))))
826 (with-eval-after-load 'find-func
827 (defvar find-function-regexp-alist)
828 (add-to-list 'find-function-regexp-alist
829 `(cl-defmethod . ,#'cl--generic-search-method)))
831 (defun cl--generic-method-info (method)
832 (let* ((specializers (cl--generic-method-specializers method))
833 (qualifiers (cl--generic-method-qualifiers method))
834 (uses-cnm (cl--generic-method-uses-cnm method))
835 (function (cl--generic-method-function method))
836 (args (help-function-arglist function 'names))
837 (docstring (documentation function))
838 (qual-string
839 (if (null qualifiers) ""
840 (cl-assert (consp qualifiers))
841 (let ((s (prin1-to-string qualifiers)))
842 (concat (substring s 1 -1) " "))))
843 (doconly (if docstring
844 (let ((split (help-split-fundoc docstring nil)))
845 (if split (cdr split) docstring))))
846 (combined-args ()))
847 (if uses-cnm (setq args (cdr args)))
848 (dolist (specializer specializers)
849 (let ((arg (if (eq '&rest (car args))
850 (intern (format "arg%d" (length combined-args)))
851 (pop args))))
852 (push (if (eq specializer t) arg (list arg specializer))
853 combined-args)))
854 (setq combined-args (append (nreverse combined-args) args))
855 (list qual-string combined-args doconly)))
857 (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
858 (defun cl--generic-describe (function)
859 ;; Supposedly this is called from help-fns, so help-fns should be loaded at
860 ;; this point.
861 (declare-function help-fns-short-filename "help-fns" (filename))
862 (let ((generic (if (symbolp function) (cl--generic function))))
863 (when generic
864 (require 'help-mode) ;Needed for `help-function-def' button!
865 (save-excursion
866 (insert "\n\nThis is a generic function.\n\n")
867 (insert (propertize "Implementations:\n\n" 'face 'bold))
868 ;; Loop over fanciful generics
869 (dolist (method (cl--generic-method-table generic))
870 (let* ((info (cl--generic-method-info method)))
871 ;; FIXME: Add hyperlinks for the types as well.
872 (insert (format "%s%S" (nth 0 info) (nth 1 info)))
873 (let* ((met-name (cons function
874 (cl--generic-method-specializers method)))
875 (file (find-lisp-object-file-name met-name 'cl-defmethod)))
876 (when file
877 (insert " in `")
878 (help-insert-xref-button (help-fns-short-filename file)
879 'help-function-def met-name file
880 'cl-defmethod)
881 (insert "'.\n")))
882 (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
884 ;;; Support for (head <val>) specializers.
886 ;; For both the `eql' and the `head' specializers, the dispatch
887 ;; is unsatisfactory. Basically, in the "common&fast case", we end up doing
889 ;; (let ((tag (gethash value <tagcode-hashtable>)))
890 ;; (funcall (gethash tag <method-cache>)))
892 ;; whereas we'd like to just do
894 ;; (funcall (gethash value <method-cache>)))
896 ;; but the problem is that the method-cache is normally "open ended", so
897 ;; a nil means "not computed yet" and if we bump into it, we dutifully fill the
898 ;; corresponding entry, whereas we'd want to just fallback on some default
899 ;; effective method (so as not to fill the cache with lots of redundant
900 ;; entries).
902 (defvar cl--generic-head-used (make-hash-table :test #'eql))
904 (defconst cl--generic-head-generalizer
905 (cl-generic-make-generalizer
906 80 (lambda (name) `(gethash (car-safe ,name) cl--generic-head-used))
907 (lambda (tag) (if (eq (car-safe tag) 'head) (list tag)))))
909 (cl-defmethod cl-generic-generalizers :extra "head" (specializer)
910 "Support for the `(head VAL)' specializers."
911 ;; We have to implement `head' here using the :extra qualifier,
912 ;; since we can't use the `head' specializer to implement itself.
913 (if (not (eq (car-safe specializer) 'head))
914 (cl-call-next-method)
915 (cl--generic-with-memoization
916 (gethash (cadr specializer) cl--generic-head-used) specializer)
917 (list cl--generic-head-generalizer)))
919 (cl--generic-prefill-dispatchers 0 (head eql))
921 ;;; Support for (eql <val>) specializers.
923 (defvar cl--generic-eql-used (make-hash-table :test #'eql))
925 (defconst cl--generic-eql-generalizer
926 (cl-generic-make-generalizer
927 100 (lambda (name) `(gethash ,name cl--generic-eql-used))
928 (lambda (tag) (if (eq (car-safe tag) 'eql) (list tag)))))
930 (cl-defmethod cl-generic-generalizers ((specializer (head eql)))
931 "Support for the `(eql VAL)' specializers."
932 (puthash (cadr specializer) specializer cl--generic-eql-used)
933 (list cl--generic-eql-generalizer))
935 (cl--generic-prefill-dispatchers 0 (eql nil))
936 (cl--generic-prefill-dispatchers window-system (eql nil))
938 ;;; Support for cl-defstructs specializers.
940 (defun cl--generic-struct-tag (name)
941 ;; It's tempting to use (and (vectorp ,name) (aref ,name 0))
942 ;; but that would suffer from some problems:
943 ;; - the vector may have size 0.
944 ;; - when called on an actual vector (rather than an object), we'd
945 ;; end up returning an arbitrary value, possibly colliding with
946 ;; other tagcode's values.
947 ;; - it can also result in returning all kinds of irrelevant
948 ;; values which would end up filling up the method-cache with
949 ;; lots of irrelevant/redundant entries.
950 ;; FIXME: We could speed this up by introducing a dedicated
951 ;; vector type at the C level, so we could do something like
952 ;; (and (vector-objectp ,name) (aref ,name 0))
953 `(and (vectorp ,name)
954 (> (length ,name) 0)
955 (let ((tag (aref ,name 0)))
956 (if (eq (symbol-function tag) :quick-object-witness-check)
957 tag))))
959 (defun cl--generic-struct-specializers (tag)
960 (and (symbolp tag) (boundp tag)
961 (let ((class (symbol-value tag)))
962 (when (cl-typep class 'cl-structure-class)
963 (let ((types ())
964 (classes (list class)))
965 ;; BFS precedence.
966 (while (let ((class (pop classes)))
967 (push (cl--class-name class) types)
968 (setq classes
969 (append classes
970 (cl--class-parents class)))))
971 (nreverse types))))))
973 (defconst cl--generic-struct-generalizer
974 (cl-generic-make-generalizer
975 50 #'cl--generic-struct-tag
976 #'cl--generic-struct-specializers))
978 (cl-defmethod cl-generic-generalizers :extra "cl-struct" (type)
979 "Support for dispatch on cl-struct types."
981 (when (symbolp type)
982 ;; Use the "cl--struct-class*" (inlinable) functions/macros rather than
983 ;; the "cl-struct-*" variants which aren't inlined, so that dispatch can
984 ;; take place without requiring cl-lib.
985 (let ((class (cl--find-class type)))
986 (and (cl-typep class 'cl-structure-class)
987 (or (null (cl--struct-class-type class))
988 (error "Can't dispatch on cl-struct %S: type is %S"
989 type (cl--struct-class-type class)))
990 (progn (cl-assert (null (cl--struct-class-named class))) t)
991 (list cl--generic-struct-generalizer))))
992 (cl-call-next-method)))
994 (cl--generic-prefill-dispatchers 0 cl--generic-generalizer)
996 ;;; Dispatch on "system types".
998 (defconst cl--generic-typeof-types
999 ;; Hand made from the source code of `type-of'.
1000 '((integer number) (symbol) (string array sequence) (cons list sequence)
1001 ;; Markers aren't `numberp', yet they are accepted wherever integers are
1002 ;; accepted, pretty much.
1003 (marker) (overlay) (float number) (window-configuration)
1004 (process) (window) (subr) (compiled-function) (buffer)
1005 (char-table array sequence)
1006 (bool-vector array sequence)
1007 (frame) (hash-table) (font-spec) (font-entity) (font-object)
1008 (vector array sequence)
1009 ;; Plus, hand made:
1010 (null symbol list sequence)
1011 (list sequence)
1012 (array sequence)
1013 (sequence)
1014 (number)))
1016 (defconst cl--generic-typeof-generalizer
1017 (cl-generic-make-generalizer
1018 ;; FIXME: We could also change `type-of' to return `null' for nil.
1019 10 (lambda (name) `(if ,name (type-of ,name) 'null))
1020 (lambda (tag) (and (symbolp tag) (assq tag cl--generic-typeof-types)))))
1022 (cl-defmethod cl-generic-generalizers :extra "typeof" (type)
1023 "Support for dispatch on builtin types."
1024 ;; FIXME: Add support for other types accepted by `cl-typep' such
1025 ;; as `character', `atom', `face', `function', ...
1027 (and (assq type cl--generic-typeof-types)
1028 (progn
1029 (if (memq type '(vector array sequence))
1030 (message "`%S' also matches CL structs and EIEIO classes" type))
1031 (list cl--generic-typeof-generalizer)))
1032 (cl-call-next-method)))
1034 (cl--generic-prefill-dispatchers 0 integer)
1036 ;; Local variables:
1037 ;; generated-autoload-file: "cl-loaddefs.el"
1038 ;; End:
1040 (provide 'cl-generic)
1041 ;;; cl-generic.el ends here