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