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