* lisp/emacs-lisp/cl-generic.el: Add support for cl-next-method-p.
[emacs.git] / lisp / emacs-lisp / cl-generic.el
blob819e2e928888df7c7b12a12b54c02cbcaf949823
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 ;; - 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.
44 ;;; Code:
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.
52 (eval-when-compile (require 'cl-lib))
53 (eval-when-compile (require 'pcase))
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.")
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.")
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)
98 (defmacro cl--generic (name)
99 `(get ,name 'cl--generic))
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))
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))))))))
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)))))
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)))
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)))
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"))
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))
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 (if (not with-cnm)
216 (cons nil (macroexpand-all fun macroenv))
217 ;; First macroexpand away the cl-function stuff (e.g. &key and
218 ;; destructuring args, `declare' and whatnot).
219 (pcase (macroexpand fun macroenv)
220 (`#'(lambda ,args . ,body)
221 (require 'cl-lib) ;Needed to expand `cl-flet'.
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))))))))
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.
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.
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.
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 (cl-generic-define-method ',name ',qualifiers ',args
291 ,uses-cnm ,fun)))))
293 ;;;###autoload
294 (defun cl-generic-define-method (name qualifiers args uses-cnm function)
295 (when (> (length qualifiers) 1)
296 (error "We only support a single qualifier per method: %S" qualifiers))
297 (unless (memq (car qualifiers) '(nil :primary :around :after :before))
298 (error "Unsupported qualifier in: %S" qualifiers))
299 (let* ((generic (cl-generic-ensure-function name))
300 (mandatory (cl--generic-mandatory-args args))
301 (specializers
302 (mapcar (lambda (arg) (if (consp arg) (cadr arg) t)) mandatory))
303 (key (cons specializers (or (car qualifiers) ':primary)))
304 (mt (cl--generic-method-table generic))
305 (me (assoc key mt))
306 (dispatches (cl--generic-dispatches generic))
307 (i 0))
308 (dolist (specializer specializers)
309 (let* ((tagcode (funcall cl-generic-tagcode-function specializer 'arg))
310 (x (assq i dispatches)))
311 (if (not x)
312 (setf (cl--generic-dispatches generic)
313 (setq dispatches (cons (list i tagcode) dispatches)))
314 (unless (member tagcode (cdr x))
315 (setf (cdr x)
316 (nreverse (sort (cons tagcode (cdr x))
317 #'car-less-than-car)))))
318 (setq i (1+ i))))
319 (if me (setcdr me (cons uses-cnm function))
320 (setf (cl--generic-method-table generic)
321 (cons `(,key ,uses-cnm . ,function) mt)))
322 ;; For aliases, cl--generic-name gives us the actual name.
323 (let ((gfun (cl--generic-make-function generic))
324 ;; Prevent `defalias' from recording this as the definition site of
325 ;; the generic function.
326 current-load-list)
327 (defalias (cl--generic-name generic) gfun))
328 (cl-pushnew `(cl-defmethod . (,(cl--generic-name generic) . ,specializers))
329 current-load-list :test #'equal)))
331 (defmacro cl--generic-with-memoization (place &rest code)
332 (declare (indent 1) (debug t))
333 (gv-letplace (getter setter) place
334 `(or ,getter
335 ,(macroexp-let2 nil val (macroexp-progn code)
336 `(progn
337 ,(funcall setter val)
338 ,val)))))
340 (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
342 (defun cl--generic-get-dispatcher (tagcodes dispatch-arg)
343 (cl--generic-with-memoization
344 (gethash (cons dispatch-arg tagcodes) cl--generic-dispatchers)
345 (let ((lexical-binding t)
346 (tag-exp `(or ,@(mapcar #'cdr
347 ;; Minor optimization: since this tag-exp is
348 ;; only used to lookup the method-cache, it
349 ;; doesn't matter if the default value is some
350 ;; constant or nil.
351 (if (macroexp-const-p (car (last tagcodes)))
352 (butlast tagcodes)
353 tagcodes))))
354 (extraargs ()))
355 (dotimes (_ dispatch-arg)
356 (push (make-symbol "arg") extraargs))
357 (byte-compile
358 `(lambda (generic dispatches-left)
359 (let ((method-cache (make-hash-table :test #'eql)))
360 (lambda (,@extraargs arg &rest args)
361 (apply (cl--generic-with-memoization
362 (gethash ,tag-exp method-cache)
363 (cl--generic-cache-miss
364 generic ',dispatch-arg dispatches-left
365 (list ,@(mapcar #'cdr tagcodes))))
366 ,@extraargs arg args))))))))
368 (defun cl--generic-make-function (generic)
369 (let* ((dispatches (cl--generic-dispatches generic))
370 (dispatch
371 (progn
372 (while (and dispatches
373 (member (cdar dispatches)
374 '(nil ((0 . 'cl--generic-type)))))
375 (setq dispatches (cdr dispatches)))
376 (pop dispatches))))
377 (if (null dispatch)
378 (cl--generic-build-combined-method
379 (cl--generic-name generic)
380 (cl--generic-method-table generic))
381 (let ((dispatcher (cl--generic-get-dispatcher
382 (cdr dispatch) (car dispatch))))
383 (funcall dispatcher generic dispatches)))))
385 (defun cl--generic-nest (fun methods)
386 (pcase-dolist (`(,uses-cnm . ,method) methods)
387 (setq fun
388 (if (not uses-cnm) method
389 (let ((next fun))
390 (lambda (&rest args)
391 (apply method
392 ;; FIXME: This sucks: passing just `next' would
393 ;; be a lot more efficient than the lambda+apply
394 ;; quasi-η, but we need this to implement the
395 ;; "if call-next-method is called with no
396 ;; arguments, then use the previous arguments".
397 (lambda (&rest cnm-args)
398 (apply next (or cnm-args args)))
399 args))))))
400 fun)
402 (defvar cl--generic-combined-method-memoization
403 (make-hash-table :test #'equal :weakness 'value)
404 "Table storing previously built combined-methods.
405 This is particularly useful when many different tags select the same set
406 of methods, since this table then allows us to share a single combined-method
407 for all those different tags in the method-cache.")
409 (defun cl--generic-build-combined-method (generic-name methods)
410 (let ((mets-by-qual ()))
411 (dolist (qm methods)
412 (push (cdr qm) (alist-get (cdar qm) mets-by-qual)))
413 (cl--generic-with-memoization
414 (gethash (cons generic-name mets-by-qual)
415 cl--generic-combined-method-memoization)
416 (cond
417 ((null mets-by-qual) (lambda (&rest args)
418 (apply #'cl-no-applicable-method
419 generic-name args)))
421 (let* ((fun (lambda (&rest args)
422 ;; FIXME: CLOS passes as second arg the "calling method".
423 ;; We don't currently have "method objects" like CLOS
424 ;; does so we can't really do it the CLOS way.
425 ;; The closest would be to pass the lambda corresponding
426 ;; to the method, but the caller wouldn't be able to do
427 ;; much with it anyway. So we pass nil for now.
428 (apply #'cl-no-next-method generic-name nil args)))
429 ;; We use `cdr' to drop the `uses-cnm' annotations.
430 (before
431 (mapcar #'cdr (reverse (alist-get :before mets-by-qual))))
432 (after (mapcar #'cdr (alist-get :after mets-by-qual))))
433 (setq fun (cl--generic-nest fun (alist-get :primary mets-by-qual)))
434 (when (or after before)
435 (let ((next fun))
436 (setq fun (lambda (&rest args)
437 (dolist (bf before)
438 (apply bf args))
439 (prog1
440 (apply next args)
441 (dolist (af after)
442 (apply af args)))))))
443 (cl--generic-nest fun (alist-get :around mets-by-qual))))))))
445 (defconst cl--generic-nnm-sample
446 (cl--generic-build-combined-method nil '(((specializer . :qualifier)))))
447 (defconst cl--generic-cnm-sample
448 (funcall (cl--generic-build-combined-method
449 nil `(((specializer . :primary) t . ,#'identity)))))
451 (defun cl--generic-isnot-nnm-p (cnm)
452 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
453 ;; ¡Big Gross Ugly Hack!
454 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
455 ;; it, and some packages use it, so we need to support it.
456 (catch 'found
457 (cl-assert (function-equal cnm cl--generic-cnm-sample))
458 (if (byte-code-function-p cnm)
459 (let ((cnm-constants (aref cnm 2))
460 (sample-constants (aref cl--generic-cnm-sample 2)))
461 (dotimes (i (length sample-constants))
462 (when (function-equal (aref sample-constants i)
463 cl--generic-nnm-sample)
464 (throw 'found
465 (not (function-equal (aref cnm-constants i)
466 cl--generic-nnm-sample))))))
467 (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
468 (let ((cnm-env (cadr cnm)))
469 (dolist (vb (cadr cl--generic-cnm-sample))
470 (when (function-equal (cdr vb) cl--generic-nnm-sample)
471 (throw 'found
472 (not (function-equal (cdar cnm-env)
473 cl--generic-nnm-sample))))
474 (setq cnm-env (cdr cnm-env)))))
475 (error "Haven't found no-next-method-sample in cnm-sample")))
477 (defun cl--generic-cache-miss (generic dispatch-arg dispatches-left tags)
478 (let ((types (apply #'append (mapcar cl-generic-tag-types-function tags)))
479 (methods '()))
480 (dolist (method-desc (cl--generic-method-table generic))
481 (let ((m (member (nth dispatch-arg (caar method-desc)) types)))
482 (when m
483 (push (cons (length m) method-desc) methods))))
484 ;; Sort the methods, most specific first.
485 ;; It would be tempting to sort them once and for all in the method-table
486 ;; rather than here, but the order might depend on the actual argument
487 ;; (e.g. for multiple inheritance with defclass).
488 (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
489 (cl--generic-make-function (cl--generic-make (cl--generic-name generic)
490 dispatches-left methods))))
492 ;;; Define some pre-defined generic functions, used internally.
494 (define-error 'cl-no-method "No method for %S")
495 (define-error 'cl-no-next-method "No next method for %S" 'cl-no-method)
496 (define-error 'cl-no-applicable-method "No applicable method for %S"
497 'cl-no-method)
499 (cl-defgeneric cl-no-next-method (generic method &rest args)
500 "Function called when `cl-call-next-method' finds no next method.")
501 (cl-defmethod cl-no-next-method (generic method &rest args)
502 (signal 'cl-no-next-method `(,generic ,method ,@args)))
504 (cl-defgeneric cl-no-applicable-method (generic &rest args)
505 "Function called when a method call finds no applicable method.")
506 (cl-defmethod cl-no-applicable-method (generic &rest args)
507 (signal 'cl-no-applicable-method `(,generic ,@args)))
509 (defun cl-call-next-method (&rest _args)
510 "Function to call the next applicable method.
511 Can only be used from within the lexical body of a primary or around method."
512 (error "cl-call-next-method only allowed inside primary and around methods"))
514 (defun cl-next-method-p ()
515 "Return non-nil if there is a next method.
516 Can only be used from within the lexical body of a primary or around method."
517 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
518 (error "cl-next-method-p only allowed inside primary and around methods"))
520 ;;; Add support for describe-function
522 (defun cl--generic-search-method (met-name)
523 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
524 (regexp-quote (format "%s\\_>" (car met-name))))))
526 (re-search-forward
527 (concat base-re "[^&\"\n]*"
528 (mapconcat (lambda (specializer)
529 (regexp-quote
530 (format "%S" (if (consp specializer)
531 (nth 1 specializer) specializer))))
532 (remq t (cdr met-name))
533 "[ \t\n]*)[^&\"\n]*"))
534 nil t)
535 (re-search-forward base-re nil t))))
538 (with-eval-after-load 'find-func
539 (defvar find-function-regexp-alist)
540 (add-to-list 'find-function-regexp-alist
541 `(cl-defmethod . ,#'cl--generic-search-method)))
543 (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
544 (defun cl--generic-describe (function)
545 (let ((generic (if (symbolp function) (cl--generic function))))
546 (when generic
547 (require 'help-mode) ;Needed for `help-function-def' button!
548 (save-excursion
549 (insert "\n\nThis is a generic function.\n\n")
550 (insert (propertize "Implementations:\n\n" 'face 'bold))
551 ;; Loop over fanciful generics
552 (pcase-dolist (`((,specializers . ,qualifier) ,uses-cnm . ,method)
553 (cl--generic-method-table generic))
554 (let* ((args (help-function-arglist method 'names))
555 (docstring (documentation method))
556 (doconly (if docstring
557 (let ((split (help-split-fundoc docstring nil)))
558 (if split (cdr split) docstring))))
559 (combined-args ()))
560 (if uses-cnm (setq args (cdr args)))
561 (dolist (specializer specializers)
562 (let ((arg (if (eq '&rest (car args))
563 (intern (format "arg%d" (length combined-args)))
564 (pop args))))
565 (push (if (eq specializer t) arg (list arg specializer))
566 combined-args)))
567 (setq combined-args (append (nreverse combined-args) args))
568 ;; FIXME: Add hyperlinks for the types as well.
569 (insert (format "%S %S" qualifier combined-args))
570 (let* ((met-name (cons function specializers))
571 (file (find-lisp-object-file-name met-name 'cl-defmethod)))
572 (when file
573 (insert " in `")
574 (help-insert-xref-button (help-fns-short-filename file)
575 'help-function-def met-name file
576 'cl-defmethod)
577 (insert "'.\n")))
578 (insert "\n" (or doconly "Undocumented") "\n\n")))))))
580 ;;; Support for (eql <val>) specializers.
582 (defvar cl--generic-eql-used (make-hash-table :test #'eql))
584 (add-function :before-until cl-generic-tagcode-function
585 #'cl--generic-eql-tagcode)
586 (defun cl--generic-eql-tagcode (type name)
587 (when (eq (car-safe type) 'eql)
588 (puthash (cadr type) type cl--generic-eql-used)
589 `(100 . (gethash ,name cl--generic-eql-used))))
591 (add-function :before-until cl-generic-tag-types-function
592 #'cl--generic-eql-tag-types)
593 (defun cl--generic-eql-tag-types (tag)
594 (if (eq (car-safe tag) 'eql) (list tag)))
596 ;;; Support for cl-defstructs specializers.
598 (add-function :before-until cl-generic-tagcode-function
599 #'cl--generic-struct-tagcode)
600 (defun cl--generic-struct-tagcode (type name)
601 (and (symbolp type)
602 (get type 'cl-struct-type)
603 (or (eq 'vector (car (get type 'cl-struct-type)))
604 (error "Can't dispatch on cl-struct %S: type is %S"
605 type (car (get type 'cl-struct-type))))
606 (or (equal '(cl-tag-slot) (car (get type 'cl-struct-slots)))
607 (error "Can't dispatch on cl-struct %S: no tag in slot 0"
608 type))
609 ;; We could/should check the vector has length >0,
610 ;; but really, mixing vectors and structs is a bad idea,
611 ;; so let's not waste time trying to handle the case
612 ;; of an empty vector.
613 ;; BEWARE: this returns a bogus tag for non-struct vectors.
614 `(50 . (and (vectorp ,name) (aref ,name 0)))))
616 (add-function :before-until cl-generic-tag-types-function
617 #'cl--generic-struct-tag-types)
618 (defun cl--generic-struct-tag-types (tag)
619 ;; FIXME: cl-defstruct doesn't make it easy for us.
620 (and (symbolp tag)
621 ;; A method call shouldn't itself mess with the match-data.
622 (string-match-p "\\`cl-struct-\\(.*\\)" (symbol-name tag))
623 (let ((types (list (intern (substring (symbol-name tag) 10)))))
624 (while (get (car types) 'cl-struct-include)
625 (push (get (car types) 'cl-struct-include) types))
626 (push 'cl-struct types) ;The "parent type" of all cl-structs.
627 (nreverse types))))
629 ;;; Dispatch on "old-style types".
631 (defconst cl--generic-typeof-types
632 ;; Hand made from the source code of `type-of'.
633 '((integer number) (symbol) (string array) (cons list)
634 ;; Markers aren't `numberp', yet they are accepted wherever integers are
635 ;; accepted, pretty much.
636 (marker) (overlay) (float number) (window-configuration)
637 (process) (window) (subr) (compiled-function) (buffer) (char-table array)
638 (bool-vector array)
639 (frame) (hash-table) (font-spec) (font-entity) (font-object)
640 (vector array)
641 ;; Plus, hand made:
642 (null list symbol)
643 (list)
644 (array)
645 (number)))
647 (add-function :before-until cl-generic-tagcode-function
648 #'cl--generic-typeof-tagcode)
649 (defun cl--generic-typeof-tagcode (type name)
650 ;; FIXME: Add support for other types accepted by `cl-typep' such
651 ;; as `character', `atom', `face', `function', ...
652 (and (assq type cl--generic-typeof-types)
653 (progn
654 (if (memq type '(vector array))
655 (message "`%S' also matches CL structs and EIEIO classes" type))
656 ;; FIXME: We could also change `type-of' to return `null' for nil.
657 `(10 . (if ,name (type-of ,name) 'null)))))
659 (add-function :before-until cl-generic-tag-types-function
660 #'cl--generic-typeof-types)
661 (defun cl--generic-typeof-types (tag)
662 (and (symbolp tag)
663 (assq tag cl--generic-typeof-types)))
665 ;;; Just for kicks: dispatch on major-mode
667 ;; Here's how you'd use it:
668 ;; (cl-defmethod foo ((x (major-mode text-mode)) y z) ...)
669 ;; And then
670 ;; (foo 'major-mode toto titi)
672 ;; FIXME: Better would be to do that via dispatch on an "implicit argument".
674 ;; (defvar cl--generic-major-modes (make-hash-table :test #'eq))
676 ;; (add-function :before-until cl-generic-tagcode-function
677 ;; #'cl--generic-major-mode-tagcode)
678 ;; (defun cl--generic-major-mode-tagcode (type name)
679 ;; (if (eq 'major-mode (car-safe type))
680 ;; `(50 . (if (eq ,name 'major-mode)
681 ;; (cl--generic-with-memoization
682 ;; (gethash major-mode cl--generic-major-modes)
683 ;; `(cl--generic-major-mode . ,major-mode))))))
685 ;; (add-function :before-until cl-generic-tag-types-function
686 ;; #'cl--generic-major-mode-types)
687 ;; (defun cl--generic-major-mode-types (tag)
688 ;; (when (eq (car-safe tag) 'cl--generic-major-mode)
689 ;; (if (eq tag 'fundamental-mode) '(fundamental-mode t)
690 ;; (let ((types `((major-mode ,(cdr tag)))))
691 ;; (while (get (car types) 'derived-mode-parent)
692 ;; (push (list 'major-mode (get (car types) 'derived-mode-parent))
693 ;; types))
694 ;; (unless (eq 'fundamental-mode (car types))
695 ;; (push '(major-mode fundamental-mode) types))
696 ;; (nreverse types)))))
698 ;; Local variables:
699 ;; generated-autoload-file: "cl-loaddefs.el"
700 ;; End:
702 (provide 'cl-generic)
703 ;;; cl-generic.el ends here