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