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