Prevent name clashes between CL structures and builtin types
[emacs.git] / lisp / emacs-lisp / cl-generic.el
blob173173305b4a045aa59bc538f0fc8fa3f29f2682
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>
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 <https://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-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)
174 (let (generic
175 (origname name))
176 (while (and (null (setq generic (cl--generic name)))
177 (fboundp name)
178 (null noerror)
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)
184 noerror)
185 (error "%s is already defined as something else than a generic function"
186 origname))
187 (if generic
188 (cl-assert (eq name (cl--generic-name generic)))
189 (setf (cl--generic name) (setq generic (cl--generic-make name))))
190 generic))
192 ;;;###autoload
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)
208 (debug
209 (&define [&or name ("setf" name :name setf)] listp
210 lambda-doc
211 [&rest [&or
212 ("declare" &rest sexp)
213 (":argument-precedence-order" &rest sexp)
214 (&define ":method" [&rest atom]
215 cl-generic-method-args lambda-doc
216 def-body)]]
217 def-body)))
218 (let* ((doc (if (stringp (car-safe options-and-methods))
219 (pop options-and-methods)))
220 (declarations nil)
221 (methods ())
222 (options ())
223 next-head)
224 (while (progn (setq next-head (car-safe (car options-and-methods)))
225 (or (keywordp next-head)
226 (eq next-head 'declare)))
227 (pcase next-head
228 (`:documentation
229 (when doc (error "Multiple doc strings for %S" name))
230 (setq doc (cadr (pop options-and-methods))))
231 (`declare
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))
240 (require 'gv)
241 (setq name (gv-setter (cadr name))))
242 `(prog1
243 (progn
244 (defalias ',name
245 (cl-generic-define ',name ',args ',(nreverse options))
246 ,(help-add-fundoc-usage doc args))
247 :autoload-end
248 ,@(mapcar (lambda (method) `(cl-defmethod ,name ,@method))
249 (nreverse methods)))
250 ,@(mapcar (lambda (declaration)
251 (let ((f (cdr (assq (car declaration)
252 defun-declarations-alist))))
253 (cond
254 (f (apply (car f) name args (cdr declaration)))
255 (t (message "Warning: Unknown defun property `%S' in %S"
256 (car declaration) name)
257 nil))))
258 (cdr declarations)))))
260 ;;;###autoload
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))
270 (when apo
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))
292 `(eval-and-compile
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."
299 (let ((res '()))
300 (while (consp 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))
304 res))
306 (defun cl--generic-split-args (args)
307 "Return (SPEC-ARGS . PLAIN-ARGS)."
308 (let ((plain-args ())
309 (specializers nil)
310 (mandatory t))
311 (dolist (arg args)
312 (push (pcase arg
313 ((or '&optional '&rest '&key) (setq mandatory nil) arg)
314 ('&context
315 (unless mandatory
316 (error "&context not immediately after mandatory args"))
317 (setq mandatory 'context) nil)
318 ((let 'nil mandatory) arg)
319 ((let 'context mandatory)
320 (unless (consp arg)
321 (error "Invalid &context arg: %S" arg))
322 (let* ((name (car arg))
323 (rewriter
324 (and (symbolp name)
325 (get name 'cl-generic--context-rewriter))))
326 (if rewriter (setq arg (apply rewriter (cdr arg)))))
327 (push `((&context . ,(car arg)) . ,(cadr arg)) specializers)
328 nil)
329 (`(,name . ,type)
330 (push (cons name (car type)) specializers)
331 name)
333 (push (cons arg t) specializers)
334 arg))
335 plain-args))
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))
358 ,@(cdr parsed-body))
359 macroenv))
360 ;; FIXME: Rather than `grep' after the fact, the
361 ;; macroexpansion should directly set some flag when cnm
362 ;; is used.
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)
368 ,@(car parsed-body)
369 ,(if (not (memq nmp uses-cnm))
370 nbody
371 `(let ((,nmp (lambda ()
372 (cl--generic-isnot-nnm-p ,cnm))))
373 ,nbody))))))
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.
385 (require 'help-fns)
386 (with-temp-buffer
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)))
392 (when (nth 2 info)
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)))))
397 ;;;###autoload
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)
427 (debug
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))
442 (require 'gv)
443 (setq name (gv-setter (cadr name))))
444 (pcase-let* ((`(,uses-cnm . ,fun) (cl--generic-lambda args body)))
445 `(progn
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")
452 nil)))
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
460 ,uses-cnm ,fun)))))
462 (defun cl--generic-member-method (specializers qualifiers methods)
463 (while
464 (and 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)))
469 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))
477 ;;;###autoload
478 (defun cl-generic-define-method (name qualifiers args uses-cnm function)
479 (pcase-let*
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)))
485 spec-args))
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))
491 (i 0))
492 (dolist (spec-arg spec-args)
493 (let* ((key (if (eq '&context (car-safe (car spec-arg)))
494 (car spec-arg) i))
495 (generalizers (cl-generic-generalizers (cdr spec-arg)))
496 (x (assoc key dispatches)))
497 (unless x
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))
503 (setf (cdr x)
504 (sort (cons generalizer (cdr x))
505 (lambda (x y)
506 (> (cl--generic-generalizer-priority x)
507 (cl--generic-generalizer-priority y)))))))
508 (setq i (1+ i))))
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)
513 (if (null me)
514 (cons method mt)
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.
529 current-load-list
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).
533 (purify-flag nil))
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
541 `(or ,getter
542 ,(macroexp-let2 nil val (macroexp-progn code)
543 `(progn
544 ,(funcall setter val)
545 ,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))
555 (lexical-binding t)
556 (tagcodes
557 (mapcar (lambda (generalizer)
558 (funcall (cl--generic-generalizer-tagcode-function
559 generalizer)
560 'arg))
561 generalizers))
562 (typescodes
563 (mapcar
564 (lambda (generalizer)
565 `(funcall ',(cl--generic-generalizer-specializers-function
566 generalizer)
567 ,(funcall (cl--generic-generalizer-tagcode-function
568 generalizer)
569 'arg)))
570 generalizers))
571 (tag-exp
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
575 ;; constant or nil.
576 `(or ,@(if (macroexp-const-p (car (last tagcodes)))
577 (butlast tagcodes)
578 tagcodes)))
579 (fixedargs '(arg))
580 (dispatch-idx dispatch-arg)
581 (bindings nil))
582 (when (eq '&context (car-safe dispatch-arg))
583 (setq bindings `((arg ,(cdr dispatch-arg))))
584 (setq fixedargs nil)
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.
591 (byte-compile
592 `(lambda (generic dispatches-left methods)
593 (let ((method-cache (make-hash-table :test #'eql)))
594 (lambda (,@fixedargs &rest args)
595 (let ,bindings
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)
610 (let* ((dispatch
611 (progn
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)))
617 (pop dispatches))))
618 (if (not (and dispatch
619 ;; If there's no method left, there's no point checking
620 ;; further arguments.
621 methods))
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)
636 (if (null methods)
637 ;; Special case needed to fix a circularity during bootstrap.
638 (cl--generic-standard-method-combination generic methods)
639 (let ((f
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
644 ;; the table.
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)
649 (condition-case nil
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)))
657 f))))
659 (defun cl--generic-no-next-method-function (generic method)
660 (lambda (&rest args)
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
666 `call-next-method'."
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
671 generic method))))
672 (lambda (&rest args)
673 (apply met-fun
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)))
681 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))))
695 (cond
696 ((null mets-by-qual)
697 (lambda (&rest args)
698 (apply #'cl-no-applicable-method generic args)))
699 ((null (alist-get nil mets-by-qual))
700 (lambda (&rest args)
701 (apply #'cl-no-primary-method generic args)))
703 (let* ((fun nil)
704 (ab-call (lambda (m) (cl-generic-call-method generic m)))
705 (before
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)
711 (let ((next fun))
712 (setq fun (lambda (&rest args)
713 (dolist (bf before)
714 (apply bf args))
715 (prog1
716 (apply next args)
717 (dolist (af after)
718 (apply af args)))))))
719 (dolist (method (cdr (assoc :around mets-by-qual)))
720 (setq fun (cl-generic-call-method generic method fun)))
721 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)
734 (nth 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)
742 (let ((methods '()))
743 (dolist (method methods-left)
744 (let* ((specializer (cl--generic-arg-specializer method dispatch-arg))
745 (m (member specializer types)))
746 (when m
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
792 methods.")
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)))
806 (eval-when-compile
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
810 ;; strictly needed.
811 (defmacro cl--generic-prefill-dispatchers (arg-or-context &rest specializers)
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
818 ,@(apply #'append
819 (mapcar #'cl-generic-generalizers specializers))
820 ,cl--generic-t-generalizer))))
821 ;; Recompute dispatch at run-time, since the generalizers may be slightly
822 ;; different (e.g. byte-compiled rather than interpreted).
823 ;; FIXME: There is a risk that the run-time generalizer is not equivalent
824 ;; to the compile-time one, in which case `fun' may not be correct
825 ;; any more!
826 `(let ((dispatch
827 `(,',arg-or-context
828 ,@(apply #'append
829 (mapcar #'cl-generic-generalizers ',specializers))
830 ,cl--generic-t-generalizer)))
831 ;; (message "Prefilling for %S with \n%S" dispatch ',fun)
832 (puthash dispatch ',fun cl--generic-dispatchers)))))
834 (cl-defmethod cl-generic-combine-methods (generic methods)
835 "Standard support for :after, :before, :around, and `:extra NAME' qualifiers."
836 (cl--generic-standard-method-combination generic methods))
838 (defconst cl--generic-nnm-sample (cl--generic-no-next-method-function t t))
839 (defconst cl--generic-cnm-sample
840 (funcall (cl--generic-build-combined-method
841 nil (list (cl--generic-make-method () () t #'identity)))))
843 (defun cl--generic-isnot-nnm-p (cnm)
844 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
845 ;; ¡Big Gross Ugly Hack!
846 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
847 ;; it, and some packages use it, so we need to support it.
848 (catch 'found
849 (cl-assert (function-equal cnm cl--generic-cnm-sample))
850 (if (byte-code-function-p cnm)
851 (let ((cnm-constants (aref cnm 2))
852 (sample-constants (aref cl--generic-cnm-sample 2)))
853 (dotimes (i (length sample-constants))
854 (when (function-equal (aref sample-constants i)
855 cl--generic-nnm-sample)
856 (throw 'found
857 (not (function-equal (aref cnm-constants i)
858 cl--generic-nnm-sample))))))
859 (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
860 (let ((cnm-env (cadr cnm)))
861 (dolist (vb (cadr cl--generic-cnm-sample))
862 (when (function-equal (cdr vb) cl--generic-nnm-sample)
863 (throw 'found
864 (not (function-equal (cdar cnm-env)
865 cl--generic-nnm-sample))))
866 (setq cnm-env (cdr cnm-env)))))
867 (error "Haven't found no-next-method-sample in cnm-sample")))
869 ;;; Define some pre-defined generic functions, used internally.
871 (define-error 'cl-no-method "No method")
872 (define-error 'cl-no-next-method "No next method" 'cl-no-method)
873 (define-error 'cl-no-primary-method "No primary method" 'cl-no-method)
874 (define-error 'cl-no-applicable-method "No applicable method"
875 'cl-no-method)
877 (cl-defgeneric cl-no-next-method (generic method &rest args)
878 "Function called when `cl-call-next-method' finds no next method."
879 (signal 'cl-no-next-method `(,(cl--generic-name generic) ,method ,@args)))
881 (cl-defgeneric cl-no-applicable-method (generic &rest args)
882 "Function called when a method call finds no applicable method."
883 (signal 'cl-no-applicable-method `(,(cl--generic-name generic) ,@args)))
885 (cl-defgeneric cl-no-primary-method (generic &rest args)
886 "Function called when a method call finds no primary method."
887 (signal 'cl-no-primary-method `(,(cl--generic-name generic) ,@args)))
889 (defun cl-call-next-method (&rest _args)
890 "Function to call the next applicable method.
891 Can only be used from within the lexical body of a primary or around method."
892 (error "cl-call-next-method only allowed inside primary and around methods"))
894 (defun cl-next-method-p ()
895 "Return non-nil if there is a next method.
896 Can only be used from within the lexical body of a primary or around method."
897 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
898 (error "cl-next-method-p only allowed inside primary and around methods"))
900 ;;;###autoload
901 (defun cl-find-method (generic qualifiers specializers)
902 (car (cl--generic-member-method
903 specializers qualifiers
904 (cl--generic-method-table (cl--generic generic)))))
906 ;;; Add support for describe-function
908 (defun cl--generic-search-method (met-name)
909 "For `find-function-regexp-alist'. Searches for a cl-defmethod.
910 MET-NAME is as returned by `cl--generic-load-hist-format'."
911 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
912 (regexp-quote (format "%s" (car met-name)))
913 "\\_>")))
915 (re-search-forward
916 (concat base-re "[^&\"\n]*"
917 (mapconcat (lambda (qualifier)
918 (regexp-quote (format "%S" qualifier)))
919 (cadr met-name)
920 "[ \t\n]*")
921 (mapconcat (lambda (specializer)
922 (regexp-quote
923 (format "%S" (if (consp specializer)
924 (nth 1 specializer) specializer))))
925 (remq t (cddr met-name))
926 "[ \t\n]*)[^&\"\n]*"))
927 nil t)
928 (re-search-forward base-re nil t))))
930 ;; WORKAROUND: This can't be a defconst due to bug#21237.
931 (defvar cl--generic-find-defgeneric-regexp "(\\(?:cl-\\)?defgeneric[ \t]+%s\\>")
933 (with-eval-after-load 'find-func
934 (defvar find-function-regexp-alist)
935 (add-to-list 'find-function-regexp-alist
936 `(cl-defmethod . ,#'cl--generic-search-method))
937 (add-to-list 'find-function-regexp-alist
938 `(cl-defgeneric . cl--generic-find-defgeneric-regexp)))
940 (defun cl--generic-method-info (method)
941 (let* ((specializers (cl--generic-method-specializers method))
942 (qualifiers (cl--generic-method-qualifiers method))
943 (uses-cnm (cl--generic-method-uses-cnm method))
944 (function (cl--generic-method-function method))
945 (args (help-function-arglist function 'names))
946 (docstring (documentation function))
947 (qual-string
948 (if (null qualifiers) ""
949 (cl-assert (consp qualifiers))
950 (let ((s (prin1-to-string qualifiers)))
951 (concat (substring s 1 -1) " "))))
952 (doconly (if docstring
953 (let ((split (help-split-fundoc docstring nil)))
954 (if split (cdr split) docstring))))
955 (combined-args ()))
956 (if uses-cnm (setq args (cdr args)))
957 (dolist (specializer specializers)
958 (let ((arg (if (eq '&rest (car args))
959 (intern (format "arg%d" (length combined-args)))
960 (pop args))))
961 (push (if (eq specializer t) arg (list arg specializer))
962 combined-args)))
963 (setq combined-args (append (nreverse combined-args) args))
964 (list qual-string combined-args doconly)))
966 (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
967 (defun cl--generic-describe (function)
968 ;; Supposedly this is called from help-fns, so help-fns should be loaded at
969 ;; this point.
970 (declare-function help-fns-short-filename "help-fns" (filename))
971 (let ((generic (if (symbolp function) (cl--generic function))))
972 (when generic
973 (require 'help-mode) ;Needed for `help-function-def' button!
974 (save-excursion
975 (insert "\n\nThis is a generic function.\n\n")
976 (insert (propertize "Implementations:\n\n" 'face 'bold))
977 ;; Loop over fanciful generics
978 (dolist (method (cl--generic-method-table generic))
979 (let* ((info (cl--generic-method-info method)))
980 ;; FIXME: Add hyperlinks for the types as well.
981 (insert (format "%s%S" (nth 0 info) (nth 1 info)))
982 (let* ((met-name (cl--generic-load-hist-format
983 function
984 (cl--generic-method-qualifiers method)
985 (cl--generic-method-specializers method)))
986 (file (find-lisp-object-file-name met-name 'cl-defmethod)))
987 (when file
988 (insert (substitute-command-keys " in `"))
989 (help-insert-xref-button (help-fns-short-filename file)
990 'help-function-def met-name file
991 'cl-defmethod)
992 (insert (substitute-command-keys "'.\n"))))
993 (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
995 (defun cl--generic-specializers-apply-to-type-p (specializers type)
996 "Return non-nil if a method with SPECIALIZERS applies to TYPE."
997 (let ((applies nil))
998 (dolist (specializer specializers)
999 (if (memq (car-safe specializer) '(subclass eieio--static))
1000 (setq specializer (nth 1 specializer)))
1001 ;; Don't include the methods that are "too generic", such as those
1002 ;; applying to `eieio-default-superclass'.
1003 (and (not (memq specializer '(t eieio-default-superclass)))
1004 (or (equal type specializer)
1005 (when (symbolp specializer)
1006 (let ((sclass (cl--find-class specializer))
1007 (tclass (cl--find-class type)))
1008 (when (and sclass tclass)
1009 (member specializer (cl--generic-class-parents tclass))))))
1010 (setq applies t)))
1011 applies))
1013 (defun cl-generic-all-functions (&optional type)
1014 "Return a list of all generic functions.
1015 Optional TYPE argument returns only those functions that contain
1016 methods for TYPE."
1017 (let ((l nil))
1018 (mapatoms
1019 (lambda (symbol)
1020 (let ((generic (and (fboundp symbol) (cl--generic symbol))))
1021 (and generic
1022 (catch 'found
1023 (if (null type) (throw 'found t))
1024 (dolist (method (cl--generic-method-table generic))
1025 (if (cl--generic-specializers-apply-to-type-p
1026 (cl--generic-method-specializers method) type)
1027 (throw 'found t))))
1028 (push symbol l)))))
1031 (defun cl--generic-method-documentation (function type)
1032 "Return info for all methods of FUNCTION (a symbol) applicable to TYPE.
1033 The value returned is a list of elements of the form
1034 \(QUALIFIERS ARGS DOC)."
1035 (let ((generic (cl--generic function))
1036 (docs ()))
1037 (when generic
1038 (dolist (method (cl--generic-method-table generic))
1039 (when (cl--generic-specializers-apply-to-type-p
1040 (cl--generic-method-specializers method) type)
1041 (push (cl--generic-method-info method) docs))))
1042 docs))
1044 (defun cl--generic-method-files (method)
1045 "Return a list of files where METHOD is defined by `cl-defmethod'.
1046 The list will have entries of the form (FILE . (METHOD ...))
1047 where (METHOD ...) contains the qualifiers and specializers of
1048 the method and is a suitable argument for
1049 `find-function-search-for-symbol'. Filenames are absolute."
1050 (let (result)
1051 (pcase-dolist (`(,file . ,defs) load-history)
1052 (dolist (def defs)
1053 (when (and (eq (car-safe def) 'cl-defmethod)
1054 (eq (cadr def) method))
1055 (push (cons file (cdr def)) result))))
1056 result))
1058 ;;; Support for (head <val>) specializers.
1060 ;; For both the `eql' and the `head' specializers, the dispatch
1061 ;; is unsatisfactory. Basically, in the "common&fast case", we end up doing
1063 ;; (let ((tag (gethash value <tagcode-hashtable>)))
1064 ;; (funcall (gethash tag <method-cache>)))
1066 ;; whereas we'd like to just do
1068 ;; (funcall (gethash value <method-cache>)))
1070 ;; but the problem is that the method-cache is normally "open ended", so
1071 ;; a nil means "not computed yet" and if we bump into it, we dutifully fill the
1072 ;; corresponding entry, whereas we'd want to just fallback on some default
1073 ;; effective method (so as not to fill the cache with lots of redundant
1074 ;; entries).
1076 (defvar cl--generic-head-used (make-hash-table :test #'eql))
1078 (cl-generic-define-generalizer cl--generic-head-generalizer
1079 80 (lambda (name &rest _) `(gethash (car-safe ,name) cl--generic-head-used))
1080 (lambda (tag &rest _) (if (eq (car-safe tag) 'head) (list tag))))
1082 (cl-defmethod cl-generic-generalizers :extra "head" (specializer)
1083 "Support for (head VAL) specializers.
1084 These match if the argument is a cons cell whose car is `eql' to VAL."
1085 ;; We have to implement `head' here using the :extra qualifier,
1086 ;; since we can't use the `head' specializer to implement itself.
1087 (if (not (eq (car-safe specializer) 'head))
1088 (cl-call-next-method)
1089 (cl--generic-with-memoization
1090 (gethash (cadr specializer) cl--generic-head-used) specializer)
1091 (list cl--generic-head-generalizer)))
1093 (cl--generic-prefill-dispatchers 0 (head eql))
1095 ;;; Support for (eql <val>) specializers.
1097 (defvar cl--generic-eql-used (make-hash-table :test #'eql))
1099 (cl-generic-define-generalizer cl--generic-eql-generalizer
1100 100 (lambda (name &rest _) `(gethash ,name cl--generic-eql-used))
1101 (lambda (tag &rest _) (if (eq (car-safe tag) 'eql) (list tag))))
1103 (cl-defmethod cl-generic-generalizers ((specializer (head eql)))
1104 "Support for (eql VAL) specializers.
1105 These match if the argument is `eql' to VAL."
1106 (puthash (cadr specializer) specializer cl--generic-eql-used)
1107 (list cl--generic-eql-generalizer))
1109 (cl--generic-prefill-dispatchers 0 (eql nil))
1110 (cl--generic-prefill-dispatchers window-system (eql nil))
1111 (cl--generic-prefill-dispatchers (terminal-parameter nil 'xterm--get-selection)
1112 (eql nil))
1113 (cl--generic-prefill-dispatchers (terminal-parameter nil 'xterm--set-selection)
1114 (eql nil))
1116 ;;; Support for cl-defstructs specializers.
1118 (defun cl--generic-struct-tag (name &rest _)
1119 ;; Use exactly the same code as for `typeof'.
1120 `(if ,name (type-of ,name) 'null))
1122 (defun cl--generic-class-parents (class)
1123 (let ((parents ())
1124 (classes (list class)))
1125 ;; BFS precedence. FIXME: Use a topological sort.
1126 (while (let ((class (pop classes)))
1127 (cl-pushnew (cl--class-name class) parents)
1128 (setq classes
1129 (append classes
1130 (cl--class-parents class)))))
1131 (nreverse parents)))
1133 (defun cl--generic-struct-specializers (tag &rest _)
1134 (and (symbolp tag)
1135 (let ((class (get tag 'cl--class)))
1136 (when (cl-typep class 'cl-structure-class)
1137 (cl--generic-class-parents class)))))
1139 (cl-generic-define-generalizer cl--generic-struct-generalizer
1140 50 #'cl--generic-struct-tag
1141 #'cl--generic-struct-specializers)
1143 (cl-defmethod cl-generic-generalizers :extra "cl-struct" (type)
1144 "Support for dispatch on types defined by `cl-defstruct'."
1146 (when (symbolp type)
1147 ;; Use the "cl--struct-class*" (inlinable) functions/macros rather than
1148 ;; the "cl-struct-*" variants which aren't inlined, so that dispatch can
1149 ;; take place without requiring cl-lib.
1150 (let ((class (cl--find-class type)))
1151 (and (cl-typep class 'cl-structure-class)
1152 (or (null (cl--struct-class-type class))
1153 (error "Can't dispatch on cl-struct %S: type is %S"
1154 type (cl--struct-class-type class)))
1155 (progn (cl-assert (null (cl--struct-class-named class))) t)
1156 (list cl--generic-struct-generalizer))))
1157 (cl-call-next-method)))
1159 (cl--generic-prefill-dispatchers 0 cl--generic-generalizer)
1161 ;;; Dispatch on "system types".
1163 (cl-generic-define-generalizer cl--generic-typeof-generalizer
1164 ;; FIXME: We could also change `type-of' to return `null' for nil.
1165 10 (lambda (name &rest _) `(if ,name (type-of ,name) 'null))
1166 (lambda (tag &rest _)
1167 (and (symbolp tag) (assq tag cl--typeof-types))))
1169 (cl-defmethod cl-generic-generalizers :extra "typeof" (type)
1170 "Support for dispatch on builtin types.
1171 See the full list and their hierarchy in `cl--typeof-types'."
1172 ;; FIXME: Add support for other types accepted by `cl-typep' such
1173 ;; as `character', `face', `function', ...
1175 (and (memq type cl--all-builtin-types)
1176 (progn
1177 ;; FIXME: While this wrinkle in the semantics can be occasionally
1178 ;; problematic, this warning is more often annoying than helpful.
1179 ;;(if (memq type '(vector array sequence))
1180 ;; (message "`%S' also matches CL structs and EIEIO classes"
1181 ;; type))
1182 (list cl--generic-typeof-generalizer)))
1183 (cl-call-next-method)))
1185 (cl--generic-prefill-dispatchers 0 integer)
1186 (cl--generic-prefill-dispatchers 0 cl--generic-generalizer integer)
1188 ;;; Dispatch on major mode.
1190 ;; Two parts:
1191 ;; - first define a specializer (derived-mode <mode>) to match symbols
1192 ;; representing major modes, while obeying the major mode hierarchy.
1193 ;; - then define a context-rewriter so you can write
1194 ;; "&context (major-mode c-mode)" rather than
1195 ;; "&context (major-mode (derived-mode c-mode))".
1197 (defun cl--generic-derived-specializers (mode &rest _)
1198 ;; FIXME: Handle (derived-mode <mode1> ... <modeN>)
1199 (let ((specializers ()))
1200 (while mode
1201 (push `(derived-mode ,mode) specializers)
1202 (setq mode (get mode 'derived-mode-parent)))
1203 (nreverse specializers)))
1205 (cl-generic-define-generalizer cl--generic-derived-generalizer
1206 90 (lambda (name) `(and (symbolp ,name) (functionp ,name) ,name))
1207 #'cl--generic-derived-specializers)
1209 (cl-defmethod cl-generic-generalizers ((_specializer (head derived-mode)))
1210 "Support for (derived-mode MODE) specializers.
1211 Used internally for the (major-mode MODE) context specializers."
1212 (list cl--generic-derived-generalizer))
1214 (cl-generic-define-context-rewriter major-mode (mode &rest modes)
1215 `(major-mode ,(if (consp mode)
1216 ;;E.g. could be (eql ...)
1217 (progn (cl-assert (null modes)) mode)
1218 `(derived-mode ,mode . ,modes))))
1220 ;;; Support for unloading.
1222 (cl-defmethod loadhist-unload-element ((x (head cl-defmethod)))
1223 (pcase-let*
1224 ((`(,name ,qualifiers . ,specializers) (cdr x))
1225 (generic (cl-generic-ensure-function name 'noerror)))
1226 (when generic
1227 (let* ((mt (cl--generic-method-table generic))
1228 (me (cl--generic-member-method specializers qualifiers mt)))
1229 (when me
1230 (setf (cl--generic-method-table generic) (delq (car me) mt)))))))
1233 (provide 'cl-generic)
1234 ;;; cl-generic.el ends here