]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/cl-generic.el
* lisp/emacs-lisp/cl-generic.el (cl-no-primary-method): New fun and error.
[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 (and (stringp (car-safe body)) (cdr body))
232 (pop body)))
233 (mandatory t))
234 (dolist (arg args)
235 (push (pcase arg
236 ((or '&optional '&rest '&key) (setq mandatory nil) arg)
237 ((and `(,name . ,type) (guard mandatory))
238 (push (cons name (car type)) specializers)
239 name)
240 (_ arg))
241 plain-args))
242 (setq plain-args (nreverse plain-args))
243 (let ((fun `(cl-function (lambda ,plain-args
244 ,@(if doc-string (list doc-string))
245 ,@body)))
246 (macroenv (cons `(cl-generic-current-method-specializers
247 . ,(lambda () specializers))
248 macroexpand-all-environment)))
249 (require 'cl-lib) ;Needed to expand `cl-flet' and `cl-function'.
250 (if (not with-cnm)
251 (cons nil (macroexpand-all fun macroenv))
252 ;; First macroexpand away the cl-function stuff (e.g. &key and
253 ;; destructuring args, `declare' and whatnot).
254 (pcase (macroexpand fun macroenv)
255 (`#'(lambda ,args . ,body)
256 (let* ((doc-string (and doc-string (stringp (car body)) (cdr body)
257 (pop body)))
258 (cnm (make-symbol "cl--cnm"))
259 (nmp (make-symbol "cl--nmp"))
260 (nbody (macroexpand-all
261 `(cl-flet ((cl-call-next-method ,cnm)
262 (cl-next-method-p ,nmp))
263 ,@body)
264 macroenv))
265 ;; FIXME: Rather than `grep' after the fact, the
266 ;; macroexpansion should directly set some flag when cnm
267 ;; is used.
268 ;; FIXME: Also, optimize the case where call-next-method is
269 ;; only called with explicit arguments.
270 (uses-cnm (cl--generic-fgrep (list cnm nmp) nbody)))
271 (cons (not (not uses-cnm))
272 `#'(lambda (,@(if uses-cnm (list cnm)) ,@args)
273 ,@(if doc-string (list doc-string))
274 ,(if (not (memq nmp uses-cnm))
275 nbody
276 `(let ((,nmp (lambda ()
277 (cl--generic-isnot-nnm-p ,cnm))))
278 ,nbody))))))
279 (f (error "Unexpected macroexpansion result: %S" f))))))))
280
281
282 ;;;###autoload
283 (defmacro cl-defmethod (name args &rest body)
284 "Define a new method for generic function NAME.
285 I.e. it defines the implementation of NAME to use for invocations where the
286 value of the dispatch argument matches the specified TYPE.
287 The dispatch argument has to be one of the mandatory arguments, and
288 all methods of NAME have to use the same argument for dispatch.
289 The dispatch argument and TYPE are specified in ARGS where the corresponding
290 formal argument appears as (VAR TYPE) rather than just VAR.
291
292 The optional second argument QUALIFIER is a specifier that
293 modifies how the method is combined with other methods, including:
294 :before - Method will be called before the primary
295 :after - Method will be called after the primary
296 :around - Method will be called around everything else
297 The absence of QUALIFIER means this is a \"primary\" method.
298
299 Other than a type, TYPE can also be of the form `(eql VAL)' in
300 which case this method will be invoked when the argument is `eql' to VAL.
301
302 \(fn NAME [QUALIFIER] ARGS &rest [DOCSTRING] BODY)"
303 (declare (doc-string 3) (indent 2)
304 (debug
305 (&define ; this means we are defining something
306 [&or name ("setf" :name setf name)]
307 ;; ^^ This is the methods symbol
308 [ &optional keywordp ] ; this is key :before etc
309 list ; arguments
310 [ &optional stringp ] ; documentation string
311 def-body))) ; part to be debugged
312 (let ((qualifiers nil)
313 (setfizer (if (eq 'setf (car-safe name))
314 ;; Call it before we call cl--generic-lambda.
315 (cl--generic-setf-rewrite (cadr name)))))
316 (while (keywordp args)
317 (push args qualifiers)
318 (setq args (pop body)))
319 (pcase-let* ((with-cnm (not (memq (car qualifiers) '(:before :after))))
320 (`(,uses-cnm . ,fun) (cl--generic-lambda args body with-cnm)))
321 `(progn
322 ,(when setfizer
323 (setq name (car setfizer))
324 (cdr setfizer))
325 ,(and (get name 'byte-obsolete-info)
326 (or (not (fboundp 'byte-compile-warning-enabled-p))
327 (byte-compile-warning-enabled-p 'obsolete))
328 (let* ((obsolete (get name 'byte-obsolete-info)))
329 (macroexp--warn-and-return
330 (macroexp--obsolete-warning name obsolete "generic function")
331 nil)))
332 ;; You could argue that `defmethod' modifies rather than defines the
333 ;; function, so warnings like "not known to be defined" are fair game.
334 ;; But in practice, it's common to use `cl-defmethod'
335 ;; without a previous `cl-defgeneric'.
336 (declare-function ,name "")
337 (cl-generic-define-method ',name ',qualifiers ',args
338 ,uses-cnm ,fun)))))
339
340 ;;;###autoload
341 (defun cl-generic-define-method (name qualifiers args uses-cnm function)
342 (when (> (length qualifiers) 1)
343 (error "We only support a single qualifier per method: %S" qualifiers))
344 (unless (memq (car qualifiers) '(nil :primary :around :after :before))
345 (error "Unsupported qualifier in: %S" qualifiers))
346 (let* ((generic (cl-generic-ensure-function name))
347 (mandatory (cl--generic-mandatory-args args))
348 (specializers
349 (mapcar (lambda (arg) (if (consp arg) (cadr arg) t)) mandatory))
350 (key (cons specializers (or (car qualifiers) ':primary)))
351 (mt (cl--generic-method-table generic))
352 (me (assoc key mt))
353 (dispatches (cl--generic-dispatches generic))
354 (i 0))
355 (dolist (specializer specializers)
356 (let* ((tagcode (funcall cl-generic-tagcode-function specializer 'arg))
357 (x (assq i dispatches)))
358 (unless x
359 (setq x (list i (funcall cl-generic-tagcode-function t 'arg)))
360 (setf (cl--generic-dispatches generic)
361 (setq dispatches (cons x dispatches))))
362 (unless (member tagcode (cdr x))
363 (setf (cdr x)
364 (nreverse (sort (cons tagcode (cdr x))
365 #'car-less-than-car))))
366 (setq i (1+ i))))
367 (if me (setcdr me (cons uses-cnm function))
368 (setf (cl--generic-method-table generic)
369 (cons `(,key ,uses-cnm . ,function) mt)))
370 (cl-pushnew `(cl-defmethod . (,(cl--generic-name generic) . ,specializers))
371 current-load-list :test #'equal)
372 (let ((gfun (cl--generic-make-function generic))
373 ;; Prevent `defalias' from recording this as the definition site of
374 ;; the generic function.
375 current-load-list)
376 ;; For aliases, cl--generic-name gives us the actual name.
377 (defalias (cl--generic-name generic) gfun))))
378
379 (defmacro cl--generic-with-memoization (place &rest code)
380 (declare (indent 1) (debug t))
381 (gv-letplace (getter setter) place
382 `(or ,getter
383 ,(macroexp-let2 nil val (macroexp-progn code)
384 `(progn
385 ,(funcall setter val)
386 ,val)))))
387
388 (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
389
390 (defun cl--generic-get-dispatcher (tagcodes dispatch-arg)
391 (cl--generic-with-memoization
392 (gethash (cons dispatch-arg tagcodes) cl--generic-dispatchers)
393 (let ((lexical-binding t)
394 (tag-exp `(or ,@(mapcar #'cdr
395 ;; Minor optimization: since this tag-exp is
396 ;; only used to lookup the method-cache, it
397 ;; doesn't matter if the default value is some
398 ;; constant or nil.
399 (if (macroexp-const-p (car (last tagcodes)))
400 (butlast tagcodes)
401 tagcodes))))
402 (extraargs ()))
403 (dotimes (_ dispatch-arg)
404 (push (make-symbol "arg") extraargs))
405 (byte-compile
406 `(lambda (generic dispatches-left)
407 (let ((method-cache (make-hash-table :test #'eql)))
408 (lambda (,@extraargs arg &rest args)
409 (apply (cl--generic-with-memoization
410 (gethash ,tag-exp method-cache)
411 (cl--generic-cache-miss
412 generic ',dispatch-arg dispatches-left
413 (list ,@(mapcar #'cdr tagcodes))))
414 ,@extraargs arg args))))))))
415
416 (defun cl--generic-make-function (generic)
417 (let* ((dispatches (cl--generic-dispatches generic))
418 (dispatch
419 (progn
420 (while (and dispatches
421 (member (cdar dispatches)
422 '(nil ((0 . 'cl--generic-type)))))
423 (setq dispatches (cdr dispatches)))
424 (pop dispatches))))
425 (if (null dispatch)
426 (cl--generic-build-combined-method
427 (cl--generic-name generic)
428 (cl--generic-method-table generic))
429 (let ((dispatcher (cl--generic-get-dispatcher
430 (cdr dispatch) (car dispatch))))
431 (funcall dispatcher generic dispatches)))))
432
433 (defun cl--generic-nest (fun methods)
434 (pcase-dolist (`(,uses-cnm . ,method) methods)
435 (setq fun
436 (if (not uses-cnm) method
437 (let ((next fun))
438 (lambda (&rest args)
439 (apply method
440 ;; FIXME: This sucks: passing just `next' would
441 ;; be a lot more efficient than the lambda+apply
442 ;; quasi-η, but we need this to implement the
443 ;; "if call-next-method is called with no
444 ;; arguments, then use the previous arguments".
445 (lambda (&rest cnm-args)
446 (apply next (or cnm-args args)))
447 args))))))
448 fun)
449
450 (defvar cl--generic-combined-method-memoization
451 (make-hash-table :test #'equal :weakness 'value)
452 "Table storing previously built combined-methods.
453 This is particularly useful when many different tags select the same set
454 of methods, since this table then allows us to share a single combined-method
455 for all those different tags in the method-cache.")
456
457 (defun cl--generic-build-combined-method (generic-name methods)
458 (let ((mets-by-qual ()))
459 (dolist (qm methods)
460 (push (cdr qm) (alist-get (cdar qm) mets-by-qual)))
461 (cl--generic-with-memoization
462 (gethash (cons generic-name mets-by-qual)
463 cl--generic-combined-method-memoization)
464 (cond
465 ((null mets-by-qual)
466 (lambda (&rest args)
467 (apply #'cl-no-applicable-method generic-name args)))
468 ((null (alist-get :primary mets-by-qual))
469 (lambda (&rest args)
470 (apply #'cl-no-primary-method generic-name args)))
471 (t
472 (let* ((fun (lambda (&rest args)
473 ;; FIXME: CLOS passes as second arg the "calling method".
474 ;; We don't currently have "method objects" like CLOS
475 ;; does so we can't really do it the CLOS way.
476 ;; The closest would be to pass the lambda corresponding
477 ;; to the method, or maybe the ((SPECIALIZERS
478 ;; . QUALIFIER) USE-CNM . FUNCTION) entry from the method
479 ;; table, but the caller wouldn't be able to do much with
480 ;; it anyway. So we pass nil for now.
481 (apply #'cl-no-next-method generic-name nil args)))
482 ;; We use `cdr' to drop the `uses-cnm' annotations.
483 (before
484 (mapcar #'cdr (reverse (alist-get :before mets-by-qual))))
485 (after (mapcar #'cdr (alist-get :after mets-by-qual))))
486 (setq fun (cl--generic-nest fun (alist-get :primary mets-by-qual)))
487 (when (or after before)
488 (let ((next fun))
489 (setq fun (lambda (&rest args)
490 (dolist (bf before)
491 (apply bf args))
492 (prog1
493 (apply next args)
494 (dolist (af after)
495 (apply af args)))))))
496 (cl--generic-nest fun (alist-get :around mets-by-qual))))))))
497
498 (defconst cl--generic-nnm-sample
499 (cl--generic-build-combined-method nil '(((specializer . :qualifier)))))
500 (defconst cl--generic-cnm-sample
501 (funcall (cl--generic-build-combined-method
502 nil `(((specializer . :primary) t . ,#'identity)))))
503
504 (defun cl--generic-isnot-nnm-p (cnm)
505 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
506 ;; ¡Big Gross Ugly Hack!
507 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
508 ;; it, and some packages use it, so we need to support it.
509 (catch 'found
510 (cl-assert (function-equal cnm cl--generic-cnm-sample))
511 (if (byte-code-function-p cnm)
512 (let ((cnm-constants (aref cnm 2))
513 (sample-constants (aref cl--generic-cnm-sample 2)))
514 (dotimes (i (length sample-constants))
515 (when (function-equal (aref sample-constants i)
516 cl--generic-nnm-sample)
517 (throw 'found
518 (not (function-equal (aref cnm-constants i)
519 cl--generic-nnm-sample))))))
520 (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
521 (let ((cnm-env (cadr cnm)))
522 (dolist (vb (cadr cl--generic-cnm-sample))
523 (when (function-equal (cdr vb) cl--generic-nnm-sample)
524 (throw 'found
525 (not (function-equal (cdar cnm-env)
526 cl--generic-nnm-sample))))
527 (setq cnm-env (cdr cnm-env)))))
528 (error "Haven't found no-next-method-sample in cnm-sample")))
529
530 (defun cl--generic-cache-miss (generic dispatch-arg dispatches-left tags)
531 (let ((types (apply #'append (mapcar cl-generic-tag-types-function tags)))
532 (methods '()))
533 (dolist (method-desc (cl--generic-method-table generic))
534 (let* ((specializer (or (nth dispatch-arg (caar method-desc)) t))
535 (m (member specializer types)))
536 (when m
537 (push (cons (length m) method-desc) methods))))
538 ;; Sort the methods, most specific first.
539 ;; It would be tempting to sort them once and for all in the method-table
540 ;; rather than here, but the order might depend on the actual argument
541 ;; (e.g. for multiple inheritance with defclass).
542 (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
543 (cl--generic-make-function (cl--generic-make (cl--generic-name generic)
544 dispatches-left methods))))
545
546 ;;; Define some pre-defined generic functions, used internally.
547
548 (define-error 'cl-no-method "No method for %S")
549 (define-error 'cl-no-next-method "No next method for %S" 'cl-no-method)
550 (define-error 'cl-no-primary-method "No primary method for %S" 'cl-no-method)
551 (define-error 'cl-no-applicable-method "No applicable method for %S"
552 'cl-no-method)
553
554 (cl-defgeneric cl-no-next-method (generic method &rest args)
555 "Function called when `cl-call-next-method' finds no next method.")
556 (cl-defmethod cl-no-next-method (generic method &rest args)
557 (signal 'cl-no-next-method `(,generic ,method ,@args)))
558
559 (cl-defgeneric cl-no-applicable-method (generic &rest args)
560 "Function called when a method call finds no applicable method.")
561 (cl-defmethod cl-no-applicable-method (generic &rest args)
562 (signal 'cl-no-applicable-method `(,generic ,@args)))
563
564 (cl-defgeneric cl-no-primary-method (generic &rest args)
565 "Function called when a method call finds no primary method.")
566 (cl-defmethod cl-no-primary-method (generic &rest args)
567 (signal 'cl-no-primary-method `(,generic ,@args)))
568
569 (defun cl-call-next-method (&rest _args)
570 "Function to call the next applicable method.
571 Can only be used from within the lexical body of a primary or around method."
572 (error "cl-call-next-method only allowed inside primary and around methods"))
573
574 (defun cl-next-method-p ()
575 "Return non-nil if there is a next method.
576 Can only be used from within the lexical body of a primary or around method."
577 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
578 (error "cl-next-method-p only allowed inside primary and around methods"))
579
580 ;;; Add support for describe-function
581
582 (defun cl--generic-search-method (met-name)
583 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
584 (regexp-quote (format "%s\\_>" (car met-name))))))
585 (or
586 (re-search-forward
587 (concat base-re "[^&\"\n]*"
588 (mapconcat (lambda (specializer)
589 (regexp-quote
590 (format "%S" (if (consp specializer)
591 (nth 1 specializer) specializer))))
592 (remq t (cdr met-name))
593 "[ \t\n]*)[^&\"\n]*"))
594 nil t)
595 (re-search-forward base-re nil t))))
596
597
598 (with-eval-after-load 'find-func
599 (defvar find-function-regexp-alist)
600 (add-to-list 'find-function-regexp-alist
601 `(cl-defmethod . ,#'cl--generic-search-method)))
602
603 (defun cl--generic-method-info (method)
604 (pcase-let ((`((,specializers . ,qualifier) ,uses-cnm . ,function) method))
605 (let* ((args (help-function-arglist function 'names))
606 (docstring (documentation function))
607 (doconly (if docstring
608 (let ((split (help-split-fundoc docstring nil)))
609 (if split (cdr split) docstring))))
610 (combined-args ()))
611 (if uses-cnm (setq args (cdr args)))
612 (dolist (specializer specializers)
613 (let ((arg (if (eq '&rest (car args))
614 (intern (format "arg%d" (length combined-args)))
615 (pop args))))
616 (push (if (eq specializer t) arg (list arg specializer))
617 combined-args)))
618 (setq combined-args (append (nreverse combined-args) args))
619 (list qualifier combined-args doconly))))
620
621 (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
622 (defun cl--generic-describe (function)
623 (let ((generic (if (symbolp function) (cl--generic function))))
624 (when generic
625 (require 'help-mode) ;Needed for `help-function-def' button!
626 (save-excursion
627 (insert "\n\nThis is a generic function.\n\n")
628 (insert (propertize "Implementations:\n\n" 'face 'bold))
629 ;; Loop over fanciful generics
630 (dolist (method (cl--generic-method-table generic))
631 (let* ((info (cl--generic-method-info method)))
632 ;; FIXME: Add hyperlinks for the types as well.
633 (insert (format "%S %S" (nth 0 info) (nth 1 info)))
634 (let* ((met-name (cons function (caar method)))
635 (file (find-lisp-object-file-name met-name 'cl-defmethod)))
636 (when file
637 (insert " in `")
638 (help-insert-xref-button (help-fns-short-filename file)
639 'help-function-def met-name file
640 'cl-defmethod)
641 (insert "'.\n")))
642 (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
643
644 ;;; Support for (eql <val>) specializers.
645
646 (defvar cl--generic-eql-used (make-hash-table :test #'eql))
647
648 (add-function :before-until cl-generic-tagcode-function
649 #'cl--generic-eql-tagcode)
650 (defun cl--generic-eql-tagcode (type name)
651 (when (eq (car-safe type) 'eql)
652 (puthash (cadr type) type cl--generic-eql-used)
653 `(100 . (gethash ,name cl--generic-eql-used))))
654
655 (add-function :before-until cl-generic-tag-types-function
656 #'cl--generic-eql-tag-types)
657 (defun cl--generic-eql-tag-types (tag)
658 (if (eq (car-safe tag) 'eql) (list tag)))
659
660 ;;; Support for cl-defstructs specializers.
661
662 (add-function :before-until cl-generic-tagcode-function
663 #'cl--generic-struct-tagcode)
664 (defun cl--generic-struct-tagcode (type name)
665 (and (symbolp type)
666 (get type 'cl-struct-type)
667 (or (eq 'vector (car (get type 'cl-struct-type)))
668 (error "Can't dispatch on cl-struct %S: type is %S"
669 type (car (get type 'cl-struct-type))))
670 (or (equal '(cl-tag-slot) (car (get type 'cl-struct-slots)))
671 (error "Can't dispatch on cl-struct %S: no tag in slot 0"
672 type))
673 ;; We could/should check the vector has length >0,
674 ;; but really, mixing vectors and structs is a bad idea,
675 ;; so let's not waste time trying to handle the case
676 ;; of an empty vector.
677 ;; BEWARE: this returns a bogus tag for non-struct vectors.
678 `(50 . (and (vectorp ,name) (aref ,name 0)))))
679
680 (add-function :before-until cl-generic-tag-types-function
681 #'cl--generic-struct-tag-types)
682 (defun cl--generic-struct-tag-types (tag)
683 ;; FIXME: cl-defstruct doesn't make it easy for us.
684 (and (symbolp tag)
685 ;; A method call shouldn't itself mess with the match-data.
686 (string-match-p "\\`cl-struct-\\(.*\\)" (symbol-name tag))
687 (let ((types (list (intern (substring (symbol-name tag) 10)))))
688 (while (get (car types) 'cl-struct-include)
689 (push (get (car types) 'cl-struct-include) types))
690 (push 'cl-struct types) ;The "parent type" of all cl-structs.
691 (nreverse types))))
692
693 ;;; Dispatch on "old-style types".
694
695 (defconst cl--generic-typeof-types
696 ;; Hand made from the source code of `type-of'.
697 '((integer number) (symbol) (string array) (cons list)
698 ;; Markers aren't `numberp', yet they are accepted wherever integers are
699 ;; accepted, pretty much.
700 (marker) (overlay) (float number) (window-configuration)
701 (process) (window) (subr) (compiled-function) (buffer) (char-table array)
702 (bool-vector array)
703 (frame) (hash-table) (font-spec) (font-entity) (font-object)
704 (vector array)
705 ;; Plus, hand made:
706 (null list symbol)
707 (list)
708 (array)
709 (number)))
710
711 (add-function :before-until cl-generic-tagcode-function
712 #'cl--generic-typeof-tagcode)
713 (defun cl--generic-typeof-tagcode (type name)
714 ;; FIXME: Add support for other types accepted by `cl-typep' such
715 ;; as `character', `atom', `face', `function', ...
716 (and (assq type cl--generic-typeof-types)
717 (progn
718 (if (memq type '(vector array))
719 (message "`%S' also matches CL structs and EIEIO classes" type))
720 ;; FIXME: We could also change `type-of' to return `null' for nil.
721 `(10 . (if ,name (type-of ,name) 'null)))))
722
723 (add-function :before-until cl-generic-tag-types-function
724 #'cl--generic-typeof-types)
725 (defun cl--generic-typeof-types (tag)
726 (and (symbolp tag)
727 (assq tag cl--generic-typeof-types)))
728
729 ;;; Just for kicks: dispatch on major-mode
730 ;;
731 ;; Here's how you'd use it:
732 ;; (cl-defmethod foo ((x (major-mode text-mode)) y z) ...)
733 ;; And then
734 ;; (foo 'major-mode toto titi)
735 ;;
736 ;; FIXME: Better would be to do that via dispatch on an "implicit argument".
737 ;; E.g. (cl-defmethod foo (y z &context (major-mode text-mode)) ...)
738
739 ;; (defvar cl--generic-major-modes (make-hash-table :test #'eq))
740 ;;
741 ;; (add-function :before-until cl-generic-tagcode-function
742 ;; #'cl--generic-major-mode-tagcode)
743 ;; (defun cl--generic-major-mode-tagcode (type name)
744 ;; (if (eq 'major-mode (car-safe type))
745 ;; `(50 . (if (eq ,name 'major-mode)
746 ;; (cl--generic-with-memoization
747 ;; (gethash major-mode cl--generic-major-modes)
748 ;; `(cl--generic-major-mode . ,major-mode))))))
749 ;;
750 ;; (add-function :before-until cl-generic-tag-types-function
751 ;; #'cl--generic-major-mode-types)
752 ;; (defun cl--generic-major-mode-types (tag)
753 ;; (when (eq (car-safe tag) 'cl--generic-major-mode)
754 ;; (if (eq tag 'fundamental-mode) '(fundamental-mode t)
755 ;; (let ((types `((major-mode ,(cdr tag)))))
756 ;; (while (get (car types) 'derived-mode-parent)
757 ;; (push (list 'major-mode (get (car types) 'derived-mode-parent))
758 ;; types))
759 ;; (unless (eq 'fundamental-mode (car types))
760 ;; (push '(major-mode fundamental-mode) types))
761 ;; (nreverse types)))))
762
763 ;; Local variables:
764 ;; generated-autoload-file: "cl-loaddefs.el"
765 ;; End:
766
767 (provide 'cl-generic)
768 ;;; cl-generic.el ends here