]> 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 (doc-string (if (and (stringp (car-safe body)) (cdr body))
247 (pop body)))
248 (mandatory t))
249 (dolist (arg args)
250 (push (pcase arg
251 ((or '&optional '&rest '&key) (setq mandatory nil) arg)
252 ((and `(,name . ,type) (guard mandatory))
253 (push (cons name (car type)) specializers)
254 name)
255 (_ arg))
256 plain-args))
257 (setq plain-args (nreverse plain-args))
258 (let ((fun `(cl-function (lambda ,plain-args
259 ,@(if doc-string (list doc-string))
260 ,@body)))
261 (macroenv (cons `(cl-generic-current-method-specializers
262 . ,(lambda () specializers))
263 macroexpand-all-environment)))
264 (require 'cl-lib) ;Needed to expand `cl-flet' and `cl-function'.
265 ;; First macroexpand away the cl-function stuff (e.g. &key and
266 ;; destructuring args, `declare' and whatnot).
267 (pcase (macroexpand fun macroenv)
268 (`#'(lambda ,args . ,body)
269 (let* ((doc-string (and doc-string (stringp (car body)) (cdr body)
270 (pop body)))
271 (cnm (make-symbol "cl--cnm"))
272 (nmp (make-symbol "cl--nmp"))
273 (nbody (macroexpand-all
274 `(cl-flet ((cl-call-next-method ,cnm)
275 (cl-next-method-p ,nmp))
276 ,@body)
277 macroenv))
278 ;; FIXME: Rather than `grep' after the fact, the
279 ;; macroexpansion should directly set some flag when cnm
280 ;; is used.
281 ;; FIXME: Also, optimize the case where call-next-method is
282 ;; only called with explicit arguments.
283 (uses-cnm (cl--generic-fgrep (list cnm nmp) nbody)))
284 (cons (not (not uses-cnm))
285 `#'(lambda (,@(if uses-cnm (list cnm)) ,@args)
286 ,@(if doc-string (list doc-string))
287 ,(if (not (memq nmp uses-cnm))
288 nbody
289 `(let ((,nmp (lambda ()
290 (cl--generic-isnot-nnm-p ,cnm))))
291 ,nbody))))))
292 (f (error "Unexpected macroexpansion result: %S" f)))))))
293
294
295 ;;;###autoload
296 (defmacro cl-defmethod (name args &rest body)
297 "Define a new method for generic function NAME.
298 I.e. it defines the implementation of NAME to use for invocations where the
299 value of the dispatch argument matches the specified TYPE.
300 The dispatch argument has to be one of the mandatory arguments, and
301 all methods of NAME have to use the same argument for dispatch.
302 The dispatch argument and TYPE are specified in ARGS where the corresponding
303 formal argument appears as (VAR TYPE) rather than just VAR.
304
305 The optional second argument QUALIFIER is a specifier that
306 modifies how the method is combined with other methods, including:
307 :before - Method will be called before the primary
308 :after - Method will be called after the primary
309 :around - Method will be called around everything else
310 The absence of QUALIFIER means this is a \"primary\" method.
311
312 Other than a type, TYPE can also be of the form `(eql VAL)' in
313 which case this method will be invoked when the argument is `eql' to VAL.
314
315 \(fn NAME [QUALIFIER] ARGS &rest [DOCSTRING] BODY)"
316 (declare (doc-string 3) (indent 2)
317 (debug
318 (&define ; this means we are defining something
319 [&or name ("setf" :name setf name)]
320 ;; ^^ This is the methods symbol
321 [ &optional keywordp ] ; this is key :before etc
322 list ; arguments
323 [ &optional stringp ] ; documentation string
324 def-body))) ; part to be debugged
325 (let ((qualifiers nil)
326 (setfizer (if (eq 'setf (car-safe name))
327 ;; Call it before we call cl--generic-lambda.
328 (cl--generic-setf-rewrite (cadr name)))))
329 (while (not (listp args))
330 (push args qualifiers)
331 (setq args (pop body)))
332 (pcase-let* ((`(,uses-cnm . ,fun) (cl--generic-lambda args body)))
333 `(progn
334 ,(when setfizer
335 (setq name (car setfizer))
336 (cdr setfizer))
337 ,(and (get name 'byte-obsolete-info)
338 (or (not (fboundp 'byte-compile-warning-enabled-p))
339 (byte-compile-warning-enabled-p 'obsolete))
340 (let* ((obsolete (get name 'byte-obsolete-info)))
341 (macroexp--warn-and-return
342 (macroexp--obsolete-warning name obsolete "generic function")
343 nil)))
344 ;; You could argue that `defmethod' modifies rather than defines the
345 ;; function, so warnings like "not known to be defined" are fair game.
346 ;; But in practice, it's common to use `cl-defmethod'
347 ;; without a previous `cl-defgeneric'.
348 (declare-function ,name "")
349 (cl-generic-define-method ',name ',qualifiers ',args
350 ,uses-cnm ,fun)))))
351
352 (defun cl--generic-member-method (specializers qualifiers methods)
353 (while
354 (and methods
355 (let ((m (car methods)))
356 (not (and (equal (cl--generic-method-specializers m) specializers)
357 (equal (cl--generic-method-qualifiers m) qualifiers)))))
358 (setq methods (cdr methods))
359 methods))
360
361 ;;;###autoload
362 (defun cl-generic-define-method (name qualifiers args uses-cnm function)
363 (let* ((generic (cl-generic-ensure-function name))
364 (mandatory (cl--generic-mandatory-args args))
365 (specializers
366 (mapcar (lambda (arg) (if (consp arg) (cadr arg) t)) mandatory))
367 (method (cl--generic-method-make
368 specializers qualifiers uses-cnm function))
369 (mt (cl--generic-method-table generic))
370 (me (cl--generic-member-method specializers qualifiers mt))
371 (dispatches (cl--generic-dispatches generic))
372 (i 0))
373 (dolist (specializer specializers)
374 (let* ((tagcode (funcall cl-generic-tagcode-function specializer 'arg))
375 (x (assq i dispatches)))
376 (unless x
377 (setq x (list i (funcall cl-generic-tagcode-function t 'arg)))
378 (setf (cl--generic-dispatches generic)
379 (setq dispatches (cons x dispatches))))
380 (unless (member tagcode (cdr x))
381 (setf (cdr x)
382 (nreverse (sort (cons tagcode (cdr x))
383 #'car-less-than-car))))
384 (setq i (1+ i))))
385 (if me (setcar me method)
386 (setf (cl--generic-method-table generic) (cons method mt)))
387 (cl-pushnew `(cl-defmethod . (,(cl--generic-name generic) . ,specializers))
388 current-load-list :test #'equal)
389 (let ((gfun (cl--generic-make-function generic))
390 ;; Prevent `defalias' from recording this as the definition site of
391 ;; the generic function.
392 current-load-list)
393 ;; For aliases, cl--generic-name gives us the actual name.
394 (defalias (cl--generic-name generic) gfun))))
395
396 (defmacro cl--generic-with-memoization (place &rest code)
397 (declare (indent 1) (debug t))
398 (gv-letplace (getter setter) place
399 `(or ,getter
400 ,(macroexp-let2 nil val (macroexp-progn code)
401 `(progn
402 ,(funcall setter val)
403 ,val)))))
404
405 (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
406
407 (defun cl--generic-get-dispatcher (tagcodes dispatch-arg)
408 (cl--generic-with-memoization
409 (gethash (cons dispatch-arg tagcodes) cl--generic-dispatchers)
410 (let ((lexical-binding t)
411 (tag-exp `(or ,@(mapcar #'cdr
412 ;; Minor optimization: since this tag-exp is
413 ;; only used to lookup the method-cache, it
414 ;; doesn't matter if the default value is some
415 ;; constant or nil.
416 (if (macroexp-const-p (car (last tagcodes)))
417 (butlast tagcodes)
418 tagcodes))))
419 (extraargs ()))
420 (dotimes (_ dispatch-arg)
421 (push (make-symbol "arg") extraargs))
422 (byte-compile
423 `(lambda (generic dispatches-left)
424 (let ((method-cache (make-hash-table :test #'eql)))
425 (lambda (,@extraargs arg &rest args)
426 (apply (cl--generic-with-memoization
427 (gethash ,tag-exp method-cache)
428 (cl--generic-cache-miss
429 generic ',dispatch-arg dispatches-left
430 (list ,@(mapcar #'cdr tagcodes))))
431 ,@extraargs arg args))))))))
432
433 (defun cl--generic-make-function (generic)
434 (let* ((dispatches (cl--generic-dispatches generic))
435 (dispatch
436 (progn
437 (while (and dispatches
438 (member (cdar dispatches)
439 '(nil ((0 . 'cl--generic-type)))))
440 (setq dispatches (cdr dispatches)))
441 (pop dispatches))))
442 (if (null dispatch)
443 (cl--generic-build-combined-method
444 (cl--generic-name generic)
445 (cl--generic-method-table generic))
446 (let ((dispatcher (cl--generic-get-dispatcher
447 (cdr dispatch) (car dispatch))))
448 (funcall dispatcher generic dispatches)))))
449
450 (defvar cl-generic-method-combination-function
451 #'cl--generic-standard-method-combination
452 "Function to build the effective method.
453 Called with 2 arguments: NAME and METHOD-ALIST.
454 It should return an effective method, i.e. a function that expects the same
455 arguments as the methods, and calls those methods in some appropriate order.
456 NAME is the name (a symbol) of the corresponding generic function.
457 METHOD-ALIST is a list of elements (QUALIFIERS . METHODS) where
458 QUALIFIERS is a list of qualifiers, and METHODS is a list of the selected
459 methods for that qualifier list.
460 The METHODS lists are sorted from most generic first to most specific last.
461 The function can use `cl-generic-call-method' to create functions that call those
462 methods.")
463
464 (defvar cl--generic-combined-method-memoization
465 (make-hash-table :test #'equal :weakness 'value)
466 "Table storing previously built combined-methods.
467 This is particularly useful when many different tags select the same set
468 of methods, since this table then allows us to share a single combined-method
469 for all those different tags in the method-cache.")
470
471 (defun cl--generic-build-combined-method (generic-name methods)
472 (cl--generic-with-memoization
473 (gethash (cons generic-name methods)
474 cl--generic-combined-method-memoization)
475 (let ((mets-by-qual ()))
476 (dolist (method methods)
477 (let* ((qualifiers (cl--generic-method-qualifiers method))
478 (x (assoc qualifiers mets-by-qual)))
479 ;; FIXME: sadly, alist-get only uses `assq' and we need `assoc'.
480 ;;(push (cdr qm) (alist-get qualifiers mets-by-qual)))
481 (if x
482 (push method (cdr x))
483 (push (list qualifiers method) mets-by-qual))))
484 (funcall cl-generic-method-combination-function
485 generic-name mets-by-qual))))
486
487 (defun cl--generic-no-next-method-function (generic method)
488 (lambda (&rest args)
489 (apply #'cl-no-next-method generic method args)))
490
491 (defun cl-generic-call-method (generic-name method &optional fun)
492 "Return a function that calls METHOD.
493 FUN is the function that should be called when METHOD calls
494 `call-next-method'."
495 (if (not (cl--generic-method-uses-cnm method))
496 (cl--generic-method-function method)
497 (let ((met-fun (cl--generic-method-function method))
498 (next (or fun (cl--generic-no-next-method-function
499 generic-name method))))
500 (lambda (&rest args)
501 (apply met-fun
502 ;; FIXME: This sucks: passing just `next' would
503 ;; be a lot more efficient than the lambda+apply
504 ;; quasi-η, but we need this to implement the
505 ;; "if call-next-method is called with no
506 ;; arguments, then use the previous arguments".
507 (lambda (&rest cnm-args)
508 (apply next (or cnm-args args)))
509 args)))))
510
511 (defun cl--generic-standard-method-combination (generic-name mets-by-qual)
512 (dolist (x mets-by-qual)
513 (unless (member (car x) '(() (:after) (:before) (:around)))
514 (error "Unsupported qualifiers in function %S: %S" generic-name (car x))))
515 (cond
516 ((null mets-by-qual)
517 (lambda (&rest args)
518 (apply #'cl-no-applicable-method generic-name args)))
519 ((null (alist-get nil mets-by-qual))
520 (lambda (&rest args)
521 (apply #'cl-no-primary-method generic-name args)))
522 (t
523 (let* ((fun nil)
524 (ab-call (lambda (m) (cl-generic-call-method generic-name m)))
525 (before
526 (mapcar ab-call (reverse (cdr (assoc '(:before) mets-by-qual)))))
527 (after (mapcar ab-call (cdr (assoc '(:after) mets-by-qual)))))
528 (dolist (method (cdr (assoc nil mets-by-qual)))
529 (setq fun (cl-generic-call-method generic-name method fun)))
530 (when (or after before)
531 (let ((next fun))
532 (setq fun (lambda (&rest args)
533 (dolist (bf before)
534 (apply bf args))
535 (prog1
536 (apply next args)
537 (dolist (af after)
538 (apply af args)))))))
539 (dolist (method (cdr (assoc '(:around) mets-by-qual)))
540 (setq fun (cl-generic-call-method generic-name method fun)))
541 fun))))
542
543 (defconst cl--generic-nnm-sample (cl--generic-no-next-method-function t t))
544 (defconst cl--generic-cnm-sample
545 (funcall (cl--generic-build-combined-method
546 nil (list (cl--generic-method-make () () t #'identity)))))
547
548 (defun cl--generic-isnot-nnm-p (cnm)
549 "Return non-nil if CNM is the function that calls `cl-no-next-method'."
550 ;; ¡Big Gross Ugly Hack!
551 ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
552 ;; it, and some packages use it, so we need to support it.
553 (catch 'found
554 (cl-assert (function-equal cnm cl--generic-cnm-sample))
555 (if (byte-code-function-p cnm)
556 (let ((cnm-constants (aref cnm 2))
557 (sample-constants (aref cl--generic-cnm-sample 2)))
558 (dotimes (i (length sample-constants))
559 (when (function-equal (aref sample-constants i)
560 cl--generic-nnm-sample)
561 (throw 'found
562 (not (function-equal (aref cnm-constants i)
563 cl--generic-nnm-sample))))))
564 (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
565 (let ((cnm-env (cadr cnm)))
566 (dolist (vb (cadr cl--generic-cnm-sample))
567 (when (function-equal (cdr vb) cl--generic-nnm-sample)
568 (throw 'found
569 (not (function-equal (cdar cnm-env)
570 cl--generic-nnm-sample))))
571 (setq cnm-env (cdr cnm-env)))))
572 (error "Haven't found no-next-method-sample in cnm-sample")))
573
574 (defun cl--generic-cache-miss (generic dispatch-arg dispatches-left tags)
575 (let ((types (apply #'append (mapcar cl-generic-tag-types-function tags)))
576 (methods '()))
577 (dolist (method (cl--generic-method-table generic))
578 (let* ((specializer (or (nth dispatch-arg
579 (cl--generic-method-specializers method))
580 t))
581 (m (member specializer types)))
582 (when m
583 (push (cons (length m) method) methods))))
584 ;; Sort the methods, most specific first.
585 ;; It would be tempting to sort them once and for all in the method-table
586 ;; rather than here, but the order might depend on the actual argument
587 ;; (e.g. for multiple inheritance with defclass).
588 (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
589 (cl--generic-make-function (cl--generic-make (cl--generic-name generic)
590 dispatches-left methods))))
591
592 ;;; Define some pre-defined generic functions, used internally.
593
594 (define-error 'cl-no-method "No method for %S")
595 (define-error 'cl-no-next-method "No next method for %S" 'cl-no-method)
596 (define-error 'cl-no-primary-method "No primary method for %S" 'cl-no-method)
597 (define-error 'cl-no-applicable-method "No applicable method for %S"
598 'cl-no-method)
599
600 (cl-defgeneric cl-no-next-method (generic method &rest args)
601 "Function called when `cl-call-next-method' finds no next method.")
602 (cl-defmethod cl-no-next-method (generic method &rest args)
603 (signal 'cl-no-next-method `(,generic ,method ,@args)))
604
605 (cl-defgeneric cl-no-applicable-method (generic &rest args)
606 "Function called when a method call finds no applicable method.")
607 (cl-defmethod cl-no-applicable-method (generic &rest args)
608 (signal 'cl-no-applicable-method `(,generic ,@args)))
609
610 (cl-defgeneric cl-no-primary-method (generic &rest args)
611 "Function called when a method call finds no primary method.")
612 (cl-defmethod cl-no-primary-method (generic &rest args)
613 (signal 'cl-no-primary-method `(,generic ,@args)))
614
615 (defun cl-call-next-method (&rest _args)
616 "Function to call the next applicable method.
617 Can only be used from within the lexical body of a primary or around method."
618 (error "cl-call-next-method only allowed inside primary and around methods"))
619
620 (defun cl-next-method-p ()
621 "Return non-nil if there is a next method.
622 Can only be used from within the lexical body of a primary or around method."
623 (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
624 (error "cl-next-method-p only allowed inside primary and around methods"))
625
626 ;;;###autoload
627 (defun cl-find-method (generic qualifiers specializers)
628 (car (cl--generic-member-method
629 specializers qualifiers
630 (cl--generic-method-table (cl--generic generic)))))
631
632 (defalias 'cl-method-qualifiers 'cl--generic-method-qualifiers)
633
634 ;;; Add support for describe-function
635
636 (defun cl--generic-search-method (met-name)
637 (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
638 (regexp-quote (format "%s\\_>" (car met-name))))))
639 (or
640 (re-search-forward
641 (concat base-re "[^&\"\n]*"
642 (mapconcat (lambda (specializer)
643 (regexp-quote
644 (format "%S" (if (consp specializer)
645 (nth 1 specializer) specializer))))
646 (remq t (cdr met-name))
647 "[ \t\n]*)[^&\"\n]*"))
648 nil t)
649 (re-search-forward base-re nil t))))
650
651
652 (with-eval-after-load 'find-func
653 (defvar find-function-regexp-alist)
654 (add-to-list 'find-function-regexp-alist
655 `(cl-defmethod . ,#'cl--generic-search-method)))
656
657 (defun cl--generic-method-info (method)
658 (let* ((specializers (cl--generic-method-specializers method))
659 (qualifiers (cl--generic-method-qualifiers method))
660 (uses-cnm (cl--generic-method-uses-cnm method))
661 (function (cl--generic-method-function method))
662 (args (help-function-arglist function 'names))
663 (docstring (documentation function))
664 (qual-string
665 (if (null qualifiers) ""
666 (cl-assert (consp qualifiers))
667 (let ((s (prin1-to-string qualifiers)))
668 (concat (substring s 1 -1) " "))))
669 (doconly (if docstring
670 (let ((split (help-split-fundoc docstring nil)))
671 (if split (cdr split) docstring))))
672 (combined-args ()))
673 (if uses-cnm (setq args (cdr args)))
674 (dolist (specializer specializers)
675 (let ((arg (if (eq '&rest (car args))
676 (intern (format "arg%d" (length combined-args)))
677 (pop args))))
678 (push (if (eq specializer t) arg (list arg specializer))
679 combined-args)))
680 (setq combined-args (append (nreverse combined-args) args))
681 (list qual-string combined-args doconly)))
682
683 (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
684 (defun cl--generic-describe (function)
685 (let ((generic (if (symbolp function) (cl--generic function))))
686 (when generic
687 (require 'help-mode) ;Needed for `help-function-def' button!
688 (save-excursion
689 (insert "\n\nThis is a generic function.\n\n")
690 (insert (propertize "Implementations:\n\n" 'face 'bold))
691 ;; Loop over fanciful generics
692 (dolist (method (cl--generic-method-table generic))
693 (let* ((info (cl--generic-method-info method)))
694 ;; FIXME: Add hyperlinks for the types as well.
695 (insert (format "%s%S" (nth 0 info) (nth 1 info)))
696 (let* ((met-name (cons function
697 (cl--generic-method-specializers method)))
698 (file (find-lisp-object-file-name met-name 'cl-defmethod)))
699 (when file
700 (insert " in `")
701 (help-insert-xref-button (help-fns-short-filename file)
702 'help-function-def met-name file
703 'cl-defmethod)
704 (insert "'.\n")))
705 (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
706
707 ;;; Support for (eql <val>) specializers.
708
709 (defvar cl--generic-eql-used (make-hash-table :test #'eql))
710
711 (add-function :before-until cl-generic-tagcode-function
712 #'cl--generic-eql-tagcode)
713 (defun cl--generic-eql-tagcode (type name)
714 (when (eq (car-safe type) 'eql)
715 (puthash (cadr type) type cl--generic-eql-used)
716 `(100 . (gethash ,name cl--generic-eql-used))))
717
718 (add-function :before-until cl-generic-tag-types-function
719 #'cl--generic-eql-tag-types)
720 (defun cl--generic-eql-tag-types (tag)
721 (if (eq (car-safe tag) 'eql) (list tag)))
722
723 ;;; Support for cl-defstructs specializers.
724
725 (add-function :before-until cl-generic-tagcode-function
726 #'cl--generic-struct-tagcode)
727 (defun cl--generic-struct-tagcode (type name)
728 (and (symbolp type)
729 (get type 'cl-struct-type)
730 (or (eq 'vector (car (get type 'cl-struct-type)))
731 (error "Can't dispatch on cl-struct %S: type is %S"
732 type (car (get type 'cl-struct-type))))
733 (or (equal '(cl-tag-slot) (car (get type 'cl-struct-slots)))
734 (error "Can't dispatch on cl-struct %S: no tag in slot 0"
735 type))
736 ;; We could/should check the vector has length >0,
737 ;; but really, mixing vectors and structs is a bad idea,
738 ;; so let's not waste time trying to handle the case
739 ;; of an empty vector.
740 ;; BEWARE: this returns a bogus tag for non-struct vectors.
741 `(50 . (and (vectorp ,name) (aref ,name 0)))))
742
743 (add-function :before-until cl-generic-tag-types-function
744 #'cl--generic-struct-tag-types)
745 (defun cl--generic-struct-tag-types (tag)
746 ;; FIXME: cl-defstruct doesn't make it easy for us.
747 (and (symbolp tag)
748 ;; A method call shouldn't itself mess with the match-data.
749 (string-match-p "\\`cl-struct-\\(.*\\)" (symbol-name tag))
750 (let ((types (list (intern (substring (symbol-name tag) 10)))))
751 (while (get (car types) 'cl-struct-include)
752 (push (get (car types) 'cl-struct-include) types))
753 (push 'cl-struct types) ;The "parent type" of all cl-structs.
754 (nreverse types))))
755
756 ;;; Dispatch on "system types".
757
758 (defconst cl--generic-typeof-types
759 ;; Hand made from the source code of `type-of'.
760 '((integer number) (symbol) (string array sequence) (cons list sequence)
761 ;; Markers aren't `numberp', yet they are accepted wherever integers are
762 ;; accepted, pretty much.
763 (marker) (overlay) (float number) (window-configuration)
764 (process) (window) (subr) (compiled-function) (buffer)
765 (char-table array sequence)
766 (bool-vector array sequence)
767 (frame) (hash-table) (font-spec) (font-entity) (font-object)
768 (vector array sequence)
769 ;; Plus, hand made:
770 (null symbol list sequence)
771 (list sequence)
772 (array sequence)
773 (sequence)
774 (number)))
775
776 (add-function :before-until cl-generic-tagcode-function
777 #'cl--generic-typeof-tagcode)
778 (defun cl--generic-typeof-tagcode (type name)
779 ;; FIXME: Add support for other types accepted by `cl-typep' such
780 ;; as `character', `atom', `face', `function', ...
781 (and (assq type cl--generic-typeof-types)
782 (progn
783 (if (memq type '(vector array sequence))
784 (message "`%S' also matches CL structs and EIEIO classes" type))
785 ;; FIXME: We could also change `type-of' to return `null' for nil.
786 `(10 . (if ,name (type-of ,name) 'null)))))
787
788 (add-function :before-until cl-generic-tag-types-function
789 #'cl--generic-typeof-types)
790 (defun cl--generic-typeof-types (tag)
791 (and (symbolp tag)
792 (assq tag cl--generic-typeof-types)))
793
794 ;;; Just for kicks: dispatch on major-mode
795 ;;
796 ;; Here's how you'd use it:
797 ;; (cl-defmethod foo ((x (major-mode text-mode)) y z) ...)
798 ;; And then
799 ;; (foo 'major-mode toto titi)
800 ;;
801 ;; FIXME: Better would be to do that via dispatch on an "implicit argument".
802 ;; E.g. (cl-defmethod foo (y z &context (major-mode text-mode)) ...)
803
804 ;; (defvar cl--generic-major-modes (make-hash-table :test #'eq))
805 ;;
806 ;; (add-function :before-until cl-generic-tagcode-function
807 ;; #'cl--generic-major-mode-tagcode)
808 ;; (defun cl--generic-major-mode-tagcode (type name)
809 ;; (if (eq 'major-mode (car-safe type))
810 ;; `(50 . (if (eq ,name 'major-mode)
811 ;; (cl--generic-with-memoization
812 ;; (gethash major-mode cl--generic-major-modes)
813 ;; `(cl--generic-major-mode . ,major-mode))))))
814 ;;
815 ;; (add-function :before-until cl-generic-tag-types-function
816 ;; #'cl--generic-major-mode-types)
817 ;; (defun cl--generic-major-mode-types (tag)
818 ;; (when (eq (car-safe tag) 'cl--generic-major-mode)
819 ;; (if (eq tag 'fundamental-mode) '(fundamental-mode t)
820 ;; (let ((types `((major-mode ,(cdr tag)))))
821 ;; (while (get (car types) 'derived-mode-parent)
822 ;; (push (list 'major-mode (get (car types) 'derived-mode-parent))
823 ;; types))
824 ;; (unless (eq 'fundamental-mode (car types))
825 ;; (push '(major-mode fundamental-mode) types))
826 ;; (nreverse types)))))
827
828 ;; Local variables:
829 ;; generated-autoload-file: "cl-loaddefs.el"
830 ;; End:
831
832 (provide 'cl-generic)
833 ;;; cl-generic.el ends here