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