]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/cl-generic.el
Merge from origin/emacs-24
[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 ;; 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. Given how rarely method-combinations are used,
34 ;; I just provided a cl-generic-method-combination-function, which
35 ;; people can use if they are really desperate for such functionality.
36 ;; - In defgeneric we don't support the options:
37 ;; declare, :method-combination, :generic-function-class, :method-class,
38 ;; :method.
39 ;; Added elements:
40 ;; - We support aliases to generic functions.
41 ;; - The kind of thing on which to dispatch can be extended.
42 ;; There is support in this file for dispatch on:
43 ;; - (eql <val>)
44 ;; - plain old types
45 ;; - type of CL structs
46 ;; eieio-core adds dispatch on:
47 ;; - class of eieio objects
48 ;; - actual class argument, using the syntax (subclass <class>).
49 ;; - cl-generic-method-combination-function (i.s.o define-method-combination).
50 ;; - cl-generic-call-method (which replaces make-method and call-method).
51
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.
64
65 ;;; Code:
66
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.
72
73 ;; TODO/FIXME:
74 ;; - WIBNI we could use something like
75 ;; (add-function :before (cl-method-function (cl-find-method ...)) ...)
76
77 (eval-when-compile (require 'cl-lib))
78 (eval-when-compile (require 'pcase))
79
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.")
98
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.")
103
104 (cl-defstruct (cl--generic-method
105 (:constructor nil)
106 (:constructor cl--generic-method-make
107 (specializers qualifiers uses-cnm function))
108 (:predicate nil))
109 (specializers nil :read-only t :type list)
110 (qualifiers nil :read-only t :type (list-of atom))
111 ;; USES-CNM is a boolean indicating if FUNCTION expects an extra argument
112 ;; holding the next-method.
113 (uses-cnm nil :read-only t :type boolean)
114 (function nil :read-only t :type function))
115
116 (cl-defstruct (cl--generic
117 (:constructor nil)
118 (:constructor cl--generic-make
119 (name &optional dispatches method-table))
120 (:predicate nil))
121 (name nil :type symbol :read-only t) ;Pointer back to the symbol.
122 ;; `dispatches' holds a list of (ARGNUM . TAGCODES) where ARGNUM is the index
123 ;; of the corresponding argument and TAGCODES is a list of (PRIORITY . EXP)
124 ;; where the EXPs are expressions (to be `or'd together) to compute the tag
125 ;; on which to dispatch and PRIORITY is the priority of each expression to
126 ;; decide in which order to sort them.
127 ;; The most important dispatch is last in the list (and the least is first).
128 (dispatches nil :type (list-of (cons natnum (list-of tagcode))))
129 (method-table nil :type (list-of cl--generic-method)))
130
131 (defmacro cl--generic (name)
132 `(get ,name 'cl--generic))
133
134 (defun cl-generic-ensure-function (name)
135 (let (generic
136 (origname name))
137 (while (and (null (setq generic (cl--generic name)))
138 (fboundp name)
139 (symbolp (symbol-function name)))
140 (setq name (symbol-function name)))
141 (unless (or (not (fboundp name))
142 (autoloadp (symbol-function name))
143 (and (functionp name) generic))
144 (error "%s is already defined as something else than a generic function"
145 origname))
146 (if generic
147 (cl-assert (eq name (cl--generic-name generic)))
148 (setf (cl--generic name) (setq generic (cl--generic-make name)))
149 (defalias name (cl--generic-make-function generic)))
150 generic))
151
152 (defun cl--generic-setf-rewrite (name)
153 (let* ((setter (intern (format "cl-generic-setter--%s" name)))
154 (exp `(unless (eq ',setter (get ',name 'cl-generic-setter))
155 ;; (when (get ',name 'gv-expander)
156 ;; (error "gv-expander conflicts with (setf %S)" ',name))
157 (setf (get ',name 'cl-generic-setter) ',setter)
158 (gv-define-setter ,name (val &rest args)
159 (cons ',setter (cons val args))))))
160 ;; Make sure `setf' can be used right away, e.g. in the body of the method.
161 (eval exp t)
162 (cons setter exp)))
163
164 ;;;###autoload
165 (defmacro cl-defgeneric (name args &rest options-and-methods)
166 "Create a generic function NAME.
167 DOC-STRING is the base documentation for this class. A generic
168 function has no body, as its purpose is to decide which method body
169 is appropriate to use. Specific methods are defined with `cl-defmethod'.
170 With this implementation the ARGS are currently ignored.
171 OPTIONS-AND-METHODS currently understands:
172 - (:documentation DOCSTRING)
173 - (declare DECLARATIONS)"
174 (declare (indent 2) (doc-string 3))
175 (let* ((docprop (assq :documentation options-and-methods))
176 (doc (cond ((stringp (car-safe options-and-methods))
177 (pop options-and-methods))
178 (docprop
179 (prog1
180 (cadr docprop)
181 (setq options-and-methods
182 (delq docprop options-and-methods))))))
183 (declarations (assq 'declare options-and-methods)))
184 (when declarations
185 (setq options-and-methods
186 (delq declarations options-and-methods)))
187 `(progn
188 ,(when (eq 'setf (car-safe name))
189 (pcase-let ((`(,setter . ,code) (cl--generic-setf-rewrite
190 (cadr name))))
191 (setq name setter)
192 code))
193 ,@(mapcar (lambda (declaration)
194 (let ((f (cdr (assq (car declaration)
195 defun-declarations-alist))))
196 (cond
197 (f (apply (car f) name args (cdr declaration)))
198 (t (message "Warning: Unknown defun property `%S' in %S"
199 (car declaration) name)
200 nil))))
201 (cdr declarations))
202 (defalias ',name
203 (cl-generic-define ',name ',args ',options-and-methods)
204 ,(help-add-fundoc-usage doc args)))))
205
206 (defun cl--generic-mandatory-args (args)
207 (let ((res ()))
208 (while (not (memq (car args) '(nil &rest &optional &key)))
209 (push (pop args) res))
210 (nreverse res)))
211
212 ;;;###autoload
213 (defun cl-generic-define (name args options-and-methods)
214 (let ((generic (cl-generic-ensure-function name))
215 (mandatory (cl--generic-mandatory-args args))
216 (apo (assq :argument-precedence-order options-and-methods)))
217 (setf (cl--generic-dispatches generic) nil)
218 (when apo
219 (dolist (arg (cdr apo))
220 (let ((pos (memq arg mandatory)))
221 (unless pos (error "%S is not a mandatory argument" arg))
222 (push (list (- (length mandatory) (length pos)))
223 (cl--generic-dispatches generic)))))
224 (setf (cl--generic-method-table generic) nil)
225 (cl--generic-make-function generic)))
226
227 (defmacro cl-generic-current-method-specializers ()
228 "List of (VAR . TYPE) where TYPE is var's specializer.
229 This macro can only be used within the lexical scope of a cl-generic method."
230 (error "cl-generic-current-method-specializers used outside of a method"))
231
232 (eval-and-compile ;Needed while compiling the cl-defmethod calls below!
233 (defun cl--generic-fgrep (vars sexp) ;Copied from pcase.el.
234 "Check which of the symbols VARS appear in SEXP."
235 (let ((res '()))
236 (while (consp sexp)
237 (dolist (var (cl--generic-fgrep vars (pop sexp)))
238 (unless (memq var res) (push var res))))
239 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
240 res))
241
242 (defun cl--generic-lambda (args body)
243 "Make the lambda expression for a method with ARGS and BODY."
244 (let ((plain-args ())
245 (specializers nil)
246 (mandatory t))
247 (dolist (arg args)
248 (push (pcase arg
249 ((or '&optional '&rest '&key) (setq mandatory nil) arg)
250 ((and `(,name . ,type) (guard mandatory))
251 (push (cons name (car type)) specializers)
252 name)
253 (_ arg))
254 plain-args))
255 (setq plain-args (nreverse plain-args))
256 (let ((fun `(cl-function (lambda ,plain-args ,@body)))
257 (macroenv (cons `(cl-generic-current-method-specializers
258 . ,(lambda () specializers))
259 macroexpand-all-environment)))
260 (require 'cl-lib) ;Needed to expand `cl-flet' and `cl-function'.
261 ;; First macroexpand away the cl-function stuff (e.g. &key and
262 ;; destructuring args, `declare' and whatnot).
263 (pcase (macroexpand fun macroenv)
264 (`#'(lambda ,args . ,body)
265 (let* ((parsed-body (macroexp-parse-body 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 ,@(cdr parsed-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 ,@(car parsed-body)
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)))))))
288
289
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.
299
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.
306
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.
309
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* ((`(,uses-cnm . ,fun) (cl--generic-lambda args body)))
328 `(progn
329 ,(when setfizer
330 (setq name (car setfizer))
331 (cdr setfizer))
332 ,(and (get name 'byte-obsolete-info)
333 (or (not (fboundp 'byte-compile-warning-enabled-p))
334 (byte-compile-warning-enabled-p 'obsolete))
335 (let* ((obsolete (get name 'byte-obsolete-info)))
336 (macroexp--warn-and-return
337 (macroexp--obsolete-warning name obsolete "generic function")
338 nil)))
339 ;; You could argue that `defmethod' modifies rather than defines the
340 ;; function, so warnings like "not known to be defined" are fair game.
341 ;; But in practice, it's common to use `cl-defmethod'
342 ;; without a previous `cl-defgeneric'.
343 (declare-function ,name "")
344 (cl-generic-define-method ',name ',qualifiers ',args
345 ,uses-cnm ,fun)))))
346
347 (defun cl--generic-member-method (specializers qualifiers methods)
348 (while
349 (and methods
350 (let ((m (car methods)))
351 (not (and (equal (cl--generic-method-specializers m) specializers)
352 (equal (cl--generic-method-qualifiers m) qualifiers)))))
353 (setq methods (cdr methods)))
354 methods)
355
356 ;;;###autoload
357 (defun cl-generic-define-method (name qualifiers args uses-cnm function)
358 (let* ((generic (cl-generic-ensure-function name))
359 (mandatory (cl--generic-mandatory-args args))
360 (specializers
361 (mapcar (lambda (arg) (if (consp arg) (cadr arg) t)) mandatory))
362 (method (cl--generic-method-make
363 specializers qualifiers uses-cnm function))
364 (mt (cl--generic-method-table generic))
365 (me (cl--generic-member-method specializers qualifiers mt))
366 (dispatches (cl--generic-dispatches generic))
367 (i 0))
368 (dolist (specializer specializers)
369 (let* ((tagcode (funcall cl-generic-tagcode-function specializer 'arg))
370 (x (assq i dispatches)))
371 (unless x
372 (setq x (list i (funcall cl-generic-tagcode-function t 'arg)))
373 (setf (cl--generic-dispatches generic)
374 (setq dispatches (cons x dispatches))))
375 (unless (member tagcode (cdr x))
376 (setf (cdr x)
377 (nreverse (sort (cons tagcode (cdr x))
378 #'car-less-than-car))))
379 (setq i (1+ i))))
380 (if me (setcar me method)
381 (setf (cl--generic-method-table generic) (cons method mt)))
382 (cl-pushnew `(cl-defmethod . (,(cl--generic-name generic) . ,specializers))
383 current-load-list :test #'equal)
384 (let ((gfun (cl--generic-make-function generic))
385 ;; Prevent `defalias' from recording this as the definition site of
386 ;; the generic function.
387 current-load-list)
388 ;; For aliases, cl--generic-name gives us the actual name.
389 (defalias (cl--generic-name generic) gfun))))
390
391 (defmacro cl--generic-with-memoization (place &rest code)
392 (declare (indent 1) (debug t))
393 (gv-letplace (getter setter) place
394 `(or ,getter
395 ,(macroexp-let2 nil val (macroexp-progn code)
396 `(progn
397 ,(funcall setter val)
398 ,val)))))
399
400 (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
401
402 (defun cl--generic-get-dispatcher (tagcodes dispatch-arg)
403 (cl--generic-with-memoization
404 (gethash (cons dispatch-arg tagcodes) cl--generic-dispatchers)
405 (let ((lexical-binding t)
406 (tag-exp `(or ,@(mapcar #'cdr
407 ;; Minor optimization: since this tag-exp is
408 ;; only used to lookup the method-cache, it
409 ;; doesn't matter if the default value is some
410 ;; constant or nil.
411 (if (macroexp-const-p (car (last tagcodes)))
412 (butlast tagcodes)
413 tagcodes))))
414 (extraargs ()))
415 (dotimes (_ dispatch-arg)
416 (push (make-symbol "arg") extraargs))
417 (byte-compile
418 `(lambda (generic dispatches-left)
419 (let ((method-cache (make-hash-table :test #'eql)))
420 (lambda (,@extraargs arg &rest args)
421 (apply (cl--generic-with-memoization
422 (gethash ,tag-exp method-cache)
423 (cl--generic-cache-miss
424 generic ',dispatch-arg dispatches-left
425 (list ,@(mapcar #'cdr tagcodes))))
426 ,@extraargs arg args))))))))
427
428 (defun cl--generic-make-function (generic)
429 (let* ((dispatches (cl--generic-dispatches generic))
430 (dispatch
431 (progn
432 (while (and dispatches
433 (member (cdar dispatches)
434 '(nil ((0 . 'cl--generic-type)))))
435 (setq dispatches (cdr dispatches)))
436 (pop dispatches))))
437 (if (null dispatch)
438 (cl--generic-build-combined-method
439 (cl--generic-name generic)
440 (cl--generic-method-table generic))
441 (let ((dispatcher (cl--generic-get-dispatcher
442 (cdr dispatch) (car dispatch))))
443 (funcall dispatcher generic dispatches)))))
444
445 (defvar cl-generic-method-combination-function
446 #'cl--generic-standard-method-combination
447 "Function to build the effective method.
448 Called with 2 arguments: NAME and METHOD-ALIST.
449 It should return an effective method, i.e. a function that expects the same
450 arguments as the methods, and calls those methods in some appropriate order.
451 NAME is the name (a symbol) of the corresponding generic function.
452 METHOD-ALIST is a list of elements (QUALIFIERS . METHODS) where
453 QUALIFIERS is a list of qualifiers, and METHODS is a list of the selected
454 methods for that qualifier list.
455 The METHODS lists are sorted from most generic first to most specific last.
456 The function can use `cl-generic-call-method' to create functions that call those
457 methods.")
458
459 (defvar cl--generic-combined-method-memoization
460 (make-hash-table :test #'equal :weakness 'value)
461 "Table storing previously built combined-methods.
462 This is particularly useful when many different tags select the same set
463 of methods, since this table then allows us to share a single combined-method
464 for all those different tags in the method-cache.")
465
466 (defun cl--generic-build-combined-method (generic-name methods)
467 (cl--generic-with-memoization
468 (gethash (cons generic-name methods)
469 cl--generic-combined-method-memoization)
470 (let ((mets-by-qual ()))
471 (dolist (method methods)
472 (let* ((qualifiers (cl--generic-method-qualifiers method))
473 (x (assoc qualifiers mets-by-qual)))
474 ;; FIXME: sadly, alist-get only uses `assq' and we need `assoc'.
475 ;;(push (cdr qm) (alist-get qualifiers mets-by-qual)))
476 (if x
477 (push method (cdr x))
478 (push (list qualifiers method) mets-by-qual))))
479 (funcall cl-generic-method-combination-function
480 generic-name mets-by-qual))))
481
482 (defun cl--generic-no-next-method-function (generic method)
483 (lambda (&rest args)
484 (apply #'cl-no-next-method generic method args)))
485
486 (defun cl-generic-call-method (generic-name method &optional fun)
487 "Return a function that calls METHOD.
488 FUN is the function that should be called when METHOD calls
489 `call-next-method'."
490 (if (not (cl--generic-method-uses-cnm method))
491 (cl--generic-method-function method)
492 (let ((met-fun (cl--generic-method-function method))
493 (next (or fun (cl--generic-no-next-method-function
494 generic-name method))))
495 (lambda (&rest args)
496 (apply met-fun
497 ;; FIXME: This sucks: passing just `next' would
498 ;; be a lot more efficient than the lambda+apply
499 ;; quasi-η, but we need this to implement the
500 ;; "if call-next-method is called with no
501 ;; arguments, then use the previous arguments".
502 (lambda (&rest cnm-args)
503 (apply next (or cnm-args args)))
504 args)))))
505
506 (defun cl--generic-standard-method-combination (generic-name mets-by-qual)
507 (dolist (x mets-by-qual)
508 (unless (member (car x) '(() (:after) (:before) (:around)))
509 (error "Unsupported qualifiers in function %S: %S" generic-name (car x))))
510 (cond
511 ((null mets-by-qual)
512 (lambda (&rest args)
513 (apply #'cl-no-applicable-method generic-name args)))
514 ((null (alist-get nil mets-by-qual))
515 (lambda (&rest args)
516 (apply #'cl-no-primary-method generic-name args)))
517 (t
518 (let* ((fun nil)
519 (ab-call (lambda (m) (cl-generic-call-method generic-name m)))
520 (before
521 (mapcar ab-call (reverse (cdr (assoc '(:before) mets-by-qual)))))
522 (after (mapcar ab-call (cdr (assoc '(:after) mets-by-qual)))))
523 (dolist (method (cdr (assoc nil mets-by-qual)))
524 (setq fun (cl-generic-call-method generic-name method fun)))
525 (when (or after before)
526 (let ((next fun))
527 (setq fun (lambda (&rest args)
528 (dolist (bf before)
529 (apply bf args))
530 (prog1
531 (apply next args)
532 (dolist (af after)
533 (apply af args)))))))
534 (dolist (method (cdr (assoc '(:around) mets-by-qual)))
535 (setq fun (cl-generic-call-method generic-name method fun)))
536 fun))))
537
538 (defconst cl--generic-nnm-sample (cl--generic-no-next-method-function t t))
539 (defconst cl--generic-cnm-sample
540 (funcall (cl--generic-build-combined-method
541 nil (list (cl--generic-method-make () () t #'identity)))))
542
543 (defun cl--generic-isnot-nnm-p (cnm)
544 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
545 ;; ¡Big Gross Ugly Hack!
546 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
547 ;; it, and some packages use it, so we need to support it.
548 (catch 'found
549 (cl-assert (function-equal cnm cl--generic-cnm-sample))
550 (if (byte-code-function-p cnm)
551 (let ((cnm-constants (aref cnm 2))
552 (sample-constants (aref cl--generic-cnm-sample 2)))
553 (dotimes (i (length sample-constants))
554 (when (function-equal (aref sample-constants i)
555 cl--generic-nnm-sample)
556 (throw 'found
557 (not (function-equal (aref cnm-constants i)
558 cl--generic-nnm-sample))))))
559 (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
560 (let ((cnm-env (cadr cnm)))
561 (dolist (vb (cadr cl--generic-cnm-sample))
562 (when (function-equal (cdr vb) cl--generic-nnm-sample)
563 (throw 'found
564 (not (function-equal (cdar cnm-env)
565 cl--generic-nnm-sample))))
566 (setq cnm-env (cdr cnm-env)))))
567 (error "Haven't found no-next-method-sample in cnm-sample")))
568
569 (defun cl--generic-cache-miss (generic dispatch-arg dispatches-left tags)
570 (let ((types (apply #'append (mapcar cl-generic-tag-types-function tags)))
571 (methods '()))
572 (dolist (method (cl--generic-method-table generic))
573 (let* ((specializer (or (nth dispatch-arg
574 (cl--generic-method-specializers method))
575 t))
576 (m (member specializer types)))
577 (when m
578 (push (cons (length m) method) methods))))
579 ;; Sort the methods, most specific first.
580 ;; It would be tempting to sort them once and for all in the method-table
581 ;; rather than here, but the order might depend on the actual argument
582 ;; (e.g. for multiple inheritance with defclass).
583 (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
584 (cl--generic-make-function (cl--generic-make (cl--generic-name generic)
585 dispatches-left methods))))
586
587 ;;; Define some pre-defined generic functions, used internally.
588
589 (define-error 'cl-no-method "No method for %S")
590 (define-error 'cl-no-next-method "No next method for %S" 'cl-no-method)
591 (define-error 'cl-no-primary-method "No primary method for %S" 'cl-no-method)
592 (define-error 'cl-no-applicable-method "No applicable method for %S"
593 'cl-no-method)
594
595 (cl-defgeneric cl-no-next-method (generic method &rest args)
596 "Function called when `cl-call-next-method' finds no next method.")
597 (cl-defmethod cl-no-next-method (generic method &rest args)
598 (signal 'cl-no-next-method `(,generic ,method ,@args)))
599
600 (cl-defgeneric cl-no-applicable-method (generic &rest args)
601 "Function called when a method call finds no applicable method.")
602 (cl-defmethod cl-no-applicable-method (generic &rest args)
603 (signal 'cl-no-applicable-method `(,generic ,@args)))
604
605 (cl-defgeneric cl-no-primary-method (generic &rest args)
606 "Function called when a method call finds no primary method.")
607 (cl-defmethod cl-no-primary-method (generic &rest args)
608 (signal 'cl-no-primary-method `(,generic ,@args)))
609
610 (defun cl-call-next-method (&rest _args)
611 "Function to call the next applicable method.
612 Can only be used from within the lexical body of a primary or around method."
613 (error "cl-call-next-method only allowed inside primary and around methods"))
614
615 (defun cl-next-method-p ()
616 "Return non-nil if there is a next method.
617 Can only be used from within the lexical body of a primary or around method."
618 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
619 (error "cl-next-method-p only allowed inside primary and around methods"))
620
621 ;;;###autoload
622 (defun cl-find-method (generic qualifiers specializers)
623 (car (cl--generic-member-method
624 specializers qualifiers
625 (cl--generic-method-table (cl--generic generic)))))
626
627 (defalias 'cl-method-qualifiers 'cl--generic-method-qualifiers)
628
629 ;;; Add support for describe-function
630
631 (defun cl--generic-search-method (met-name)
632 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
633 (regexp-quote (format "%s" (car met-name)))
634 "\\_>")))
635 (or
636 (re-search-forward
637 (concat base-re "[^&\"\n]*"
638 (mapconcat (lambda (specializer)
639 (regexp-quote
640 (format "%S" (if (consp specializer)
641 (nth 1 specializer) specializer))))
642 (remq t (cdr met-name))
643 "[ \t\n]*)[^&\"\n]*"))
644 nil t)
645 (re-search-forward base-re nil t))))
646
647
648 (with-eval-after-load 'find-func
649 (defvar find-function-regexp-alist)
650 (add-to-list 'find-function-regexp-alist
651 `(cl-defmethod . ,#'cl--generic-search-method)))
652
653 (defun cl--generic-method-info (method)
654 (let* ((specializers (cl--generic-method-specializers method))
655 (qualifiers (cl--generic-method-qualifiers method))
656 (uses-cnm (cl--generic-method-uses-cnm method))
657 (function (cl--generic-method-function method))
658 (args (help-function-arglist function 'names))
659 (docstring (documentation function))
660 (qual-string
661 (if (null qualifiers) ""
662 (cl-assert (consp qualifiers))
663 (let ((s (prin1-to-string qualifiers)))
664 (concat (substring s 1 -1) " "))))
665 (doconly (if docstring
666 (let ((split (help-split-fundoc docstring nil)))
667 (if split (cdr split) docstring))))
668 (combined-args ()))
669 (if uses-cnm (setq args (cdr args)))
670 (dolist (specializer specializers)
671 (let ((arg (if (eq '&rest (car args))
672 (intern (format "arg%d" (length combined-args)))
673 (pop args))))
674 (push (if (eq specializer t) arg (list arg specializer))
675 combined-args)))
676 (setq combined-args (append (nreverse combined-args) args))
677 (list qual-string combined-args doconly)))
678
679 (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
680 (defun cl--generic-describe (function)
681 (let ((generic (if (symbolp function) (cl--generic function))))
682 (when generic
683 (require 'help-mode) ;Needed for `help-function-def' button!
684 (save-excursion
685 (insert "\n\nThis is a generic function.\n\n")
686 (insert (propertize "Implementations:\n\n" 'face 'bold))
687 ;; Loop over fanciful generics
688 (dolist (method (cl--generic-method-table generic))
689 (let* ((info (cl--generic-method-info method)))
690 ;; FIXME: Add hyperlinks for the types as well.
691 (insert (format "%s%S" (nth 0 info) (nth 1 info)))
692 (let* ((met-name (cons function
693 (cl--generic-method-specializers method)))
694 (file (find-lisp-object-file-name met-name 'cl-defmethod)))
695 (when file
696 (insert " in `")
697 (help-insert-xref-button (help-fns-short-filename file)
698 'help-function-def met-name file
699 'cl-defmethod)
700 (insert "'.\n")))
701 (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
702
703 ;;; Support for (eql <val>) specializers.
704
705 (defvar cl--generic-eql-used (make-hash-table :test #'eql))
706
707 (add-function :before-until cl-generic-tagcode-function
708 #'cl--generic-eql-tagcode)
709 (defun cl--generic-eql-tagcode (type name)
710 (when (eq (car-safe type) 'eql)
711 (puthash (cadr type) type cl--generic-eql-used)
712 `(100 . (gethash ,name cl--generic-eql-used))))
713
714 (add-function :before-until cl-generic-tag-types-function
715 #'cl--generic-eql-tag-types)
716 (defun cl--generic-eql-tag-types (tag)
717 (if (eq (car-safe tag) 'eql) (list tag)))
718
719 ;;; Support for cl-defstructs specializers.
720
721 (add-function :before-until cl-generic-tagcode-function
722 #'cl--generic-struct-tagcode)
723
724 (defun cl--generic-struct-tag (name)
725 `(and (vectorp ,name)
726 (> (length ,name) 0)
727 (let ((tag (aref ,name 0)))
728 (if (eq (symbol-function tag) :quick-object-witness-check)
729 tag))))
730
731 (defun cl--generic-struct-tagcode (type name)
732 (and (symbolp type)
733 (get type 'cl-struct-type)
734 (or (null (car (get type 'cl-struct-type)))
735 (error "Can't dispatch on cl-struct %S: type is %S"
736 type (car (get type 'cl-struct-type))))
737 (or (equal '(cl-tag-slot) (car (get type 'cl-struct-slots)))
738 (error "Can't dispatch on cl-struct %S: no tag in slot 0"
739 type))
740 ;; It's tempting to use (and (vectorp ,name) (aref ,name 0))
741 ;; but that would suffer from some problems:
742 ;; - the vector may have size 0.
743 ;; - when called on an actual vector (rather than an object), we'd
744 ;; end up returning an arbitrary value, possibly colliding with
745 ;; other tagcode's values.
746 ;; - it can also result in returning all kinds of irrelevant
747 ;; values which would end up filling up the method-cache with
748 ;; lots of irrelevant/redundant entries.
749 ;; FIXME: We could speed this up by introducing a dedicated
750 ;; vector type at the C level, so we could do something like
751 ;; (and (vector-objectp ,name) (aref ,name 0))
752 `(50 . ,(cl--generic-struct-tag name))))
753
754 (add-function :before-until cl-generic-tag-types-function
755 #'cl--generic-struct-tag-types)
756 (defun cl--generic-struct-tag-types (tag)
757 ;; FIXME: cl-defstruct doesn't make it easy for us.
758 (and (symbolp tag)
759 ;; A method call shouldn't itself mess with the match-data.
760 (string-match-p "\\`cl-struct-\\(.*\\)" (symbol-name tag))
761 (let ((types (list (intern (substring (symbol-name tag) 10)))))
762 (while (get (car types) 'cl-struct-include)
763 (push (get (car types) 'cl-struct-include) types))
764 (push 'cl-structure-object types) ;The "parent type" of all cl-structs.
765 (nreverse types))))
766
767 ;;; Dispatch on "system types".
768
769 (defconst cl--generic-typeof-types
770 ;; Hand made from the source code of `type-of'.
771 '((integer number) (symbol) (string array sequence) (cons list sequence)
772 ;; Markers aren't `numberp', yet they are accepted wherever integers are
773 ;; accepted, pretty much.
774 (marker) (overlay) (float number) (window-configuration)
775 (process) (window) (subr) (compiled-function) (buffer)
776 (char-table array sequence)
777 (bool-vector array sequence)
778 (frame) (hash-table) (font-spec) (font-entity) (font-object)
779 (vector array sequence)
780 ;; Plus, hand made:
781 (null symbol list sequence)
782 (list sequence)
783 (array sequence)
784 (sequence)
785 (number)))
786
787 (add-function :before-until cl-generic-tagcode-function
788 #'cl--generic-typeof-tagcode)
789 (defun cl--generic-typeof-tagcode (type name)
790 ;; FIXME: Add support for other types accepted by `cl-typep' such
791 ;; as `character', `atom', `face', `function', ...
792 (and (assq type cl--generic-typeof-types)
793 (progn
794 (if (memq type '(vector array sequence))
795 (message "`%S' also matches CL structs and EIEIO classes" type))
796 ;; FIXME: We could also change `type-of' to return `null' for nil.
797 `(10 . (if ,name (type-of ,name) 'null)))))
798
799 (add-function :before-until cl-generic-tag-types-function
800 #'cl--generic-typeof-types)
801 (defun cl--generic-typeof-types (tag)
802 (and (symbolp tag)
803 (assq tag cl--generic-typeof-types)))
804
805 ;;; Just for kicks: dispatch on major-mode
806 ;;
807 ;; Here's how you'd use it:
808 ;; (cl-defmethod foo ((x (major-mode text-mode)) y z) ...)
809 ;; And then
810 ;; (foo 'major-mode toto titi)
811 ;;
812 ;; FIXME: Better would be to do that via dispatch on an "implicit argument".
813 ;; E.g. (cl-defmethod foo (y z &context (major-mode text-mode)) ...)
814
815 ;; (defvar cl--generic-major-modes (make-hash-table :test #'eq))
816 ;;
817 ;; (add-function :before-until cl-generic-tagcode-function
818 ;; #'cl--generic-major-mode-tagcode)
819 ;; (defun cl--generic-major-mode-tagcode (type name)
820 ;; (if (eq 'major-mode (car-safe type))
821 ;; `(50 . (if (eq ,name 'major-mode)
822 ;; (cl--generic-with-memoization
823 ;; (gethash major-mode cl--generic-major-modes)
824 ;; `(cl--generic-major-mode . ,major-mode))))))
825 ;;
826 ;; (add-function :before-until cl-generic-tag-types-function
827 ;; #'cl--generic-major-mode-types)
828 ;; (defun cl--generic-major-mode-types (tag)
829 ;; (when (eq (car-safe tag) 'cl--generic-major-mode)
830 ;; (if (eq tag 'fundamental-mode) '(fundamental-mode t)
831 ;; (let ((types `((major-mode ,(cdr tag)))))
832 ;; (while (get (car types) 'derived-mode-parent)
833 ;; (push (list 'major-mode (get (car types) 'derived-mode-parent))
834 ;; types))
835 ;; (unless (eq 'fundamental-mode (car types))
836 ;; (push '(major-mode fundamental-mode) types))
837 ;; (nreverse types)))))
838
839 ;; Local variables:
840 ;; generated-autoload-file: "cl-loaddefs.el"
841 ;; End:
842
843 (provide 'cl-generic)
844 ;;; cl-generic.el ends here