]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/cl-generic.el
* lisp/emacs-lisp/eieio*.el: Fix up warnings and improve compatibility
[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
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; This implements the most of CLOS's multiple-dispatch generic functions.
25 ;; To use it you need either (require 'cl-generic) or (require 'cl-lib).
26 ;; The main entry points are: `cl-defgeneric' and `cl-defmethod'.
27
28 ;; Missing elements:
29 ;; - We don't support make-method, call-method, define-method-combination.
30 ;; - Method and generic function objects: CLOS defines methods as objects
31 ;; (same for generic functions), whereas we don't offer such an abstraction.
32 ;; - `no-next-method' should receive the "calling method" object, but since we
33 ;; don't have such a thing, we pass nil instead.
34 ;; - In defgeneric we don't support the options:
35 ;; declare, :method-combination, :generic-function-class, :method-class,
36 ;; :method.
37 ;; Added elements:
38 ;; - We support aliases to generic functions.
39 ;; - The kind of thing on which to dispatch can be extended.
40 ;; There is support in this file for dispatch on:
41 ;; - (eql <val>)
42 ;; - plain old types
43 ;; - type of CL structs
44 ;; eieio-core adds dispatch on:
45 ;; - class of eieio objects
46 ;; - actual class argument, using the syntax (subclass <class>).
47
48 ;; Efficiency considerations: overall, I've made an effort to make this fairly
49 ;; efficient for the expected case (e.g. no constant redefinition of methods).
50 ;; - Generic functions which do not dispatch on any argument are implemented
51 ;; optimally (just as efficient as plain old functions).
52 ;; - Generic functions which only dispatch on one argument are fairly efficient
53 ;; (not a lot of room for improvement, I think).
54 ;; - Multiple dispatch is implemented rather naively. There's an extra `apply'
55 ;; function call for every dispatch; we don't optimize each dispatch
56 ;; based on the set of candidate methods remaining; we don't optimize the
57 ;; order in which we performs the dispatches either; If/when this
58 ;; becomes a problem, we can try and optimize it.
59 ;; - call-next-method could be made more efficient, but isn't too terrible.
60
61 ;;; Code:
62
63 ;; Note: For generic functions that dispatch on several arguments (i.e. those
64 ;; which use the multiple-dispatch feature), we always use the same "tagcodes"
65 ;; and the same set of arguments on which to dispatch. This works, but is
66 ;; often suboptimal since after one dispatch, the remaining dispatches can
67 ;; usually be simplified, or even completely skipped.
68
69 (eval-when-compile (require 'cl-lib))
70 (eval-when-compile (require 'pcase))
71
72 (defvar cl-generic-tagcode-function
73 (lambda (type _name)
74 (if (eq type t) '(0 . 'cl--generic-type)
75 (error "Unknown specializer %S" type)))
76 "Function to get the Elisp code to extract the tag on which we dispatch.
77 Takes a \"parameter-specializer-name\" and a variable name, and returns
78 a pair (PRIORITY . CODE) where CODE is an Elisp expression that should be
79 used to extract the \"tag\" (from the object held in the named variable)
80 that should uniquely determine if we have a match
81 \(i.e. the \"tag\" is the value that will be used to dispatch to the proper
82 method(s)).
83 Such \"tagcodes\" will be or'd together.
84 PRIORITY is an integer from 0 to 100 which is used to sort the tagcodes
85 in the `or'. The higher the priority, the more specific the tag should be.
86 More specifically, if PRIORITY is N and we have two objects X and Y
87 whose tag (according to TAGCODE) is `eql', then it should be the case
88 that for all other (PRIORITY . TAGCODE) where PRIORITY ≤ N, then
89 \(eval TAGCODE) for X is `eql' to (eval TAGCODE) for Y.")
90
91 (defvar cl-generic-tag-types-function
92 (lambda (tag) (if (eq tag 'cl--generic-type) '(t)))
93 "Function to get the list of types that a given \"tag\" matches.
94 They should be sorted from most specific to least specific.")
95
96 (cl-defstruct (cl--generic
97 (:constructor nil)
98 (:constructor cl--generic-make
99 (name &optional dispatches method-table))
100 (:predicate nil))
101 (name nil :type symbol :read-only t) ;Pointer back to the symbol.
102 ;; `dispatches' holds a list of (ARGNUM . TAGCODES) where ARGNUM is the index
103 ;; of the corresponding argument and TAGCODES is a list of (PRIORITY . EXP)
104 ;; where the EXPs are expressions (to be `or'd together) to compute the tag
105 ;; on which to dispatch and PRIORITY is the priority of each expression to
106 ;; decide in which order to sort them.
107 ;; The most important dispatch is last in the list (and the least is first).
108 (dispatches nil :type (list-of (cons natnum (list-of tagcode))))
109 ;; `method-table' is a list of
110 ;; ((SPECIALIZERS . QUALIFIER) USES-CNM . FUNCTION), where
111 ;; USES-CNM is a boolean indicating if FUNCTION calls `cl-call-next-method'
112 ;; (and hence expects an extra argument holding the next-method).
113 (method-table nil :type (list-of (cons (cons (list-of type) keyword)
114 (cons boolean function)))))
115
116 (defmacro cl--generic (name)
117 `(get ,name 'cl--generic))
118
119 (defun cl-generic-ensure-function (name)
120 (let (generic
121 (origname name))
122 (while (and (null (setq generic (cl--generic name)))
123 (fboundp name)
124 (symbolp (symbol-function name)))
125 (setq name (symbol-function name)))
126 (unless (or (not (fboundp name))
127 (autoloadp (symbol-function name))
128 (and (functionp name) generic))
129 (error "%s is already defined as something else than a generic function"
130 origname))
131 (if generic
132 (cl-assert (eq name (cl--generic-name generic)))
133 (setf (cl--generic name) (setq generic (cl--generic-make name)))
134 (defalias name (cl--generic-make-function generic)))
135 generic))
136
137 (defun cl--generic-setf-rewrite (name)
138 (let* ((setter (intern (format "cl-generic-setter--%s" name)))
139 (exp `(unless (eq ',setter (get ',name 'cl-generic-setter))
140 ;; (when (get ',name 'gv-expander)
141 ;; (error "gv-expander conflicts with (setf %S)" ',name))
142 (setf (get ',name 'cl-generic-setter) ',setter)
143 (gv-define-setter ,name (val &rest args)
144 (cons ',setter (cons val args))))))
145 ;; Make sure `setf' can be used right away, e.g. in the body of the method.
146 (eval exp t)
147 (cons setter exp)))
148
149 ;;;###autoload
150 (defmacro cl-defgeneric (name args &rest options-and-methods)
151 "Create a generic function NAME.
152 DOC-STRING is the base documentation for this class. A generic
153 function has no body, as its purpose is to decide which method body
154 is appropriate to use. Specific methods are defined with `cl-defmethod'.
155 With this implementation the ARGS are currently ignored.
156 OPTIONS-AND-METHODS currently understands:
157 - (:documentation DOCSTRING)
158 - (declare DECLARATIONS)"
159 (declare (indent 2) (doc-string 3))
160 (let* ((docprop (assq :documentation options-and-methods))
161 (doc (cond ((stringp (car-safe options-and-methods))
162 (pop options-and-methods))
163 (docprop
164 (prog1
165 (cadr docprop)
166 (setq options-and-methods
167 (delq docprop options-and-methods))))))
168 (declarations (assq 'declare options-and-methods)))
169 (when declarations
170 (setq options-and-methods
171 (delq declarations options-and-methods)))
172 `(progn
173 ,(when (eq 'setf (car-safe name))
174 (pcase-let ((`(,setter . ,code) (cl--generic-setf-rewrite
175 (cadr name))))
176 (setq name setter)
177 code))
178 ,@(mapcar (lambda (declaration)
179 (let ((f (cdr (assq (car declaration)
180 defun-declarations-alist))))
181 (cond
182 (f (apply (car f) name args (cdr declaration)))
183 (t (message "Warning: Unknown defun property `%S' in %S"
184 (car declaration) name)
185 nil))))
186 (cdr declarations))
187 (defalias ',name
188 (cl-generic-define ',name ',args ',options-and-methods)
189 ,(help-add-fundoc-usage doc args)))))
190
191 (defun cl--generic-mandatory-args (args)
192 (let ((res ()))
193 (while (not (memq (car args) '(nil &rest &optional &key)))
194 (push (pop args) res))
195 (nreverse res)))
196
197 ;;;###autoload
198 (defun cl-generic-define (name args options-and-methods)
199 (let ((generic (cl-generic-ensure-function name))
200 (mandatory (cl--generic-mandatory-args args))
201 (apo (assq :argument-precedence-order options-and-methods)))
202 (setf (cl--generic-dispatches generic) nil)
203 (when apo
204 (dolist (arg (cdr apo))
205 (let ((pos (memq arg mandatory)))
206 (unless pos (error "%S is not a mandatory argument" arg))
207 (push (list (- (length mandatory) (length pos)))
208 (cl--generic-dispatches generic)))))
209 (setf (cl--generic-method-table generic) nil)
210 (cl--generic-make-function generic)))
211
212 (defmacro cl-generic-current-method-specializers ()
213 "List of (VAR . TYPE) where TYPE is var's specializer.
214 This macro can only be used within the lexical scope of a cl-generic method."
215 (error "cl-generic-current-method-specializers used outside of a method"))
216
217 (eval-and-compile ;Needed while compiling the cl-defmethod calls below!
218 (defun cl--generic-fgrep (vars sexp) ;Copied from pcase.el.
219 "Check which of the symbols VARS appear in SEXP."
220 (let ((res '()))
221 (while (consp sexp)
222 (dolist (var (cl--generic-fgrep vars (pop sexp)))
223 (unless (memq var res) (push var res))))
224 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
225 res))
226
227 (defun cl--generic-lambda (args body with-cnm)
228 "Make the lambda expression for a method with ARGS and BODY."
229 (let ((plain-args ())
230 (specializers nil)
231 (doc-string (if (stringp (car-safe body)) (pop body)))
232 (mandatory t))
233 (dolist (arg args)
234 (push (pcase arg
235 ((or '&optional '&rest '&key) (setq mandatory nil) arg)
236 ((and `(,name . ,type) (guard mandatory))
237 (push (cons name (car type)) specializers)
238 name)
239 (_ arg))
240 plain-args))
241 (setq plain-args (nreverse plain-args))
242 (let ((fun `(cl-function (lambda ,plain-args
243 ,@(if doc-string (list doc-string))
244 ,@body)))
245 (macroenv (cons `(cl-generic-current-method-specializers
246 . ,(lambda () specializers))
247 macroexpand-all-environment)))
248 (require 'cl-lib) ;Needed to expand `cl-flet' and `cl-function'.
249 (if (not with-cnm)
250 (cons nil (macroexpand-all fun macroenv))
251 ;; First macroexpand away the cl-function stuff (e.g. &key and
252 ;; destructuring args, `declare' and whatnot).
253 (pcase (macroexpand fun macroenv)
254 (`#'(lambda ,args . ,body)
255 (let* ((doc-string (and doc-string (stringp (car body))
256 (pop body)))
257 (cnm (make-symbol "cl--cnm"))
258 (nmp (make-symbol "cl--nmp"))
259 (nbody (macroexpand-all
260 `(cl-flet ((cl-call-next-method ,cnm)
261 (cl-next-method-p ,nmp))
262 ,@body)
263 macroenv))
264 ;; FIXME: Rather than `grep' after the fact, the
265 ;; macroexpansion should directly set some flag when cnm
266 ;; is used.
267 ;; FIXME: Also, optimize the case where call-next-method is
268 ;; only called with explicit arguments.
269 (uses-cnm (cl--generic-fgrep (list cnm nmp) nbody)))
270 (cons (not (not uses-cnm))
271 `#'(lambda (,@(if uses-cnm (list cnm)) ,@args)
272 ,@(if doc-string (list doc-string))
273 ,(if (not (memq nmp uses-cnm))
274 nbody
275 `(let ((,nmp (lambda ()
276 (cl--generic-isnot-nnm-p ,cnm))))
277 ,nbody))))))
278 (f (error "Unexpected macroexpansion result: %S" f))))))))
279
280
281 ;;;###autoload
282 (defmacro cl-defmethod (name args &rest body)
283 "Define a new method for generic function NAME.
284 I.e. it defines the implementation of NAME to use for invocations where the
285 value of the dispatch argument matches the specified TYPE.
286 The dispatch argument has to be one of the mandatory arguments, and
287 all methods of NAME have to use the same argument for dispatch.
288 The dispatch argument and TYPE are specified in ARGS where the corresponding
289 formal argument appears as (VAR TYPE) rather than just VAR.
290
291 The optional second argument QUALIFIER is a specifier that
292 modifies how the method is combined with other methods, including:
293 :before - Method will be called before the primary
294 :after - Method will be called after the primary
295 :around - Method will be called around everything else
296 The absence of QUALIFIER means this is a \"primary\" method.
297
298 Other than a type, TYPE can also be of the form `(eql VAL)' in
299 which case this method will be invoked when the argument is `eql' to VAL.
300
301 \(fn NAME [QUALIFIER] ARGS &rest [DOCSTRING] BODY)"
302 (declare (doc-string 3) (indent 2)
303 (debug
304 (&define ; this means we are defining something
305 [&or name ("setf" :name setf name)]
306 ;; ^^ This is the methods symbol
307 [ &optional keywordp ] ; this is key :before etc
308 list ; arguments
309 [ &optional stringp ] ; documentation string
310 def-body))) ; part to be debugged
311 (let ((qualifiers nil)
312 (setfizer (if (eq 'setf (car-safe name))
313 ;; Call it before we call cl--generic-lambda.
314 (cl--generic-setf-rewrite (cadr name)))))
315 (while (keywordp args)
316 (push args qualifiers)
317 (setq args (pop body)))
318 (pcase-let* ((with-cnm (not (memq (car qualifiers) '(:before :after))))
319 (`(,uses-cnm . ,fun) (cl--generic-lambda args body with-cnm)))
320 `(progn
321 ,(when setfizer
322 (setq name (car setfizer))
323 (cdr setfizer))
324 ,(and (get name 'byte-obsolete-info)
325 (or (not (fboundp 'byte-compile-warning-enabled-p))
326 (byte-compile-warning-enabled-p 'obsolete))
327 (let* ((obsolete (get name 'byte-obsolete-info)))
328 (macroexp--warn-and-return
329 (macroexp--obsolete-warning name obsolete "generic function")
330 nil)))
331 ;; You could argue that `defmethod' modifies rather than defines the
332 ;; function, so warnings like "not known to be defined" are fair game.
333 ;; But in practice, it's common to use `cl-defmethod'
334 ;; without a previous `cl-defgeneric'.
335 (declare-function ,name "")
336 (cl-generic-define-method ',name ',qualifiers ',args
337 ,uses-cnm ,fun)))))
338
339 ;;;###autoload
340 (defun cl-generic-define-method (name qualifiers args uses-cnm function)
341 (when (> (length qualifiers) 1)
342 (error "We only support a single qualifier per method: %S" qualifiers))
343 (unless (memq (car qualifiers) '(nil :primary :around :after :before))
344 (error "Unsupported qualifier in: %S" qualifiers))
345 (let* ((generic (cl-generic-ensure-function name))
346 (mandatory (cl--generic-mandatory-args args))
347 (specializers
348 (mapcar (lambda (arg) (if (consp arg) (cadr arg) t)) mandatory))
349 (key (cons specializers (or (car qualifiers) ':primary)))
350 (mt (cl--generic-method-table generic))
351 (me (assoc key mt))
352 (dispatches (cl--generic-dispatches generic))
353 (i 0))
354 (dolist (specializer specializers)
355 (let* ((tagcode (funcall cl-generic-tagcode-function specializer 'arg))
356 (x (assq i dispatches)))
357 (unless x
358 (setq x (list i (funcall cl-generic-tagcode-function t 'arg)))
359 (setf (cl--generic-dispatches generic)
360 (setq dispatches (cons x dispatches))))
361 (unless (member tagcode (cdr x))
362 (setf (cdr x)
363 (nreverse (sort (cons tagcode (cdr x))
364 #'car-less-than-car))))
365 (setq i (1+ i))))
366 (if me (setcdr me (cons uses-cnm function))
367 (setf (cl--generic-method-table generic)
368 (cons `(,key ,uses-cnm . ,function) mt)))
369 (cl-pushnew `(cl-defmethod . (,(cl--generic-name generic) . ,specializers))
370 current-load-list :test #'equal)
371 (let ((gfun (cl--generic-make-function generic))
372 ;; Prevent `defalias' from recording this as the definition site of
373 ;; the generic function.
374 current-load-list)
375 ;; For aliases, cl--generic-name gives us the actual name.
376 (defalias (cl--generic-name generic) gfun))))
377
378 (defmacro cl--generic-with-memoization (place &rest code)
379 (declare (indent 1) (debug t))
380 (gv-letplace (getter setter) place
381 `(or ,getter
382 ,(macroexp-let2 nil val (macroexp-progn code)
383 `(progn
384 ,(funcall setter val)
385 ,val)))))
386
387 (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
388
389 (defun cl--generic-get-dispatcher (tagcodes dispatch-arg)
390 (cl--generic-with-memoization
391 (gethash (cons dispatch-arg tagcodes) cl--generic-dispatchers)
392 (let ((lexical-binding t)
393 (tag-exp `(or ,@(mapcar #'cdr
394 ;; Minor optimization: since this tag-exp is
395 ;; only used to lookup the method-cache, it
396 ;; doesn't matter if the default value is some
397 ;; constant or nil.
398 (if (macroexp-const-p (car (last tagcodes)))
399 (butlast tagcodes)
400 tagcodes))))
401 (extraargs ()))
402 (dotimes (_ dispatch-arg)
403 (push (make-symbol "arg") extraargs))
404 (byte-compile
405 `(lambda (generic dispatches-left)
406 (let ((method-cache (make-hash-table :test #'eql)))
407 (lambda (,@extraargs arg &rest args)
408 (apply (cl--generic-with-memoization
409 (gethash ,tag-exp method-cache)
410 (cl--generic-cache-miss
411 generic ',dispatch-arg dispatches-left
412 (list ,@(mapcar #'cdr tagcodes))))
413 ,@extraargs arg args))))))))
414
415 (defun cl--generic-make-function (generic)
416 (let* ((dispatches (cl--generic-dispatches generic))
417 (dispatch
418 (progn
419 (while (and dispatches
420 (member (cdar dispatches)
421 '(nil ((0 . 'cl--generic-type)))))
422 (setq dispatches (cdr dispatches)))
423 (pop dispatches))))
424 (if (null dispatch)
425 (cl--generic-build-combined-method
426 (cl--generic-name generic)
427 (cl--generic-method-table generic))
428 (let ((dispatcher (cl--generic-get-dispatcher
429 (cdr dispatch) (car dispatch))))
430 (funcall dispatcher generic dispatches)))))
431
432 (defun cl--generic-nest (fun methods)
433 (pcase-dolist (`(,uses-cnm . ,method) methods)
434 (setq fun
435 (if (not uses-cnm) method
436 (let ((next fun))
437 (lambda (&rest args)
438 (apply method
439 ;; FIXME: This sucks: passing just `next' would
440 ;; be a lot more efficient than the lambda+apply
441 ;; quasi-η, but we need this to implement the
442 ;; "if call-next-method is called with no
443 ;; arguments, then use the previous arguments".
444 (lambda (&rest cnm-args)
445 (apply next (or cnm-args args)))
446 args))))))
447 fun)
448
449 (defvar cl--generic-combined-method-memoization
450 (make-hash-table :test #'equal :weakness 'value)
451 "Table storing previously built combined-methods.
452 This is particularly useful when many different tags select the same set
453 of methods, since this table then allows us to share a single combined-method
454 for all those different tags in the method-cache.")
455
456 (defun cl--generic-build-combined-method (generic-name methods)
457 (let ((mets-by-qual ()))
458 (dolist (qm methods)
459 (push (cdr qm) (alist-get (cdar qm) mets-by-qual)))
460 (cl--generic-with-memoization
461 (gethash (cons generic-name mets-by-qual)
462 cl--generic-combined-method-memoization)
463 (cond
464 ((null mets-by-qual) (lambda (&rest args)
465 (apply #'cl-no-applicable-method
466 generic-name args)))
467 (t
468 (let* ((fun (lambda (&rest args)
469 ;; FIXME: CLOS passes as second arg the "calling method".
470 ;; We don't currently have "method objects" like CLOS
471 ;; does so we can't really do it the CLOS way.
472 ;; The closest would be to pass the lambda corresponding
473 ;; to the method, or maybe the ((SPECIALIZERS
474 ;; . QUALIFIER) USE-CNM . FUNCTION) entry from the method
475 ;; table, but the caller wouldn't be able to do much with
476 ;; it anyway. So we pass nil for now.
477 ;; FIXME: signal `no-primary-method' if there's
478 ;; no primary.
479 (apply #'cl-no-next-method generic-name nil args)))
480 ;; We use `cdr' to drop the `uses-cnm' annotations.
481 (before
482 (mapcar #'cdr (reverse (alist-get :before mets-by-qual))))
483 (after (mapcar #'cdr (alist-get :after mets-by-qual))))
484 (setq fun (cl--generic-nest fun (alist-get :primary mets-by-qual)))
485 (when (or after before)
486 (let ((next fun))
487 (setq fun (lambda (&rest args)
488 (dolist (bf before)
489 (apply bf args))
490 (prog1
491 (apply next args)
492 (dolist (af after)
493 (apply af args)))))))
494 (cl--generic-nest fun (alist-get :around mets-by-qual))))))))
495
496 (defconst cl--generic-nnm-sample
497 (cl--generic-build-combined-method nil '(((specializer . :qualifier)))))
498 (defconst cl--generic-cnm-sample
499 (funcall (cl--generic-build-combined-method
500 nil `(((specializer . :primary) t . ,#'identity)))))
501
502 (defun cl--generic-isnot-nnm-p (cnm)
503 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
504 ;; ¡Big Gross Ugly Hack!
505 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
506 ;; it, and some packages use it, so we need to support it.
507 (catch 'found
508 (cl-assert (function-equal cnm cl--generic-cnm-sample))
509 (if (byte-code-function-p cnm)
510 (let ((cnm-constants (aref cnm 2))
511 (sample-constants (aref cl--generic-cnm-sample 2)))
512 (dotimes (i (length sample-constants))
513 (when (function-equal (aref sample-constants i)
514 cl--generic-nnm-sample)
515 (throw 'found
516 (not (function-equal (aref cnm-constants i)
517 cl--generic-nnm-sample))))))
518 (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
519 (let ((cnm-env (cadr cnm)))
520 (dolist (vb (cadr cl--generic-cnm-sample))
521 (when (function-equal (cdr vb) cl--generic-nnm-sample)
522 (throw 'found
523 (not (function-equal (cdar cnm-env)
524 cl--generic-nnm-sample))))
525 (setq cnm-env (cdr cnm-env)))))
526 (error "Haven't found no-next-method-sample in cnm-sample")))
527
528 (defun cl--generic-cache-miss (generic dispatch-arg dispatches-left tags)
529 (let ((types (apply #'append (mapcar cl-generic-tag-types-function tags)))
530 (methods '()))
531 (dolist (method-desc (cl--generic-method-table generic))
532 (let* ((specializer (or (nth dispatch-arg (caar method-desc)) t))
533 (m (member specializer types)))
534 (when m
535 (push (cons (length m) method-desc) methods))))
536 ;; Sort the methods, most specific first.
537 ;; It would be tempting to sort them once and for all in the method-table
538 ;; rather than here, but the order might depend on the actual argument
539 ;; (e.g. for multiple inheritance with defclass).
540 (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
541 (cl--generic-make-function (cl--generic-make (cl--generic-name generic)
542 dispatches-left methods))))
543
544 ;;; Define some pre-defined generic functions, used internally.
545
546 (define-error 'cl-no-method "No method for %S")
547 (define-error 'cl-no-next-method "No next method for %S" 'cl-no-method)
548 (define-error 'cl-no-applicable-method "No applicable method for %S"
549 'cl-no-method)
550
551 (cl-defgeneric cl-no-next-method (generic method &rest args)
552 "Function called when `cl-call-next-method' finds no next method.")
553 (cl-defmethod cl-no-next-method (generic method &rest args)
554 (signal 'cl-no-next-method `(,generic ,method ,@args)))
555
556 (cl-defgeneric cl-no-applicable-method (generic &rest args)
557 "Function called when a method call finds no applicable method.")
558 (cl-defmethod cl-no-applicable-method (generic &rest args)
559 (signal 'cl-no-applicable-method `(,generic ,@args)))
560
561 (defun cl-call-next-method (&rest _args)
562 "Function to call the next applicable method.
563 Can only be used from within the lexical body of a primary or around method."
564 (error "cl-call-next-method only allowed inside primary and around methods"))
565
566 (defun cl-next-method-p ()
567 "Return non-nil if there is a next method.
568 Can only be used from within the lexical body of a primary or around method."
569 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
570 (error "cl-next-method-p only allowed inside primary and around methods"))
571
572 ;;; Add support for describe-function
573
574 (defun cl--generic-search-method (met-name)
575 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
576 (regexp-quote (format "%s\\_>" (car met-name))))))
577 (or
578 (re-search-forward
579 (concat base-re "[^&\"\n]*"
580 (mapconcat (lambda (specializer)
581 (regexp-quote
582 (format "%S" (if (consp specializer)
583 (nth 1 specializer) specializer))))
584 (remq t (cdr met-name))
585 "[ \t\n]*)[^&\"\n]*"))
586 nil t)
587 (re-search-forward base-re nil t))))
588
589
590 (with-eval-after-load 'find-func
591 (defvar find-function-regexp-alist)
592 (add-to-list 'find-function-regexp-alist
593 `(cl-defmethod . ,#'cl--generic-search-method)))
594
595 (defun cl--generic-method-info (method)
596 (pcase-let ((`((,specializers . ,qualifier) ,uses-cnm . ,function) method))
597 (let* ((args (help-function-arglist function 'names))
598 (docstring (documentation function))
599 (doconly (if docstring
600 (let ((split (help-split-fundoc docstring nil)))
601 (if split (cdr split) docstring))))
602 (combined-args ()))
603 (if uses-cnm (setq args (cdr args)))
604 (dolist (specializer specializers)
605 (let ((arg (if (eq '&rest (car args))
606 (intern (format "arg%d" (length combined-args)))
607 (pop args))))
608 (push (if (eq specializer t) arg (list arg specializer))
609 combined-args)))
610 (setq combined-args (append (nreverse combined-args) args))
611 (list qualifier combined-args doconly))))
612
613 (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
614 (defun cl--generic-describe (function)
615 (let ((generic (if (symbolp function) (cl--generic function))))
616 (when generic
617 (require 'help-mode) ;Needed for `help-function-def' button!
618 (save-excursion
619 (insert "\n\nThis is a generic function.\n\n")
620 (insert (propertize "Implementations:\n\n" 'face 'bold))
621 ;; Loop over fanciful generics
622 (dolist (method (cl--generic-method-table generic))
623 (let* ((info (cl--generic-method-info method)))
624 ;; FIXME: Add hyperlinks for the types as well.
625 (insert (format "%S %S" (nth 0 info) (nth 1 info)))
626 (let* ((met-name (cons function (caar method)))
627 (file (find-lisp-object-file-name met-name 'cl-defmethod)))
628 (when file
629 (insert " in `")
630 (help-insert-xref-button (help-fns-short-filename file)
631 'help-function-def met-name file
632 'cl-defmethod)
633 (insert "'.\n")))
634 (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
635
636 ;;; Support for (eql <val>) specializers.
637
638 (defvar cl--generic-eql-used (make-hash-table :test #'eql))
639
640 (add-function :before-until cl-generic-tagcode-function
641 #'cl--generic-eql-tagcode)
642 (defun cl--generic-eql-tagcode (type name)
643 (when (eq (car-safe type) 'eql)
644 (puthash (cadr type) type cl--generic-eql-used)
645 `(100 . (gethash ,name cl--generic-eql-used))))
646
647 (add-function :before-until cl-generic-tag-types-function
648 #'cl--generic-eql-tag-types)
649 (defun cl--generic-eql-tag-types (tag)
650 (if (eq (car-safe tag) 'eql) (list tag)))
651
652 ;;; Support for cl-defstructs specializers.
653
654 (add-function :before-until cl-generic-tagcode-function
655 #'cl--generic-struct-tagcode)
656 (defun cl--generic-struct-tagcode (type name)
657 (and (symbolp type)
658 (get type 'cl-struct-type)
659 (or (eq 'vector (car (get type 'cl-struct-type)))
660 (error "Can't dispatch on cl-struct %S: type is %S"
661 type (car (get type 'cl-struct-type))))
662 (or (equal '(cl-tag-slot) (car (get type 'cl-struct-slots)))
663 (error "Can't dispatch on cl-struct %S: no tag in slot 0"
664 type))
665 ;; We could/should check the vector has length >0,
666 ;; but really, mixing vectors and structs is a bad idea,
667 ;; so let's not waste time trying to handle the case
668 ;; of an empty vector.
669 ;; BEWARE: this returns a bogus tag for non-struct vectors.
670 `(50 . (and (vectorp ,name) (aref ,name 0)))))
671
672 (add-function :before-until cl-generic-tag-types-function
673 #'cl--generic-struct-tag-types)
674 (defun cl--generic-struct-tag-types (tag)
675 ;; FIXME: cl-defstruct doesn't make it easy for us.
676 (and (symbolp tag)
677 ;; A method call shouldn't itself mess with the match-data.
678 (string-match-p "\\`cl-struct-\\(.*\\)" (symbol-name tag))
679 (let ((types (list (intern (substring (symbol-name tag) 10)))))
680 (while (get (car types) 'cl-struct-include)
681 (push (get (car types) 'cl-struct-include) types))
682 (push 'cl-struct types) ;The "parent type" of all cl-structs.
683 (nreverse types))))
684
685 ;;; Dispatch on "old-style types".
686
687 (defconst cl--generic-typeof-types
688 ;; Hand made from the source code of `type-of'.
689 '((integer number) (symbol) (string array) (cons list)
690 ;; Markers aren't `numberp', yet they are accepted wherever integers are
691 ;; accepted, pretty much.
692 (marker) (overlay) (float number) (window-configuration)
693 (process) (window) (subr) (compiled-function) (buffer) (char-table array)
694 (bool-vector array)
695 (frame) (hash-table) (font-spec) (font-entity) (font-object)
696 (vector array)
697 ;; Plus, hand made:
698 (null list symbol)
699 (list)
700 (array)
701 (number)))
702
703 (add-function :before-until cl-generic-tagcode-function
704 #'cl--generic-typeof-tagcode)
705 (defun cl--generic-typeof-tagcode (type name)
706 ;; FIXME: Add support for other types accepted by `cl-typep' such
707 ;; as `character', `atom', `face', `function', ...
708 (and (assq type cl--generic-typeof-types)
709 (progn
710 (if (memq type '(vector array))
711 (message "`%S' also matches CL structs and EIEIO classes" type))
712 ;; FIXME: We could also change `type-of' to return `null' for nil.
713 `(10 . (if ,name (type-of ,name) 'null)))))
714
715 (add-function :before-until cl-generic-tag-types-function
716 #'cl--generic-typeof-types)
717 (defun cl--generic-typeof-types (tag)
718 (and (symbolp tag)
719 (assq tag cl--generic-typeof-types)))
720
721 ;;; Just for kicks: dispatch on major-mode
722 ;;
723 ;; Here's how you'd use it:
724 ;; (cl-defmethod foo ((x (major-mode text-mode)) y z) ...)
725 ;; And then
726 ;; (foo 'major-mode toto titi)
727 ;;
728 ;; FIXME: Better would be to do that via dispatch on an "implicit argument".
729
730 ;; (defvar cl--generic-major-modes (make-hash-table :test #'eq))
731 ;;
732 ;; (add-function :before-until cl-generic-tagcode-function
733 ;; #'cl--generic-major-mode-tagcode)
734 ;; (defun cl--generic-major-mode-tagcode (type name)
735 ;; (if (eq 'major-mode (car-safe type))
736 ;; `(50 . (if (eq ,name 'major-mode)
737 ;; (cl--generic-with-memoization
738 ;; (gethash major-mode cl--generic-major-modes)
739 ;; `(cl--generic-major-mode . ,major-mode))))))
740 ;;
741 ;; (add-function :before-until cl-generic-tag-types-function
742 ;; #'cl--generic-major-mode-types)
743 ;; (defun cl--generic-major-mode-types (tag)
744 ;; (when (eq (car-safe tag) 'cl--generic-major-mode)
745 ;; (if (eq tag 'fundamental-mode) '(fundamental-mode t)
746 ;; (let ((types `((major-mode ,(cdr tag)))))
747 ;; (while (get (car types) 'derived-mode-parent)
748 ;; (push (list 'major-mode (get (car types) 'derived-mode-parent))
749 ;; types))
750 ;; (unless (eq 'fundamental-mode (car types))
751 ;; (push '(major-mode fundamental-mode) types))
752 ;; (nreverse types)))))
753
754 ;; Local variables:
755 ;; generated-autoload-file: "cl-loaddefs.el"
756 ;; End:
757
758 (provide 'cl-generic)
759 ;;; cl-generic.el ends here