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