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