1 ;;; cl-generic.el --- CLOS-style generic functions for Elisp -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2015-2018 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
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 <https://www.gnu.org/licenses/>.
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'.
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.
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
45 ;; - (head <val>) which checks that the arg is a cons with <val> as its head.
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
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,
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.
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).
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
106 (:constructor cl-generic-make-generalizer
107 (name priority tagcode-function specializers-function
)))
108 (name nil
:type string
)
109 (priority nil
:type integer
)
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
)))
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
137 (:constructor cl--generic-make-method
138 (specializers qualifiers uses-cnm function
))
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
149 (:constructor cl--generic-make
(name))
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-p (f)
170 "Return non-nil if F is a generic function."
171 (and (symbolp f
) (cl--generic f
)))
173 (defun cl-generic-ensure-function (name &optional noerror
)
176 (while (and (null (setq generic
(cl--generic name
)))
179 (symbolp (symbol-function name
)))
180 (setq name
(symbol-function name
)))
181 (unless (or (not (fboundp name
))
182 (autoloadp (symbol-function name
))
183 (and (functionp name
) generic
)
185 (error "%s is already defined as something else than a generic function"
188 (cl-assert (eq name
(cl--generic-name generic
)))
189 (setf (cl--generic name
) (setq generic
(cl--generic-make name
))))
193 (defmacro cl-defgeneric
(name args
&rest options-and-methods
)
194 "Create a generic function NAME.
195 DOC-STRING is the base documentation for this class. A generic
196 function has no body, as its purpose is to decide which method body
197 is appropriate to use. Specific methods are defined with `cl-defmethod'.
198 With this implementation the ARGS are currently ignored.
199 OPTIONS-AND-METHODS currently understands:
200 - (:documentation DOCSTRING)
201 - (declare DECLARATIONS)
202 - (:argument-precedence-order &rest ARGS)
203 - (:method [QUALIFIERS...] ARGS &rest BODY)
204 DEFAULT-BODY, if present, is used as the body of a default method.
206 \(fn NAME ARGS [DOC-STRING] [OPTIONS-AND-METHODS...] &rest DEFAULT-BODY)"
207 (declare (indent 2) (doc-string 3)
209 (&define
[&or name
("setf" name
:name setf
)] listp
212 ("declare" &rest sexp
)
213 (":argument-precedence-order" &rest sexp
)
214 (&define
":method" [&rest atom
]
215 cl-generic-method-args lambda-doc
218 (let* ((doc (if (stringp (car-safe options-and-methods
))
219 (pop options-and-methods
)))
224 (while (progn (setq next-head
(car-safe (car options-and-methods
)))
225 (or (keywordp next-head
)
226 (eq next-head
'declare
)))
229 (when doc
(error "Multiple doc strings for %S" name
))
230 (setq doc
(cadr (pop options-and-methods
))))
232 (when declarations
(error "Multiple `declare' for %S" name
))
233 (setq declarations
(pop options-and-methods
)))
234 (`:method
(push (cdr (pop options-and-methods
)) methods
))
235 (_ (push (pop options-and-methods
) options
))))
236 (when options-and-methods
237 ;; Anything remaining is assumed to be a default method body.
238 (push `(,args
,@options-and-methods
) methods
))
239 (when (eq 'setf
(car-safe name
))
241 (setq name
(gv-setter (cadr name
))))
245 (cl-generic-define ',name
',args
',(nreverse options
))
246 ,(help-add-fundoc-usage doc args
))
248 ,@(mapcar (lambda (method) `(cl-defmethod ,name
,@method
))
250 ,@(mapcar (lambda (declaration)
251 (let ((f (cdr (assq (car declaration
)
252 defun-declarations-alist
))))
254 (f (apply (car f
) name args
(cdr declaration
)))
255 (t (message "Warning: Unknown defun property `%S' in %S"
256 (car declaration
) name
)
258 (cdr declarations
)))))
261 (defun cl-generic-define (name args options
)
262 (pcase-let* ((generic (cl-generic-ensure-function name
'noerror
))
263 (`(,spec-args .
,_
) (cl--generic-split-args args
))
264 (mandatory (mapcar #'car spec-args
))
265 (apo (assq :argument-precedence-order options
)))
266 (unless (fboundp name
)
267 ;; If the generic function was fmakunbound, throw away previous methods.
268 (setf (cl--generic-dispatches generic
) nil
)
269 (setf (cl--generic-method-table generic
) nil
))
271 (dolist (arg (cdr apo
))
272 (let ((pos (memq arg mandatory
)))
273 (unless pos
(error "%S is not a mandatory argument" arg
))
274 (let* ((argno (- (length mandatory
) (length pos
)))
275 (dispatches (cl--generic-dispatches generic
))
276 (dispatch (or (assq argno dispatches
) (list argno
))))
277 (setf (cl--generic-dispatches generic
)
278 (cons dispatch
(delq dispatch dispatches
)))))))
279 (setf (cl--generic-options generic
) options
)
280 (cl--generic-make-function generic
)))
282 (defmacro cl-generic-current-method-specializers
()
283 "List of (VAR . TYPE) where TYPE is var's specializer.
284 This macro can only be used within the lexical scope of a cl-generic method."
285 (error "cl-generic-current-method-specializers used outside of a method"))
287 (defmacro cl-generic-define-context-rewriter
(name args
&rest body
)
288 "Define a special kind of context named NAME.
289 Whenever a context specializer of the form (NAME . ARGS) appears,
290 the specializer used will be the one returned by BODY."
291 (declare (debug (&define name lambda-list def-body
)) (indent defun
))
293 (put ',name
'cl-generic--context-rewriter
294 (lambda ,args
,@body
))))
296 (eval-and-compile ;Needed while compiling the cl-defmethod calls below!
297 (defun cl--generic-fgrep (vars sexp
) ;Copied from pcase.el.
298 "Check which of the symbols VARS appear in SEXP."
301 (dolist (var (cl--generic-fgrep vars
(pop sexp
)))
302 (unless (memq var res
) (push var res
))))
303 (and (memq sexp vars
) (not (memq sexp res
)) (push sexp res
))
306 (defun cl--generic-split-args (args)
307 "Return (SPEC-ARGS . PLAIN-ARGS)."
308 (let ((plain-args ())
313 ((or '&optional
'&rest
'&key
) (setq mandatory nil
) arg
)
316 (error "&context not immediately after mandatory args"))
317 (setq mandatory
'context
) nil
)
318 ((let 'nil mandatory
) arg
)
319 ((let 'context mandatory
)
321 (error "Invalid &context arg: %S" arg
))
322 (let* ((name (car arg
))
325 (get name
'cl-generic--context-rewriter
))))
326 (if rewriter
(setq arg
(apply rewriter
(cdr arg
)))))
327 (push `((&context .
,(car arg
)) .
,(cadr arg
)) specializers
)
330 (push (cons name
(car type
)) specializers
)
333 (push (cons arg t
) specializers
)
336 (cons (nreverse specializers
)
337 (nreverse (delq nil plain-args
)))))
339 (defun cl--generic-lambda (args body
)
340 "Make the lambda expression for a method with ARGS and BODY."
341 (pcase-let* ((`(,spec-args .
,plain-args
)
342 (cl--generic-split-args args
))
343 (fun `(cl-function (lambda ,plain-args
,@body
)))
344 (macroenv (cons `(cl-generic-current-method-specializers
345 .
,(lambda () spec-args
))
346 macroexpand-all-environment
)))
347 (require 'cl-lib
) ;Needed to expand `cl-flet' and `cl-function'.
348 ;; First macroexpand away the cl-function stuff (e.g. &key and
349 ;; destructuring args, `declare' and whatnot).
350 (pcase (macroexpand fun macroenv
)
351 (`#'(lambda ,args .
,body
)
352 (let* ((parsed-body (macroexp-parse-body body
))
353 (cnm (make-symbol "cl--cnm"))
354 (nmp (make-symbol "cl--nmp"))
355 (nbody (macroexpand-all
356 `(cl-flet ((cl-call-next-method ,cnm
)
357 (cl-next-method-p ,nmp
))
360 ;; FIXME: Rather than `grep' after the fact, the
361 ;; macroexpansion should directly set some flag when cnm
363 ;; FIXME: Also, optimize the case where call-next-method is
364 ;; only called with explicit arguments.
365 (uses-cnm (cl--generic-fgrep (list cnm nmp
) nbody
)))
366 (cons (not (not uses-cnm
))
367 `#'(lambda (,@(if uses-cnm
(list cnm
)) ,@args
)
369 ,(if (not (memq nmp uses-cnm
))
371 `(let ((,nmp
(lambda ()
372 (cl--generic-isnot-nnm-p ,cnm
))))
374 (f (error "Unexpected macroexpansion result: %S" f
))))))
376 (put 'cl-defmethod
'function-documentation
377 '(cl--generic-make-defmethod-docstring))
379 (defun cl--generic-make-defmethod-docstring ()
380 ;; FIXME: Copy&paste from pcase--make-docstring.
381 (let* ((main (documentation (symbol-function 'cl-defmethod
) 'raw
))
382 (ud (help-split-fundoc main
'cl-defmethod
)))
383 ;; So that eg emacs -Q -l cl-lib --eval "(documentation 'pcase)" works,
384 ;; where cl-lib is anything using pcase-defmacro.
387 (insert (or (cdr ud
) main
))
388 (insert "\n\n\tCurrently supported forms for TYPE:\n\n")
389 (dolist (method (reverse (cl--generic-method-table
390 (cl--generic 'cl-generic-generalizers
))))
391 (let* ((info (cl--generic-method-info method
)))
393 (insert (nth 2 info
) "\n\n"))))
394 (let ((combined-doc (buffer-string)))
395 (if ud
(help-add-fundoc-usage combined-doc
(car ud
)) combined-doc
)))))
398 (defmacro cl-defmethod
(name args
&rest body
)
399 "Define a new method for generic function NAME.
400 I.e. it defines the implementation of NAME to use for invocations where the
401 values of the dispatch arguments match the specified TYPEs.
402 The dispatch arguments have to be among the mandatory arguments, and
403 all methods of NAME have to use the same set of arguments for dispatch.
404 Each dispatch argument and TYPE are specified in ARGS where the corresponding
405 formal argument appears as (VAR TYPE) rather than just VAR.
407 The optional second argument QUALIFIER is a specifier that
408 modifies how the method is combined with other methods, including:
409 :before - Method will be called before the primary
410 :after - Method will be called after the primary
411 :around - Method will be called around everything else
412 The absence of QUALIFIER means this is a \"primary\" method.
413 The set of acceptable qualifiers and their meaning is defined
414 \(and can be extended) by the methods of `cl-generic-combine-methods'.
416 ARGS can also include so-called context specializers, introduced by
417 `&context' (which should appear right after the mandatory arguments,
418 before any &optional or &rest). They have the form (EXPR TYPE) where
419 EXPR is an Elisp expression whose value should match TYPE for the
420 method to be applicable.
422 The set of acceptable TYPEs (also called \"specializers\") is defined
423 \(and can be extended) by the various methods of `cl-generic-generalizers'.
425 \(fn NAME [QUALIFIER] ARGS &rest [DOCSTRING] BODY)"
426 (declare (doc-string 3) (indent defun
)
428 (&define
; this means we are defining something
429 [&or name
("setf" name
:name setf
)]
430 ;; ^^ This is the methods symbol
431 [ &rest atom
] ; Multiple qualifiers are allowed.
432 ; Like in CLOS spec, we support
433 ; any non-list values.
434 cl-generic-method-args
; arguments
435 lambda-doc
; documentation string
436 def-body
))) ; part to be debugged
437 (let ((qualifiers nil
))
438 (while (not (listp args
))
439 (push args qualifiers
)
440 (setq args
(pop body
)))
441 (when (eq 'setf
(car-safe name
))
443 (setq name
(gv-setter (cadr name
))))
444 (pcase-let* ((`(,uses-cnm .
,fun
) (cl--generic-lambda args body
)))
446 ,(and (get name
'byte-obsolete-info
)
447 (or (not (fboundp 'byte-compile-warning-enabled-p
))
448 (byte-compile-warning-enabled-p 'obsolete
))
449 (let* ((obsolete (get name
'byte-obsolete-info
)))
450 (macroexp--warn-and-return
451 (macroexp--obsolete-warning name obsolete
"generic function")
453 ;; You could argue that `defmethod' modifies rather than defines the
454 ;; function, so warnings like "not known to be defined" are fair game.
455 ;; But in practice, it's common to use `cl-defmethod'
456 ;; without a previous `cl-defgeneric'.
457 ;; The ",'" is a no-op that pacifies check-declare.
458 (,'declare-function
,name
"")
459 (cl-generic-define-method ',name
',(nreverse qualifiers
) ',args
462 (defun cl--generic-member-method (specializers qualifiers methods
)
465 (let ((m (car methods
)))
466 (not (and (equal (cl--generic-method-specializers m
) specializers
)
467 (equal (cl--generic-method-qualifiers m
) qualifiers
)))))
468 (setq methods
(cdr methods
)))
471 (defun cl--generic-load-hist-format (name qualifiers specializers
)
472 ;; FIXME: This function is used in elisp-mode.el and
473 ;; elisp-mode-tests.el, but I still decided to use an internal name
474 ;; because these uses should be removed or moved into cl-generic.el.
475 `(,name
,qualifiers .
,specializers
))
478 (defun cl-generic-define-method (name qualifiers args uses-cnm function
)
480 ((generic (cl-generic-ensure-function name
))
481 (`(,spec-args .
,_
) (cl--generic-split-args args
))
482 (specializers (mapcar (lambda (spec-arg)
483 (if (eq '&context
(car-safe (car spec-arg
)))
484 spec-arg
(cdr spec-arg
)))
486 (method (cl--generic-make-method
487 specializers qualifiers uses-cnm function
))
488 (mt (cl--generic-method-table generic
))
489 (me (cl--generic-member-method specializers qualifiers mt
))
490 (dispatches (cl--generic-dispatches generic
))
492 (dolist (spec-arg spec-args
)
493 (let* ((key (if (eq '&context
(car-safe (car spec-arg
)))
495 (generalizers (cl-generic-generalizers (cdr spec-arg
)))
496 (x (assoc key dispatches
)))
498 (setq x
(cons key
(cl-generic-generalizers t
)))
499 (setf (cl--generic-dispatches generic
)
500 (setq dispatches
(cons x dispatches
))))
501 (dolist (generalizer generalizers
)
502 (unless (member generalizer
(cdr x
))
504 (sort (cons generalizer
(cdr x
))
506 (> (cl--generic-generalizer-priority x
)
507 (cl--generic-generalizer-priority y
)))))))
509 ;; We used to (setcar me method), but that can cause false positives in
510 ;; the hash-consing table of the method-builder (bug#20644).
511 ;; See also the related FIXME in cl--generic-build-combined-method.
512 (setf (cl--generic-method-table generic
)
515 ;; Keep the ordering; important for methods with :extra qualifiers.
516 (mapcar (lambda (x) (if (eq x
(car me
)) method x
)) mt
)))
517 (let ((sym (cl--generic-name generic
))) ; Actual name (for aliases).
518 (unless (symbol-function sym
)
519 (defalias sym
'dummy
)) ;Record definition into load-history.
520 (cl-pushnew `(cl-defmethod .
,(cl--generic-load-hist-format
521 (cl--generic-name generic
)
522 qualifiers specializers
))
523 current-load-list
:test
#'equal
)
524 ;; FIXME: Try to avoid re-constructing a new function if the old one
525 ;; is still valid (e.g. still empty method cache)?
526 (let ((gfun (cl--generic-make-function generic
))
527 ;; Prevent `defalias' from recording this as the definition site of
528 ;; the generic function.
530 ;; BEWARE! Don't purify this function definition, since that leads
531 ;; to memory corruption if the hash-tables it holds are modified
532 ;; (the GC doesn't trace those pointers).
534 ;; But do use `defalias', so that it interacts properly with nadvice,
535 ;; e.g. for tracing/debug-on-entry.
536 (defalias sym gfun
)))))
538 (defmacro cl--generic-with-memoization
(place &rest code
)
539 (declare (indent 1) (debug t
))
540 (gv-letplace (getter setter
) place
542 ,(macroexp-let2 nil val
(macroexp-progn code
)
544 ,(funcall setter val
)
547 (defvar cl--generic-dispatchers
(make-hash-table :test
#'equal
))
549 (defun cl--generic-get-dispatcher (dispatch)
550 (cl--generic-with-memoization
551 (gethash dispatch cl--generic-dispatchers
)
552 ;; (message "cl--generic-get-dispatcher (%S)" dispatch)
553 (let* ((dispatch-arg (car dispatch
))
554 (generalizers (cdr dispatch
))
557 (mapcar (lambda (generalizer)
558 (funcall (cl--generic-generalizer-tagcode-function
564 (lambda (generalizer)
565 `(funcall ',(cl--generic-generalizer-specializers-function
567 ,(funcall (cl--generic-generalizer-tagcode-function
572 ;; Minor optimization: since this tag-exp is
573 ;; only used to lookup the method-cache, it
574 ;; doesn't matter if the default value is some
576 `(or ,@(if (macroexp-const-p (car (last tagcodes
)))
580 (dispatch-idx dispatch-arg
)
582 (when (eq '&context
(car-safe dispatch-arg
))
583 (setq bindings
`((arg ,(cdr dispatch-arg
))))
585 (setq dispatch-idx
0))
586 (dotimes (i dispatch-idx
)
587 (push (make-symbol (format "arg%d" (- dispatch-idx i
1))) fixedargs
))
588 ;; FIXME: For generic functions with a single method (or with 2 methods,
589 ;; one of which always matches), using a tagcode + hash-table is
590 ;; overkill: better just use a `cl-typep' test.
592 `(lambda (generic dispatches-left methods
)
593 (let ((method-cache (make-hash-table :test
#'eql
)))
594 (lambda (,@fixedargs
&rest args
)
596 (apply (cl--generic-with-memoization
597 (gethash ,tag-exp method-cache
)
598 (cl--generic-cache-miss
599 generic
',dispatch-arg dispatches-left methods
600 ,(if (cdr typescodes
)
601 `(append ,@typescodes
) (car typescodes
))))
602 ,@fixedargs args
)))))))))
604 (defun cl--generic-make-function (generic)
605 (cl--generic-make-next-function generic
606 (cl--generic-dispatches generic
)
607 (cl--generic-method-table generic
)))
609 (defun cl--generic-make-next-function (generic dispatches methods
)
612 (while (and dispatches
613 (let ((x (nth 1 (car dispatches
))))
614 ;; No need to dispatch for t specializers.
615 (or (null x
) (equal x cl--generic-t-generalizer
))))
616 (setq dispatches
(cdr dispatches
)))
618 (if (not (and dispatch
619 ;; If there's no method left, there's no point checking
620 ;; further arguments.
622 (cl--generic-build-combined-method generic methods
)
623 (let ((dispatcher (cl--generic-get-dispatcher dispatch
)))
624 (funcall dispatcher generic dispatches methods
)))))
626 (defvar cl--generic-combined-method-memoization
627 (make-hash-table :test
#'equal
:weakness
'value
)
628 "Table storing previously built combined-methods.
629 This is particularly useful when many different tags select the same set
630 of methods, since this table then allows us to share a single combined-method
631 for all those different tags in the method-cache.")
633 (define-error 'cl--generic-cyclic-definition
"Cyclic definition: %S")
635 (defun cl--generic-build-combined-method (generic methods
)
637 ;; Special case needed to fix a circularity during bootstrap.
638 (cl--generic-standard-method-combination generic methods
)
640 (cl--generic-with-memoization
641 ;; FIXME: Since the fields of `generic' are modified, this
642 ;; hash-table won't work right, because the hashes will change!
643 ;; It's not terribly serious, but reduces the effectiveness of
645 (gethash (cons generic methods
)
646 cl--generic-combined-method-memoization
)
647 (puthash (cons generic methods
) :cl--generic--under-construction
648 cl--generic-combined-method-memoization
)
650 (cl-generic-combine-methods generic methods
)
651 ;; Special case needed to fix a circularity during bootstrap.
652 (cl--generic-cyclic-definition
653 (cl--generic-standard-method-combination generic methods
))))))
654 (if (eq f
:cl--generic--under-construction
)
655 (signal 'cl--generic-cyclic-definition
656 (list (cl--generic-name generic
)))
659 (defun cl--generic-no-next-method-function (generic method
)
661 (apply #'cl-no-next-method generic method args
)))
663 (defun cl-generic-call-method (generic method
&optional fun
)
664 "Return a function that calls METHOD.
665 FUN is the function that should be called when METHOD calls
667 (if (not (cl--generic-method-uses-cnm method
))
668 (cl--generic-method-function method
)
669 (let ((met-fun (cl--generic-method-function method
))
670 (next (or fun
(cl--generic-no-next-method-function
674 ;; FIXME: This sucks: passing just `next' would
675 ;; be a lot more efficient than the lambda+apply
676 ;; quasi-η, but we need this to implement the
677 ;; "if call-next-method is called with no
678 ;; arguments, then use the previous arguments".
679 (lambda (&rest cnm-args
)
680 (apply next
(or cnm-args args
)))
683 ;; Standard CLOS name.
684 (defalias 'cl-method-qualifiers
#'cl--generic-method-qualifiers
)
686 (defun cl--generic-standard-method-combination (generic methods
)
687 (let ((mets-by-qual ()))
688 (dolist (method methods
)
689 (let ((qualifiers (cl-method-qualifiers method
)))
690 (if (eq (car qualifiers
) :extra
) (setq qualifiers
(cddr qualifiers
)))
691 (unless (member qualifiers
'(() (:after
) (:before
) (:around
)))
692 (error "Unsupported qualifiers in function %S: %S"
693 (cl--generic-name generic
) qualifiers
))
694 (push method
(alist-get (car qualifiers
) mets-by-qual
))))
698 (apply #'cl-no-applicable-method generic args
)))
699 ((null (alist-get nil mets-by-qual
))
701 (apply #'cl-no-primary-method generic args
)))
704 (ab-call (lambda (m) (cl-generic-call-method generic m
)))
706 (mapcar ab-call
(reverse (cdr (assoc :before mets-by-qual
)))))
707 (after (mapcar ab-call
(cdr (assoc :after mets-by-qual
)))))
708 (dolist (method (cdr (assoc nil mets-by-qual
)))
709 (setq fun
(cl-generic-call-method generic method fun
)))
710 (when (or after before
)
712 (setq fun
(lambda (&rest args
)
718 (apply af args
)))))))
719 (dolist (method (cdr (assoc :around mets-by-qual
)))
720 (setq fun
(cl-generic-call-method generic method fun
)))
723 (defun cl-generic-apply (generic args
)
724 "Like `apply' but takes a cl-generic object rather than a function."
725 ;; Handy in cl-no-applicable-method, for example.
726 ;; In Common Lisp, generic-function objects are funcallable. Ideally
727 ;; we'd want the same in Elisp, but it would either require using a very
728 ;; different (and less efficient) representation of cl--generic objects,
729 ;; or non-trivial changes in the general infrastructure (compiler and such).
730 (apply (cl--generic-name generic
) args
))
732 (defun cl--generic-arg-specializer (method dispatch-arg
)
733 (or (if (integerp dispatch-arg
)
735 (cl--generic-method-specializers method
))
736 (cdr (assoc dispatch-arg
737 (cl--generic-method-specializers method
))))
740 (defun cl--generic-cache-miss (generic
741 dispatch-arg dispatches-left methods-left types
)
743 (dolist (method methods-left
)
744 (let* ((specializer (cl--generic-arg-specializer method dispatch-arg
))
745 (m (member specializer types
)))
747 (push (cons (length m
) method
) methods
))))
748 ;; Sort the methods, most specific first.
749 ;; It would be tempting to sort them once and for all in the method-table
750 ;; rather than here, but the order might depend on the actual argument
751 ;; (e.g. for multiple inheritance with defclass).
752 (setq methods
(nreverse (mapcar #'cdr
(sort methods
#'car-less-than-car
))))
753 (cl--generic-make-next-function generic dispatches-left methods
)))
755 (cl-defgeneric cl-generic-generalizers
(specializer)
756 "Return a list of generalizers for a given SPECIALIZER.
757 To each kind of `specializer', corresponds a `generalizer' which describes
758 how to extract a \"tag\" from an object which will then let us check if this
759 object matches the specializer. A typical example of a \"tag\" would be the
760 type of an object. It's called a `generalizer' because it
761 takes a specific object and returns a more general approximation,
762 denoting a set of objects to which it belongs.
763 A generalizer gives us the chunk of code which the
764 dispatch function needs to use to extract the \"tag\" of an object, as well
765 as a function which turns this tag into an ordered list of
766 `specializers' that this object matches.
767 The code which extracts the tag should be as fast as possible.
768 The tags should be chosen according to the following rules:
769 - The tags should not be too specific: similar objects which match the
770 same list of specializers should ideally use the same (`eql') tag.
771 This insures that the cached computation of the applicable
772 methods for one object can be reused for other objects.
773 - Corollary: objects which don't match any of the relevant specializers
774 should ideally all use the same tag (typically nil).
775 This insures that this cache does not grow unnecessarily large.
776 - Two different generalizers G1 and G2 should not use the same tag
777 unless they use it for the same set of objects. IOW, if G1.tag(X1) =
778 G2.tag(X2) then G1.tag(X1) = G2.tag(X1) = G1.tag(X2) = G2.tag(X2).
779 - If G1.priority > G2.priority and G1.tag(X1) = G1.tag(X2) and this tag is
780 non-nil, then you have to make sure that the G2.tag(X1) = G2.tag(X2).
781 This is because the method-cache is only indexed with the first non-nil
782 tag (by order of decreasing priority).")
784 (cl-defgeneric cl-generic-combine-methods
(generic methods
)
785 "Build the effective method made of METHODS.
786 It should return a function that expects the same arguments as the methods, and
787 calls those methods in some appropriate order.
788 GENERIC is the generic function (mostly used for its name).
789 METHODS is the list of the selected methods.
790 The METHODS list is sorted from most specific first to most generic last.
791 The function can use `cl-generic-call-method' to create functions that call those
794 (unless (ignore-errors (cl-generic-generalizers t
))
795 ;; Temporary definition to let the next defmethod succeed.
796 (fset 'cl-generic-generalizers
797 (lambda (specializer)
798 (if (eq t specializer
) (list cl--generic-t-generalizer
))))
799 (fset 'cl-generic-combine-methods
#'cl--generic-standard-method-combination
))
801 (cl-defmethod cl-generic-generalizers (specializer)
802 "Support for the catch-all t specializer which always matches."
803 (if (eq specializer t
) (list cl--generic-t-generalizer
)
804 (error "Unknown specializer %S" specializer
)))
807 ;; This macro is brittle and only really important in order to be
808 ;; able to preload cl-generic without also preloading the byte-compiler,
809 ;; So we use `eval-when-compile' so as not keep it available longer than
811 (defmacro cl--generic-prefill-dispatchers
(arg-or-context specializer
)
812 (unless (integerp arg-or-context
)
813 (setq arg-or-context
`(&context .
,arg-or-context
)))
814 (unless (fboundp 'cl--generic-get-dispatcher
)
815 (require 'cl-generic
))
816 (let ((fun (cl--generic-get-dispatcher
817 `(,arg-or-context
,@(cl-generic-generalizers specializer
)
818 ,cl--generic-t-generalizer
))))
819 ;; Recompute dispatch at run-time, since the generalizers may be slightly
820 ;; different (e.g. byte-compiled rather than interpreted).
821 ;; FIXME: There is a risk that the run-time generalizer is not equivalent
822 ;; to the compile-time one, in which case `fun' may not be correct
824 `(let ((dispatch `(,',arg-or-context
825 ,@(cl-generic-generalizers ',specializer
)
826 ,cl--generic-t-generalizer
)))
827 ;; (message "Prefilling for %S with \n%S" dispatch ',fun)
828 (puthash dispatch
',fun cl--generic-dispatchers
)))))
830 (cl-defmethod cl-generic-combine-methods (generic methods
)
831 "Standard support for :after, :before, :around, and `:extra NAME' qualifiers."
832 (cl--generic-standard-method-combination generic methods
))
834 (defconst cl--generic-nnm-sample
(cl--generic-no-next-method-function t t
))
835 (defconst cl--generic-cnm-sample
836 (funcall (cl--generic-build-combined-method
837 nil
(list (cl--generic-make-method () () t
#'identity
)))))
839 (defun cl--generic-isnot-nnm-p (cnm)
840 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
841 ;; ¡Big Gross Ugly Hack!
842 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
843 ;; it, and some packages use it, so we need to support it.
845 (cl-assert (function-equal cnm cl--generic-cnm-sample
))
846 (if (byte-code-function-p cnm
)
847 (let ((cnm-constants (aref cnm
2))
848 (sample-constants (aref cl--generic-cnm-sample
2)))
849 (dotimes (i (length sample-constants
))
850 (when (function-equal (aref sample-constants i
)
851 cl--generic-nnm-sample
)
853 (not (function-equal (aref cnm-constants i
)
854 cl--generic-nnm-sample
))))))
855 (cl-assert (eq 'closure
(car-safe cl--generic-cnm-sample
)))
856 (let ((cnm-env (cadr cnm
)))
857 (dolist (vb (cadr cl--generic-cnm-sample
))
858 (when (function-equal (cdr vb
) cl--generic-nnm-sample
)
860 (not (function-equal (cdar cnm-env
)
861 cl--generic-nnm-sample
))))
862 (setq cnm-env
(cdr cnm-env
)))))
863 (error "Haven't found no-next-method-sample in cnm-sample")))
865 ;;; Define some pre-defined generic functions, used internally.
867 (define-error 'cl-no-method
"No method")
868 (define-error 'cl-no-next-method
"No next method" 'cl-no-method
)
869 (define-error 'cl-no-primary-method
"No primary method" 'cl-no-method
)
870 (define-error 'cl-no-applicable-method
"No applicable method"
873 (cl-defgeneric cl-no-next-method
(generic method
&rest args
)
874 "Function called when `cl-call-next-method' finds no next method."
875 (signal 'cl-no-next-method
`(,(cl--generic-name generic
) ,method
,@args
)))
877 (cl-defgeneric cl-no-applicable-method
(generic &rest args
)
878 "Function called when a method call finds no applicable method."
879 (signal 'cl-no-applicable-method
`(,(cl--generic-name generic
) ,@args
)))
881 (cl-defgeneric cl-no-primary-method
(generic &rest args
)
882 "Function called when a method call finds no primary method."
883 (signal 'cl-no-primary-method
`(,(cl--generic-name generic
) ,@args
)))
885 (defun cl-call-next-method (&rest _args
)
886 "Function to call the next applicable method.
887 Can only be used from within the lexical body of a primary or around method."
888 (error "cl-call-next-method only allowed inside primary and around methods"))
890 (defun cl-next-method-p ()
891 "Return non-nil if there is a next method.
892 Can only be used from within the lexical body of a primary or around method."
893 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
894 (error "cl-next-method-p only allowed inside primary and around methods"))
897 (defun cl-find-method (generic qualifiers specializers
)
898 (car (cl--generic-member-method
899 specializers qualifiers
900 (cl--generic-method-table (cl--generic generic
)))))
902 ;;; Add support for describe-function
904 (defun cl--generic-search-method (met-name)
905 "For `find-function-regexp-alist'. Searches for a cl-defmethod.
906 MET-NAME is as returned by `cl--generic-load-hist-format'."
907 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
908 (regexp-quote (format "%s" (car met-name
)))
912 (concat base-re
"[^&\"\n]*"
913 (mapconcat (lambda (qualifier)
914 (regexp-quote (format "%S" qualifier
)))
917 (mapconcat (lambda (specializer)
919 (format "%S" (if (consp specializer
)
920 (nth 1 specializer
) specializer
))))
921 (remq t
(cddr met-name
))
922 "[ \t\n]*)[^&\"\n]*"))
924 (re-search-forward base-re nil t
))))
926 ;; WORKAROUND: This can't be a defconst due to bug#21237.
927 (defvar cl--generic-find-defgeneric-regexp
"(\\(?:cl-\\)?defgeneric[ \t]+%s\\>")
929 (with-eval-after-load 'find-func
930 (defvar find-function-regexp-alist
)
931 (add-to-list 'find-function-regexp-alist
932 `(cl-defmethod .
,#'cl--generic-search-method
))
933 (add-to-list 'find-function-regexp-alist
934 `(cl-defgeneric . cl--generic-find-defgeneric-regexp
)))
936 (defun cl--generic-method-info (method)
937 (let* ((specializers (cl--generic-method-specializers method
))
938 (qualifiers (cl--generic-method-qualifiers method
))
939 (uses-cnm (cl--generic-method-uses-cnm method
))
940 (function (cl--generic-method-function method
))
941 (args (help-function-arglist function
'names
))
942 (docstring (documentation function
))
944 (if (null qualifiers
) ""
945 (cl-assert (consp qualifiers
))
946 (let ((s (prin1-to-string qualifiers
)))
947 (concat (substring s
1 -
1) " "))))
948 (doconly (if docstring
949 (let ((split (help-split-fundoc docstring nil
)))
950 (if split
(cdr split
) docstring
))))
952 (if uses-cnm
(setq args
(cdr args
)))
953 (dolist (specializer specializers
)
954 (let ((arg (if (eq '&rest
(car args
))
955 (intern (format "arg%d" (length combined-args
)))
957 (push (if (eq specializer t
) arg
(list arg specializer
))
959 (setq combined-args
(append (nreverse combined-args
) args
))
960 (list qual-string combined-args doconly
)))
962 (add-hook 'help-fns-describe-function-functions
#'cl--generic-describe
)
963 (defun cl--generic-describe (function)
964 ;; Supposedly this is called from help-fns, so help-fns should be loaded at
966 (declare-function help-fns-short-filename
"help-fns" (filename))
967 (let ((generic (if (symbolp function
) (cl--generic function
))))
969 (require 'help-mode
) ;Needed for `help-function-def' button!
971 (insert "\n\nThis is a generic function.\n\n")
972 (insert (propertize "Implementations:\n\n" 'face
'bold
))
973 ;; Loop over fanciful generics
974 (dolist (method (cl--generic-method-table generic
))
975 (let* ((info (cl--generic-method-info method
)))
976 ;; FIXME: Add hyperlinks for the types as well.
977 (insert (format "%s%S" (nth 0 info
) (nth 1 info
)))
978 (let* ((met-name (cl--generic-load-hist-format
980 (cl--generic-method-qualifiers method
)
981 (cl--generic-method-specializers method
)))
982 (file (find-lisp-object-file-name met-name
'cl-defmethod
)))
984 (insert (substitute-command-keys " in `"))
985 (help-insert-xref-button (help-fns-short-filename file
)
986 'help-function-def met-name file
988 (insert (substitute-command-keys "'.\n"))))
989 (insert "\n" (or (nth 2 info
) "Undocumented") "\n\n")))))))
991 (defun cl--generic-specializers-apply-to-type-p (specializers type
)
992 "Return non-nil if a method with SPECIALIZERS applies to TYPE."
994 (dolist (specializer specializers
)
995 (if (memq (car-safe specializer
) '(subclass eieio--static
))
996 (setq specializer
(nth 1 specializer
)))
997 ;; Don't include the methods that are "too generic", such as those
998 ;; applying to `eieio-default-superclass'.
999 (and (not (memq specializer
'(t eieio-default-superclass
)))
1000 (or (equal type specializer
)
1001 (when (symbolp specializer
)
1002 (let ((sclass (cl--find-class specializer
))
1003 (tclass (cl--find-class type
)))
1004 (when (and sclass tclass
)
1005 (member specializer
(cl--generic-class-parents tclass
))))))
1009 (defun cl-generic-all-functions (&optional type
)
1010 "Return a list of all generic functions.
1011 Optional TYPE argument returns only those functions that contain
1016 (let ((generic (and (fboundp symbol
) (cl--generic symbol
))))
1019 (if (null type
) (throw 'found t
))
1020 (dolist (method (cl--generic-method-table generic
))
1021 (if (cl--generic-specializers-apply-to-type-p
1022 (cl--generic-method-specializers method
) type
)
1027 (defun cl--generic-method-documentation (function type
)
1028 "Return info for all methods of FUNCTION (a symbol) applicable to TYPE.
1029 The value returned is a list of elements of the form
1030 \(QUALIFIERS ARGS DOC)."
1031 (let ((generic (cl--generic function
))
1034 (dolist (method (cl--generic-method-table generic
))
1035 (when (cl--generic-specializers-apply-to-type-p
1036 (cl--generic-method-specializers method
) type
)
1037 (push (cl--generic-method-info method
) docs
))))
1040 (defun cl--generic-method-files (method)
1041 "Return a list of files where METHOD is defined by `cl-defmethod'.
1042 The list will have entries of the form (FILE . (METHOD ...))
1043 where (METHOD ...) contains the qualifiers and specializers of
1044 the method and is a suitable argument for
1045 `find-function-search-for-symbol'. Filenames are absolute."
1047 (pcase-dolist (`(,file .
,defs
) load-history
)
1049 (when (and (eq (car-safe def
) 'cl-defmethod
)
1050 (eq (cadr def
) method
))
1051 (push (cons file
(cdr def
)) result
))))
1054 ;;; Support for (head <val>) specializers.
1056 ;; For both the `eql' and the `head' specializers, the dispatch
1057 ;; is unsatisfactory. Basically, in the "common&fast case", we end up doing
1059 ;; (let ((tag (gethash value <tagcode-hashtable>)))
1060 ;; (funcall (gethash tag <method-cache>)))
1062 ;; whereas we'd like to just do
1064 ;; (funcall (gethash value <method-cache>)))
1066 ;; but the problem is that the method-cache is normally "open ended", so
1067 ;; a nil means "not computed yet" and if we bump into it, we dutifully fill the
1068 ;; corresponding entry, whereas we'd want to just fallback on some default
1069 ;; effective method (so as not to fill the cache with lots of redundant
1072 (defvar cl--generic-head-used
(make-hash-table :test
#'eql
))
1074 (cl-generic-define-generalizer cl--generic-head-generalizer
1075 80 (lambda (name &rest _
) `(gethash (car-safe ,name
) cl--generic-head-used
))
1076 (lambda (tag &rest _
) (if (eq (car-safe tag
) 'head
) (list tag
))))
1078 (cl-defmethod cl-generic-generalizers :extra
"head" (specializer)
1079 "Support for (head VAL) specializers.
1080 These match if the argument is a cons cell whose car is `eql' to VAL."
1081 ;; We have to implement `head' here using the :extra qualifier,
1082 ;; since we can't use the `head' specializer to implement itself.
1083 (if (not (eq (car-safe specializer
) 'head
))
1084 (cl-call-next-method)
1085 (cl--generic-with-memoization
1086 (gethash (cadr specializer
) cl--generic-head-used
) specializer
)
1087 (list cl--generic-head-generalizer
)))
1089 (cl--generic-prefill-dispatchers 0 (head eql
))
1091 ;;; Support for (eql <val>) specializers.
1093 (defvar cl--generic-eql-used
(make-hash-table :test
#'eql
))
1095 (cl-generic-define-generalizer cl--generic-eql-generalizer
1096 100 (lambda (name &rest _
) `(gethash ,name cl--generic-eql-used
))
1097 (lambda (tag &rest _
) (if (eq (car-safe tag
) 'eql
) (list tag
))))
1099 (cl-defmethod cl-generic-generalizers ((specializer (head eql
)))
1100 "Support for (eql VAL) specializers.
1101 These match if the argument is `eql' to VAL."
1102 (puthash (cadr specializer
) specializer cl--generic-eql-used
)
1103 (list cl--generic-eql-generalizer
))
1105 (cl--generic-prefill-dispatchers 0 (eql nil
))
1106 (cl--generic-prefill-dispatchers window-system
(eql nil
))
1107 (cl--generic-prefill-dispatchers (terminal-parameter nil
'xterm--get-selection
)
1109 (cl--generic-prefill-dispatchers (terminal-parameter nil
'xterm--set-selection
)
1112 ;;; Support for cl-defstructs specializers.
1114 (defun cl--generic-struct-tag (name &rest _
)
1115 ;; Use exactly the same code as for `typeof'.
1116 `(if ,name
(type-of ,name
) 'null
))
1118 (defun cl--generic-class-parents (class)
1120 (classes (list class
)))
1121 ;; BFS precedence. FIXME: Use a topological sort.
1122 (while (let ((class (pop classes
)))
1123 (cl-pushnew (cl--class-name class
) parents
)
1126 (cl--class-parents class
)))))
1127 (nreverse parents
)))
1129 (defun cl--generic-struct-specializers (tag &rest _
)
1131 (let ((class (get tag
'cl--class
)))
1132 (when (cl-typep class
'cl-structure-class
)
1133 (cl--generic-class-parents class
)))))
1135 (cl-generic-define-generalizer cl--generic-struct-generalizer
1136 50 #'cl--generic-struct-tag
1137 #'cl--generic-struct-specializers
)
1139 (cl-defmethod cl-generic-generalizers :extra
"cl-struct" (type)
1140 "Support for dispatch on types defined by `cl-defstruct'."
1142 (when (symbolp type
)
1143 ;; Use the "cl--struct-class*" (inlinable) functions/macros rather than
1144 ;; the "cl-struct-*" variants which aren't inlined, so that dispatch can
1145 ;; take place without requiring cl-lib.
1146 (let ((class (cl--find-class type
)))
1147 (and (cl-typep class
'cl-structure-class
)
1148 (or (null (cl--struct-class-type class
))
1149 (error "Can't dispatch on cl-struct %S: type is %S"
1150 type
(cl--struct-class-type class
)))
1151 (progn (cl-assert (null (cl--struct-class-named class
))) t
)
1152 (list cl--generic-struct-generalizer
))))
1153 (cl-call-next-method)))
1155 (cl--generic-prefill-dispatchers 0 cl--generic-generalizer
)
1157 ;;; Dispatch on "system types".
1159 (defconst cl--generic-typeof-types
1160 ;; Hand made from the source code of `type-of'.
1161 '((integer number number-or-marker atom
)
1162 (symbol atom
) (string array sequence atom
)
1163 (cons list sequence
)
1164 ;; Markers aren't `numberp', yet they are accepted wherever integers are
1165 ;; accepted, pretty much.
1166 (marker number-or-marker atom
)
1167 (overlay atom
) (float number atom
) (window-configuration atom
)
1168 (process atom
) (window atom
) (subr atom
) (compiled-function function atom
)
1169 (buffer atom
) (char-table array sequence atom
)
1170 (bool-vector array sequence atom
)
1171 (frame atom
) (hash-table atom
) (terminal atom
)
1172 (thread atom
) (mutex atom
) (condvar atom
)
1173 (font-spec atom
) (font-entity atom
) (font-object atom
)
1174 (vector array sequence atom
)
1175 ;; Plus, really hand made:
1176 (null symbol list sequence atom
))
1177 "Alist of supertypes.
1178 Each element has the form (TYPE . SUPERTYPES) where TYPE is one of
1179 the symbols returned by `type-of', and SUPERTYPES is the list of its
1180 supertypes from the most specific to least specific.")
1182 (defconst cl--generic-all-builtin-types
1183 (delete-dups (copy-sequence (apply #'append cl--generic-typeof-types
))))
1185 (cl-generic-define-generalizer cl--generic-typeof-generalizer
1186 ;; FIXME: We could also change `type-of' to return `null' for nil.
1187 10 (lambda (name &rest _
) `(if ,name
(type-of ,name
) 'null
))
1188 (lambda (tag &rest _
)
1189 (and (symbolp tag
) (assq tag cl--generic-typeof-types
))))
1191 (cl-defmethod cl-generic-generalizers :extra
"typeof" (type)
1192 "Support for dispatch on builtin types.
1193 See the full list and their hierarchy in `cl--generic-typeof-types'."
1194 ;; FIXME: Add support for other types accepted by `cl-typep' such
1195 ;; as `character', `face', `function', ...
1197 (and (memq type cl--generic-all-builtin-types
)
1199 ;; FIXME: While this wrinkle in the semantics can be occasionally
1200 ;; problematic, this warning is more often annoying than helpful.
1201 ;;(if (memq type '(vector array sequence))
1202 ;; (message "`%S' also matches CL structs and EIEIO classes"
1204 (list cl--generic-typeof-generalizer
)))
1205 (cl-call-next-method)))
1207 (cl--generic-prefill-dispatchers 0 integer
)
1209 ;;; Dispatch on major mode.
1212 ;; - first define a specializer (derived-mode <mode>) to match symbols
1213 ;; representing major modes, while obeying the major mode hierarchy.
1214 ;; - then define a context-rewriter so you can write
1215 ;; "&context (major-mode c-mode)" rather than
1216 ;; "&context (major-mode (derived-mode c-mode))".
1218 (defun cl--generic-derived-specializers (mode &rest _
)
1219 ;; FIXME: Handle (derived-mode <mode1> ... <modeN>)
1220 (let ((specializers ()))
1222 (push `(derived-mode ,mode
) specializers
)
1223 (setq mode
(get mode
'derived-mode-parent
)))
1224 (nreverse specializers
)))
1226 (cl-generic-define-generalizer cl--generic-derived-generalizer
1227 90 (lambda (name) `(and (symbolp ,name
) (functionp ,name
) ,name
))
1228 #'cl--generic-derived-specializers
)
1230 (cl-defmethod cl-generic-generalizers ((_specializer (head derived-mode
)))
1231 "Support for (derived-mode MODE) specializers.
1232 Used internally for the (major-mode MODE) context specializers."
1233 (list cl--generic-derived-generalizer
))
1235 (cl-generic-define-context-rewriter major-mode
(mode &rest modes
)
1236 `(major-mode ,(if (consp mode
)
1237 ;;E.g. could be (eql ...)
1238 (progn (cl-assert (null modes
)) mode
)
1239 `(derived-mode ,mode .
,modes
))))
1241 ;;; Support for unloading.
1243 (cl-defmethod loadhist-unload-element ((x (head cl-defmethod
)))
1245 ((`(,name
,qualifiers .
,specializers
) (cdr x
))
1246 (generic (cl-generic-ensure-function name
'noerror
)))
1248 (let* ((mt (cl--generic-method-table generic
))
1249 (me (cl--generic-member-method specializers qualifiers mt
)))
1251 (setf (cl--generic-method-table generic
) (delq (car me
) mt
)))))))
1254 (provide 'cl-generic
)
1255 ;;; cl-generic.el ends here