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