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