cl-generic.el 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. ;;; cl-generic.el --- CLOS-style generic functions for Elisp -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2015-2017 Free Software Foundation, Inc.
  3. ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
  4. ;; Version: 1.0
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This implements the most of CLOS's multiple-dispatch generic functions.
  18. ;; To use it you need either (require 'cl-generic) or (require 'cl-lib).
  19. ;; The main entry points are: `cl-defgeneric' and `cl-defmethod'.
  20. ;; Missing elements:
  21. ;; - We don't support make-method, call-method, define-method-combination.
  22. ;; CLOS's define-method-combination is IMO overly complicated, and it suffers
  23. ;; from a significant problem: the method-combination code returns a sexp
  24. ;; that needs to be `eval'uated or compiled. IOW it requires run-time
  25. ;; code generation. Given how rarely method-combinations are used,
  26. ;; I just provided a cl-generic-combine-methods generic function, to which
  27. ;; people can add methods if they are really desperate for such functionality.
  28. ;; - In defgeneric we don't support the options:
  29. ;; declare, :method-combination, :generic-function-class, :method-class.
  30. ;; Added elements:
  31. ;; - We support aliases to generic functions.
  32. ;; - cl-generic-generalizers. This generic function lets you extend the kind
  33. ;; of thing on which to dispatch. There is support in this file for
  34. ;; dispatch on:
  35. ;; - (eql <val>)
  36. ;; - (head <val>) which checks that the arg is a cons with <val> as its head.
  37. ;; - plain old types
  38. ;; - type of CL structs
  39. ;; eieio-core adds dispatch on:
  40. ;; - class of eieio objects
  41. ;; - actual class argument, using the syntax (subclass <class>).
  42. ;; - cl-generic-combine-methods (i.s.o define-method-combination and
  43. ;; compute-effective-method).
  44. ;; - cl-generic-call-method (which replaces make-method and call-method).
  45. ;; - The standard method combination supports ":extra STRING" qualifiers
  46. ;; which simply allows adding more methods for the same
  47. ;; specializers&qualifiers.
  48. ;; - Methods can dispatch on the context. For that, a method needs to specify
  49. ;; context arguments, introduced by `&context' (which need to come right
  50. ;; after the mandatory arguments and before anything like
  51. ;; &optional/&rest/&key). Each context argument is given as (EXP SPECIALIZER)
  52. ;; which means that EXP is taken as an expression which computes some context
  53. ;; and this value is then used to dispatch.
  54. ;; E.g. (foo &context (major-mode (eql c-mode))) is an arglist specifying
  55. ;; that this method will only be applicable when `major-mode' has value
  56. ;; `c-mode'.
  57. ;; Efficiency considerations: overall, I've made an effort to make this fairly
  58. ;; efficient for the expected case (e.g. no constant redefinition of methods).
  59. ;; - Generic functions which do not dispatch on any argument are implemented
  60. ;; optimally (just as efficient as plain old functions).
  61. ;; - Generic functions which only dispatch on one argument are fairly efficient
  62. ;; (not a lot of room for improvement without changes to the byte-compiler,
  63. ;; I think).
  64. ;; - Multiple dispatch is implemented rather naively. There's an extra `apply'
  65. ;; function call for every dispatch; we don't optimize each dispatch
  66. ;; based on the set of candidate methods remaining; we don't optimize the
  67. ;; order in which we performs the dispatches either;
  68. ;; If/when this becomes a problem, we can try and optimize it.
  69. ;; - call-next-method could be made more efficient, but isn't too terrible.
  70. ;; TODO:
  71. ;;
  72. ;; - A generic "filter" generalizer (e.g. could be used to cleanly add methods
  73. ;; to cl-generic-combine-methods with a specializer that says it applies only
  74. ;; when some particular qualifier is used).
  75. ;;; Code:
  76. ;; The autoloads.el mechanism which adds package--builtin-versions
  77. ;; maintenance to loaddefs.el doesn't work for preloaded packages (such
  78. ;; as this one), so we have to do it by hand!
  79. (push (purecopy '(cl-generic 1 0)) package--builtin-versions)
  80. ;; Note: For generic functions that dispatch on several arguments (i.e. those
  81. ;; which use the multiple-dispatch feature), we always use the same "tagcodes"
  82. ;; and the same set of arguments on which to dispatch. This works, but is
  83. ;; often suboptimal since after one dispatch, the remaining dispatches can
  84. ;; usually be simplified, or even completely skipped.
  85. (eval-when-compile (require 'cl-lib))
  86. (eval-when-compile (require 'cl-macs)) ;For cl--find-class.
  87. (eval-when-compile (require 'pcase))
  88. (cl-defstruct (cl--generic-generalizer
  89. (:constructor nil)
  90. (:constructor cl-generic-make-generalizer
  91. (name priority tagcode-function specializers-function)))
  92. (name nil :type string)
  93. (priority nil :type integer)
  94. tagcode-function
  95. specializers-function)
  96. (defmacro cl-generic-define-generalizer
  97. (name priority tagcode-function specializers-function)
  98. "Define a new kind of generalizer.
  99. NAME is the name of the variable that will hold it.
  100. PRIORITY defines which generalizer takes precedence.
  101. The catch-all generalizer has priority 0.
  102. Then `eql' generalizer has priority 100.
  103. TAGCODE-FUNCTION takes as first argument a varname and should return
  104. a chunk of code that computes the tag of the value held in that variable.
  105. Further arguments are reserved for future use.
  106. SPECIALIZERS-FUNCTION takes as first argument a tag value TAG
  107. and should return a list of specializers that match TAG.
  108. Further arguments are reserved for future use."
  109. (declare (indent 1) (debug (symbolp body)))
  110. `(defconst ,name
  111. (cl-generic-make-generalizer
  112. ',name ,priority ,tagcode-function ,specializers-function)))
  113. (cl-generic-define-generalizer cl--generic-t-generalizer
  114. 0 (lambda (_name &rest _) nil) (lambda (_tag &rest _) '(t)))
  115. (cl-defstruct (cl--generic-method
  116. (:constructor nil)
  117. (:constructor cl--generic-make-method
  118. (specializers qualifiers uses-cnm function))
  119. (:predicate nil))
  120. (specializers nil :read-only t :type list)
  121. (qualifiers nil :read-only t :type (list-of atom))
  122. ;; USES-CNM is a boolean indicating if FUNCTION expects an extra argument
  123. ;; holding the next-method.
  124. (uses-cnm nil :read-only t :type boolean)
  125. (function nil :read-only t :type function))
  126. (cl-defstruct (cl--generic
  127. (:constructor nil)
  128. (:constructor cl--generic-make (name))
  129. (:predicate nil))
  130. (name nil :type symbol :read-only t) ;Pointer back to the symbol.
  131. ;; `dispatches' holds a list of (ARGNUM . TAGCODES) where ARGNUM is the index
  132. ;; of the corresponding argument and TAGCODES is a list of (PRIORITY . EXP)
  133. ;; where the EXPs are expressions (to be `or'd together) to compute the tag
  134. ;; on which to dispatch and PRIORITY is the priority of each expression to
  135. ;; decide in which order to sort them.
  136. ;; The most important dispatch is last in the list (and the least is first).
  137. (dispatches nil :type (list-of (cons natnum (list-of generalizers))))
  138. (method-table nil :type (list-of cl--generic-method))
  139. (options nil :type list))
  140. (defun cl-generic-function-options (generic)
  141. "Return the options of the generic function GENERIC."
  142. (cl--generic-options generic))
  143. (defmacro cl--generic (name)
  144. `(get ,name 'cl--generic))
  145. (defun cl-generic-p (f)
  146. "Return non-nil if F is a generic function."
  147. (and (symbolp f) (cl--generic f)))
  148. (defun cl-generic-ensure-function (name &optional noerror)
  149. (let (generic
  150. (origname name))
  151. (while (and (null (setq generic (cl--generic name)))
  152. (fboundp name)
  153. (null noerror)
  154. (symbolp (symbol-function name)))
  155. (setq name (symbol-function name)))
  156. (unless (or (not (fboundp name))
  157. (autoloadp (symbol-function name))
  158. (and (functionp name) generic)
  159. noerror)
  160. (error "%s is already defined as something else than a generic function"
  161. origname))
  162. (if generic
  163. (cl-assert (eq name (cl--generic-name generic)))
  164. (setf (cl--generic name) (setq generic (cl--generic-make name))))
  165. generic))
  166. ;;;###autoload
  167. (defmacro cl-defgeneric (name args &rest options-and-methods)
  168. "Create a generic function NAME.
  169. DOC-STRING is the base documentation for this class. A generic
  170. function has no body, as its purpose is to decide which method body
  171. is appropriate to use. Specific methods are defined with `cl-defmethod'.
  172. With this implementation the ARGS are currently ignored.
  173. OPTIONS-AND-METHODS currently understands:
  174. - (:documentation DOCSTRING)
  175. - (declare DECLARATIONS)
  176. - (:argument-precedence-order &rest ARGS)
  177. - (:method [QUALIFIERS...] ARGS &rest BODY)
  178. DEFAULT-BODY, if present, is used as the body of a default method.
  179. \(fn NAME ARGS [DOC-STRING] [OPTIONS-AND-METHODS...] &rest DEFAULT-BODY)"
  180. (declare (indent 2) (doc-string 3))
  181. (let* ((doc (if (stringp (car-safe options-and-methods))
  182. (pop options-and-methods)))
  183. (declarations nil)
  184. (methods ())
  185. (options ())
  186. next-head)
  187. (while (progn (setq next-head (car-safe (car options-and-methods)))
  188. (or (keywordp next-head)
  189. (eq next-head 'declare)))
  190. (pcase next-head
  191. (`:documentation
  192. (when doc (error "Multiple doc strings for %S" name))
  193. (setq doc (cadr (pop options-and-methods))))
  194. (`declare
  195. (when declarations (error "Multiple `declare' for %S" name))
  196. (setq declarations (pop options-and-methods)))
  197. (`:method (push (cdr (pop options-and-methods)) methods))
  198. (_ (push (pop options-and-methods) options))))
  199. (when options-and-methods
  200. ;; Anything remaining is assumed to be a default method body.
  201. (push `(,args ,@options-and-methods) methods))
  202. (when (eq 'setf (car-safe name))
  203. (require 'gv)
  204. (setq name (gv-setter (cadr name))))
  205. `(prog1
  206. (progn
  207. (defalias ',name
  208. (cl-generic-define ',name ',args ',(nreverse options))
  209. ,(help-add-fundoc-usage doc args))
  210. :autoload-end
  211. ,@(mapcar (lambda (method) `(cl-defmethod ,name ,@method))
  212. (nreverse methods)))
  213. ,@(mapcar (lambda (declaration)
  214. (let ((f (cdr (assq (car declaration)
  215. defun-declarations-alist))))
  216. (cond
  217. (f (apply (car f) name args (cdr declaration)))
  218. (t (message "Warning: Unknown defun property `%S' in %S"
  219. (car declaration) name)
  220. nil))))
  221. (cdr declarations)))))
  222. ;;;###autoload
  223. (defun cl-generic-define (name args options)
  224. (pcase-let* ((generic (cl-generic-ensure-function name 'noerror))
  225. (`(,spec-args . ,_) (cl--generic-split-args args))
  226. (mandatory (mapcar #'car spec-args))
  227. (apo (assq :argument-precedence-order options)))
  228. (unless (fboundp name)
  229. ;; If the generic function was fmakunbound, throw away previous methods.
  230. (setf (cl--generic-dispatches generic) nil)
  231. (setf (cl--generic-method-table generic) nil))
  232. (when apo
  233. (dolist (arg (cdr apo))
  234. (let ((pos (memq arg mandatory)))
  235. (unless pos (error "%S is not a mandatory argument" arg))
  236. (let* ((argno (- (length mandatory) (length pos)))
  237. (dispatches (cl--generic-dispatches generic))
  238. (dispatch (or (assq argno dispatches) (list argno))))
  239. (setf (cl--generic-dispatches generic)
  240. (cons dispatch (delq dispatch dispatches)))))))
  241. (setf (cl--generic-options generic) options)
  242. (cl--generic-make-function generic)))
  243. (defmacro cl-generic-current-method-specializers ()
  244. "List of (VAR . TYPE) where TYPE is var's specializer.
  245. This macro can only be used within the lexical scope of a cl-generic method."
  246. (error "cl-generic-current-method-specializers used outside of a method"))
  247. (defmacro cl-generic-define-context-rewriter (name args &rest body)
  248. "Define a special kind of context named NAME.
  249. Whenever a context specializer of the form (NAME . ARGS) appears,
  250. the specializer used will be the one returned by BODY."
  251. (declare (debug (&define name lambda-list def-body)) (indent defun))
  252. `(eval-and-compile
  253. (put ',name 'cl-generic--context-rewriter
  254. (lambda ,args ,@body))))
  255. (eval-and-compile ;Needed while compiling the cl-defmethod calls below!
  256. (defun cl--generic-fgrep (vars sexp) ;Copied from pcase.el.
  257. "Check which of the symbols VARS appear in SEXP."
  258. (let ((res '()))
  259. (while (consp sexp)
  260. (dolist (var (cl--generic-fgrep vars (pop sexp)))
  261. (unless (memq var res) (push var res))))
  262. (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
  263. res))
  264. (defun cl--generic-split-args (args)
  265. "Return (SPEC-ARGS . PLAIN-ARGS)."
  266. (let ((plain-args ())
  267. (specializers nil)
  268. (mandatory t))
  269. (dolist (arg args)
  270. (push (pcase arg
  271. ((or '&optional '&rest '&key) (setq mandatory nil) arg)
  272. ('&context
  273. (unless mandatory
  274. (error "&context not immediately after mandatory args"))
  275. (setq mandatory 'context) nil)
  276. ((let 'nil mandatory) arg)
  277. ((let 'context mandatory)
  278. (unless (consp arg)
  279. (error "Invalid &context arg: %S" arg))
  280. (let* ((name (car arg))
  281. (rewriter
  282. (and (symbolp name)
  283. (get name 'cl-generic--context-rewriter))))
  284. (if rewriter (setq arg (apply rewriter (cdr arg)))))
  285. (push `((&context . ,(car arg)) . ,(cadr arg)) specializers)
  286. nil)
  287. (`(,name . ,type)
  288. (push (cons name (car type)) specializers)
  289. name)
  290. (_
  291. (push (cons arg t) specializers)
  292. arg))
  293. plain-args))
  294. (cons (nreverse specializers)
  295. (nreverse (delq nil plain-args)))))
  296. (defun cl--generic-lambda (args body)
  297. "Make the lambda expression for a method with ARGS and BODY."
  298. (pcase-let* ((`(,spec-args . ,plain-args)
  299. (cl--generic-split-args args))
  300. (fun `(cl-function (lambda ,plain-args ,@body)))
  301. (macroenv (cons `(cl-generic-current-method-specializers
  302. . ,(lambda () spec-args))
  303. macroexpand-all-environment)))
  304. (require 'cl-lib) ;Needed to expand `cl-flet' and `cl-function'.
  305. ;; First macroexpand away the cl-function stuff (e.g. &key and
  306. ;; destructuring args, `declare' and whatnot).
  307. (pcase (macroexpand fun macroenv)
  308. (`#'(lambda ,args . ,body)
  309. (let* ((parsed-body (macroexp-parse-body body))
  310. (cnm (make-symbol "cl--cnm"))
  311. (nmp (make-symbol "cl--nmp"))
  312. (nbody (macroexpand-all
  313. `(cl-flet ((cl-call-next-method ,cnm)
  314. (cl-next-method-p ,nmp))
  315. ,@(cdr parsed-body))
  316. macroenv))
  317. ;; FIXME: Rather than `grep' after the fact, the
  318. ;; macroexpansion should directly set some flag when cnm
  319. ;; is used.
  320. ;; FIXME: Also, optimize the case where call-next-method is
  321. ;; only called with explicit arguments.
  322. (uses-cnm (cl--generic-fgrep (list cnm nmp) nbody)))
  323. (cons (not (not uses-cnm))
  324. `#'(lambda (,@(if uses-cnm (list cnm)) ,@args)
  325. ,@(car parsed-body)
  326. ,(if (not (memq nmp uses-cnm))
  327. nbody
  328. `(let ((,nmp (lambda ()
  329. (cl--generic-isnot-nnm-p ,cnm))))
  330. ,nbody))))))
  331. (f (error "Unexpected macroexpansion result: %S" f))))))
  332. (put 'cl-defmethod 'function-documentation
  333. '(cl--generic-make-defmethod-docstring))
  334. (defun cl--generic-make-defmethod-docstring ()
  335. ;; FIXME: Copy&paste from pcase--make-docstring.
  336. (let* ((main (documentation (symbol-function 'cl-defmethod) 'raw))
  337. (ud (help-split-fundoc main 'cl-defmethod)))
  338. ;; So that eg emacs -Q -l cl-lib --eval "(documentation 'pcase)" works,
  339. ;; where cl-lib is anything using pcase-defmacro.
  340. (require 'help-fns)
  341. (with-temp-buffer
  342. (insert (or (cdr ud) main))
  343. (insert "\n\n\tCurrently supported forms for TYPE:\n\n")
  344. (dolist (method (reverse (cl--generic-method-table
  345. (cl--generic 'cl-generic-generalizers))))
  346. (let* ((info (cl--generic-method-info method)))
  347. (when (nth 2 info)
  348. (insert (nth 2 info) "\n\n"))))
  349. (let ((combined-doc (buffer-string)))
  350. (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
  351. ;;;###autoload
  352. (defmacro cl-defmethod (name args &rest body)
  353. "Define a new method for generic function NAME.
  354. I.e. it defines the implementation of NAME to use for invocations where the
  355. values of the dispatch arguments match the specified TYPEs.
  356. The dispatch arguments have to be among the mandatory arguments, and
  357. all methods of NAME have to use the same set of arguments for dispatch.
  358. Each dispatch argument and TYPE are specified in ARGS where the corresponding
  359. formal argument appears as (VAR TYPE) rather than just VAR.
  360. The optional second argument QUALIFIER is a specifier that
  361. modifies how the method is combined with other methods, including:
  362. :before - Method will be called before the primary
  363. :after - Method will be called after the primary
  364. :around - Method will be called around everything else
  365. The absence of QUALIFIER means this is a \"primary\" method.
  366. The set of acceptable qualifiers and their meaning is defined
  367. \(and can be extended) by the methods of `cl-generic-combine-methods'.
  368. ARGS can also include so-called context specializers, introduced by
  369. `&context' (which should appear right after the mandatory arguments,
  370. before any &optional or &rest). They have the form (EXPR TYPE) where
  371. EXPR is an Elisp expression whose value should match TYPE for the
  372. method to be applicable.
  373. The set of acceptable TYPEs (also called \"specializers\") is defined
  374. \(and can be extended) by the various methods of `cl-generic-generalizers'.
  375. \(fn NAME [QUALIFIER] ARGS &rest [DOCSTRING] BODY)"
  376. (declare (doc-string 3) (indent defun)
  377. (debug
  378. (&define ; this means we are defining something
  379. [&or name ("setf" name :name setf)]
  380. ;; ^^ This is the methods symbol
  381. [ &rest atom ] ; Multiple qualifiers are allowed.
  382. ; Like in CLOS spec, we support
  383. ; any non-list values.
  384. cl-generic-method-args ; arguments
  385. [ &optional stringp ] ; documentation string
  386. def-body))) ; part to be debugged
  387. (let ((qualifiers nil))
  388. (while (not (listp args))
  389. (push args qualifiers)
  390. (setq args (pop body)))
  391. (when (eq 'setf (car-safe name))
  392. (require 'gv)
  393. (setq name (gv-setter (cadr name))))
  394. (pcase-let* ((`(,uses-cnm . ,fun) (cl--generic-lambda args body)))
  395. `(progn
  396. ,(and (get name 'byte-obsolete-info)
  397. (or (not (fboundp 'byte-compile-warning-enabled-p))
  398. (byte-compile-warning-enabled-p 'obsolete))
  399. (let* ((obsolete (get name 'byte-obsolete-info)))
  400. (macroexp--warn-and-return
  401. (macroexp--obsolete-warning name obsolete "generic function")
  402. nil)))
  403. ;; You could argue that `defmethod' modifies rather than defines the
  404. ;; function, so warnings like "not known to be defined" are fair game.
  405. ;; But in practice, it's common to use `cl-defmethod'
  406. ;; without a previous `cl-defgeneric'.
  407. ;; The ",'" is a no-op that pacifies check-declare.
  408. (,'declare-function ,name "")
  409. (cl-generic-define-method ',name ',(nreverse qualifiers) ',args
  410. ,uses-cnm ,fun)))))
  411. (defun cl--generic-member-method (specializers qualifiers methods)
  412. (while
  413. (and methods
  414. (let ((m (car methods)))
  415. (not (and (equal (cl--generic-method-specializers m) specializers)
  416. (equal (cl--generic-method-qualifiers m) qualifiers)))))
  417. (setq methods (cdr methods)))
  418. methods)
  419. (defun cl--generic-load-hist-format (name qualifiers specializers)
  420. ;; FIXME: This function is used in elisp-mode.el and
  421. ;; elisp-mode-tests.el, but I still decided to use an internal name
  422. ;; because these uses should be removed or moved into cl-generic.el.
  423. `(,name ,qualifiers . ,specializers))
  424. ;;;###autoload
  425. (defun cl-generic-define-method (name qualifiers args uses-cnm function)
  426. (pcase-let*
  427. ((generic (cl-generic-ensure-function name))
  428. (`(,spec-args . ,_) (cl--generic-split-args args))
  429. (specializers (mapcar (lambda (spec-arg)
  430. (if (eq '&context (car-safe (car spec-arg)))
  431. spec-arg (cdr spec-arg)))
  432. spec-args))
  433. (method (cl--generic-make-method
  434. specializers qualifiers uses-cnm function))
  435. (mt (cl--generic-method-table generic))
  436. (me (cl--generic-member-method specializers qualifiers mt))
  437. (dispatches (cl--generic-dispatches generic))
  438. (i 0))
  439. (dolist (spec-arg spec-args)
  440. (let* ((key (if (eq '&context (car-safe (car spec-arg)))
  441. (car spec-arg) i))
  442. (generalizers (cl-generic-generalizers (cdr spec-arg)))
  443. (x (assoc key dispatches)))
  444. (unless x
  445. (setq x (cons key (cl-generic-generalizers t)))
  446. (setf (cl--generic-dispatches generic)
  447. (setq dispatches (cons x dispatches))))
  448. (dolist (generalizer generalizers)
  449. (unless (member generalizer (cdr x))
  450. (setf (cdr x)
  451. (sort (cons generalizer (cdr x))
  452. (lambda (x y)
  453. (> (cl--generic-generalizer-priority x)
  454. (cl--generic-generalizer-priority y)))))))
  455. (setq i (1+ i))))
  456. ;; We used to (setcar me method), but that can cause false positives in
  457. ;; the hash-consing table of the method-builder (bug#20644).
  458. ;; See also the related FIXME in cl--generic-build-combined-method.
  459. (setf (cl--generic-method-table generic)
  460. (if (null me)
  461. (cons method mt)
  462. ;; Keep the ordering; important for methods with :extra qualifiers.
  463. (mapcar (lambda (x) (if (eq x (car me)) method x)) mt)))
  464. (let ((sym (cl--generic-name generic))) ; Actual name (for aliases).
  465. (unless (symbol-function sym)
  466. (defalias sym 'dummy)) ;Record definition into load-history.
  467. (cl-pushnew `(cl-defmethod . ,(cl--generic-load-hist-format
  468. (cl--generic-name generic)
  469. qualifiers specializers))
  470. current-load-list :test #'equal)
  471. ;; FIXME: Try to avoid re-constructing a new function if the old one
  472. ;; is still valid (e.g. still empty method cache)?
  473. (let ((gfun (cl--generic-make-function generic))
  474. ;; Prevent `defalias' from recording this as the definition site of
  475. ;; the generic function.
  476. current-load-list
  477. ;; BEWARE! Don't purify this function definition, since that leads
  478. ;; to memory corruption if the hash-tables it holds are modified
  479. ;; (the GC doesn't trace those pointers).
  480. (purify-flag nil))
  481. ;; But do use `defalias', so that it interacts properly with nadvice,
  482. ;; e.g. for tracing/debug-on-entry.
  483. (defalias sym gfun)))))
  484. (defmacro cl--generic-with-memoization (place &rest code)
  485. (declare (indent 1) (debug t))
  486. (gv-letplace (getter setter) place
  487. `(or ,getter
  488. ,(macroexp-let2 nil val (macroexp-progn code)
  489. `(progn
  490. ,(funcall setter val)
  491. ,val)))))
  492. (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
  493. (defun cl--generic-get-dispatcher (dispatch)
  494. (cl--generic-with-memoization
  495. (gethash dispatch cl--generic-dispatchers)
  496. ;; (message "cl--generic-get-dispatcher (%S)" dispatch)
  497. (let* ((dispatch-arg (car dispatch))
  498. (generalizers (cdr dispatch))
  499. (lexical-binding t)
  500. (tagcodes
  501. (mapcar (lambda (generalizer)
  502. (funcall (cl--generic-generalizer-tagcode-function
  503. generalizer)
  504. 'arg))
  505. generalizers))
  506. (typescodes
  507. (mapcar
  508. (lambda (generalizer)
  509. `(funcall ',(cl--generic-generalizer-specializers-function
  510. generalizer)
  511. ,(funcall (cl--generic-generalizer-tagcode-function
  512. generalizer)
  513. 'arg)))
  514. generalizers))
  515. (tag-exp
  516. ;; Minor optimization: since this tag-exp is
  517. ;; only used to lookup the method-cache, it
  518. ;; doesn't matter if the default value is some
  519. ;; constant or nil.
  520. `(or ,@(if (macroexp-const-p (car (last tagcodes)))
  521. (butlast tagcodes)
  522. tagcodes)))
  523. (fixedargs '(arg))
  524. (dispatch-idx dispatch-arg)
  525. (bindings nil))
  526. (when (eq '&context (car-safe dispatch-arg))
  527. (setq bindings `((arg ,(cdr dispatch-arg))))
  528. (setq fixedargs nil)
  529. (setq dispatch-idx 0))
  530. (dotimes (i dispatch-idx)
  531. (push (make-symbol (format "arg%d" (- dispatch-idx i 1))) fixedargs))
  532. ;; FIXME: For generic functions with a single method (or with 2 methods,
  533. ;; one of which always matches), using a tagcode + hash-table is
  534. ;; overkill: better just use a `cl-typep' test.
  535. (byte-compile
  536. `(lambda (generic dispatches-left methods)
  537. (let ((method-cache (make-hash-table :test #'eql)))
  538. (lambda (,@fixedargs &rest args)
  539. (let ,bindings
  540. (apply (cl--generic-with-memoization
  541. (gethash ,tag-exp method-cache)
  542. (cl--generic-cache-miss
  543. generic ',dispatch-arg dispatches-left methods
  544. ,(if (cdr typescodes)
  545. `(append ,@typescodes) (car typescodes))))
  546. ,@fixedargs args)))))))))
  547. (defun cl--generic-make-function (generic)
  548. (cl--generic-make-next-function generic
  549. (cl--generic-dispatches generic)
  550. (cl--generic-method-table generic)))
  551. (defun cl--generic-make-next-function (generic dispatches methods)
  552. (let* ((dispatch
  553. (progn
  554. (while (and dispatches
  555. (let ((x (nth 1 (car dispatches))))
  556. ;; No need to dispatch for t specializers.
  557. (or (null x) (equal x cl--generic-t-generalizer))))
  558. (setq dispatches (cdr dispatches)))
  559. (pop dispatches))))
  560. (if (not (and dispatch
  561. ;; If there's no method left, there's no point checking
  562. ;; further arguments.
  563. methods))
  564. (cl--generic-build-combined-method generic methods)
  565. (let ((dispatcher (cl--generic-get-dispatcher dispatch)))
  566. (funcall dispatcher generic dispatches methods)))))
  567. (defvar cl--generic-combined-method-memoization
  568. (make-hash-table :test #'equal :weakness 'value)
  569. "Table storing previously built combined-methods.
  570. This is particularly useful when many different tags select the same set
  571. of methods, since this table then allows us to share a single combined-method
  572. for all those different tags in the method-cache.")
  573. (define-error 'cl--generic-cyclic-definition "Cyclic definition: %S")
  574. (defun cl--generic-build-combined-method (generic methods)
  575. (if (null methods)
  576. ;; Special case needed to fix a circularity during bootstrap.
  577. (cl--generic-standard-method-combination generic methods)
  578. (let ((f
  579. (cl--generic-with-memoization
  580. ;; FIXME: Since the fields of `generic' are modified, this
  581. ;; hash-table won't work right, because the hashes will change!
  582. ;; It's not terribly serious, but reduces the effectiveness of
  583. ;; the table.
  584. (gethash (cons generic methods)
  585. cl--generic-combined-method-memoization)
  586. (puthash (cons generic methods) :cl--generic--under-construction
  587. cl--generic-combined-method-memoization)
  588. (condition-case nil
  589. (cl-generic-combine-methods generic methods)
  590. ;; Special case needed to fix a circularity during bootstrap.
  591. (cl--generic-cyclic-definition
  592. (cl--generic-standard-method-combination generic methods))))))
  593. (if (eq f :cl--generic--under-construction)
  594. (signal 'cl--generic-cyclic-definition
  595. (list (cl--generic-name generic)))
  596. f))))
  597. (defun cl--generic-no-next-method-function (generic method)
  598. (lambda (&rest args)
  599. (apply #'cl-no-next-method generic method args)))
  600. (defun cl-generic-call-method (generic method &optional fun)
  601. "Return a function that calls METHOD.
  602. FUN is the function that should be called when METHOD calls
  603. `call-next-method'."
  604. (if (not (cl--generic-method-uses-cnm method))
  605. (cl--generic-method-function method)
  606. (let ((met-fun (cl--generic-method-function method))
  607. (next (or fun (cl--generic-no-next-method-function
  608. generic method))))
  609. (lambda (&rest args)
  610. (apply met-fun
  611. ;; FIXME: This sucks: passing just `next' would
  612. ;; be a lot more efficient than the lambda+apply
  613. ;; quasi-η, but we need this to implement the
  614. ;; "if call-next-method is called with no
  615. ;; arguments, then use the previous arguments".
  616. (lambda (&rest cnm-args)
  617. (apply next (or cnm-args args)))
  618. args)))))
  619. ;; Standard CLOS name.
  620. (defalias 'cl-method-qualifiers #'cl--generic-method-qualifiers)
  621. (defun cl--generic-standard-method-combination (generic methods)
  622. (let ((mets-by-qual ()))
  623. (dolist (method methods)
  624. (let ((qualifiers (cl-method-qualifiers method)))
  625. (if (eq (car qualifiers) :extra) (setq qualifiers (cddr qualifiers)))
  626. (unless (member qualifiers '(() (:after) (:before) (:around)))
  627. (error "Unsupported qualifiers in function %S: %S"
  628. (cl--generic-name generic) qualifiers))
  629. (push method (alist-get (car qualifiers) mets-by-qual))))
  630. (cond
  631. ((null mets-by-qual)
  632. (lambda (&rest args)
  633. (apply #'cl-no-applicable-method generic args)))
  634. ((null (alist-get nil mets-by-qual))
  635. (lambda (&rest args)
  636. (apply #'cl-no-primary-method generic args)))
  637. (t
  638. (let* ((fun nil)
  639. (ab-call (lambda (m) (cl-generic-call-method generic m)))
  640. (before
  641. (mapcar ab-call (reverse (cdr (assoc :before mets-by-qual)))))
  642. (after (mapcar ab-call (cdr (assoc :after mets-by-qual)))))
  643. (dolist (method (cdr (assoc nil mets-by-qual)))
  644. (setq fun (cl-generic-call-method generic method fun)))
  645. (when (or after before)
  646. (let ((next fun))
  647. (setq fun (lambda (&rest args)
  648. (dolist (bf before)
  649. (apply bf args))
  650. (prog1
  651. (apply next args)
  652. (dolist (af after)
  653. (apply af args)))))))
  654. (dolist (method (cdr (assoc :around mets-by-qual)))
  655. (setq fun (cl-generic-call-method generic method fun)))
  656. fun)))))
  657. (defun cl-generic-apply (generic args)
  658. "Like `apply' but takes a cl-generic object rather than a function."
  659. ;; Handy in cl-no-applicable-method, for example.
  660. ;; In Common Lisp, generic-function objects are funcallable. Ideally
  661. ;; we'd want the same in Elisp, but it would either require using a very
  662. ;; different (and less efficient) representation of cl--generic objects,
  663. ;; or non-trivial changes in the general infrastructure (compiler and such).
  664. (apply (cl--generic-name generic) args))
  665. (defun cl--generic-arg-specializer (method dispatch-arg)
  666. (or (if (integerp dispatch-arg)
  667. (nth dispatch-arg
  668. (cl--generic-method-specializers method))
  669. (cdr (assoc dispatch-arg
  670. (cl--generic-method-specializers method))))
  671. t))
  672. (defun cl--generic-cache-miss (generic
  673. dispatch-arg dispatches-left methods-left types)
  674. (let ((methods '()))
  675. (dolist (method methods-left)
  676. (let* ((specializer (cl--generic-arg-specializer method dispatch-arg))
  677. (m (member specializer types)))
  678. (when m
  679. (push (cons (length m) method) methods))))
  680. ;; Sort the methods, most specific first.
  681. ;; It would be tempting to sort them once and for all in the method-table
  682. ;; rather than here, but the order might depend on the actual argument
  683. ;; (e.g. for multiple inheritance with defclass).
  684. (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
  685. (cl--generic-make-next-function generic dispatches-left methods)))
  686. (cl-defgeneric cl-generic-generalizers (specializer)
  687. "Return a list of generalizers for a given SPECIALIZER.
  688. To each kind of `specializer', corresponds a `generalizer' which describes
  689. how to extract a \"tag\" from an object which will then let us check if this
  690. object matches the specializer. A typical example of a \"tag\" would be the
  691. type of an object. It's called a `generalizer' because it
  692. takes a specific object and returns a more general approximation,
  693. denoting a set of objects to which it belongs.
  694. A generalizer gives us the chunk of code which the
  695. dispatch function needs to use to extract the \"tag\" of an object, as well
  696. as a function which turns this tag into an ordered list of
  697. `specializers' that this object matches.
  698. The code which extracts the tag should be as fast as possible.
  699. The tags should be chosen according to the following rules:
  700. - The tags should not be too specific: similar objects which match the
  701. same list of specializers should ideally use the same (`eql') tag.
  702. This insures that the cached computation of the applicable
  703. methods for one object can be reused for other objects.
  704. - Corollary: objects which don't match any of the relevant specializers
  705. should ideally all use the same tag (typically nil).
  706. This insures that this cache does not grow unnecessarily large.
  707. - Two different generalizers G1 and G2 should not use the same tag
  708. unless they use it for the same set of objects. IOW, if G1.tag(X1) =
  709. G2.tag(X2) then G1.tag(X1) = G2.tag(X1) = G1.tag(X2) = G2.tag(X2).
  710. - If G1.priority > G2.priority and G1.tag(X1) = G1.tag(X2) and this tag is
  711. non-nil, then you have to make sure that the G2.tag(X1) = G2.tag(X2).
  712. This is because the method-cache is only indexed with the first non-nil
  713. tag (by order of decreasing priority).")
  714. (cl-defgeneric cl-generic-combine-methods (generic methods)
  715. "Build the effective method made of METHODS.
  716. It should return a function that expects the same arguments as the methods, and
  717. calls those methods in some appropriate order.
  718. GENERIC is the generic function (mostly used for its name).
  719. METHODS is the list of the selected methods.
  720. The METHODS list is sorted from most specific first to most generic last.
  721. The function can use `cl-generic-call-method' to create functions that call those
  722. methods.")
  723. (unless (ignore-errors (cl-generic-generalizers t))
  724. ;; Temporary definition to let the next defmethod succeed.
  725. (fset 'cl-generic-generalizers
  726. (lambda (specializer)
  727. (if (eq t specializer) (list cl--generic-t-generalizer))))
  728. (fset 'cl-generic-combine-methods #'cl--generic-standard-method-combination))
  729. (cl-defmethod cl-generic-generalizers (specializer)
  730. "Support for the catch-all t specializer which always matches."
  731. (if (eq specializer t) (list cl--generic-t-generalizer)
  732. (error "Unknown specializer %S" specializer)))
  733. (eval-when-compile
  734. ;; This macro is brittle and only really important in order to be
  735. ;; able to preload cl-generic without also preloading the byte-compiler,
  736. ;; So we use `eval-when-compile' so as not keep it available longer than
  737. ;; strictly needed.
  738. (defmacro cl--generic-prefill-dispatchers (arg-or-context specializer)
  739. (unless (integerp arg-or-context)
  740. (setq arg-or-context `(&context . ,arg-or-context)))
  741. (unless (fboundp 'cl--generic-get-dispatcher)
  742. (require 'cl-generic))
  743. (let ((fun (cl--generic-get-dispatcher
  744. `(,arg-or-context ,@(cl-generic-generalizers specializer)
  745. ,cl--generic-t-generalizer))))
  746. ;; Recompute dispatch at run-time, since the generalizers may be slightly
  747. ;; different (e.g. byte-compiled rather than interpreted).
  748. ;; FIXME: There is a risk that the run-time generalizer is not equivalent
  749. ;; to the compile-time one, in which case `fun' may not be correct
  750. ;; any more!
  751. `(let ((dispatch `(,',arg-or-context
  752. ,@(cl-generic-generalizers ',specializer)
  753. ,cl--generic-t-generalizer)))
  754. ;; (message "Prefilling for %S with \n%S" dispatch ',fun)
  755. (puthash dispatch ',fun cl--generic-dispatchers)))))
  756. (cl-defmethod cl-generic-combine-methods (generic methods)
  757. "Standard support for :after, :before, :around, and `:extra NAME' qualifiers."
  758. (cl--generic-standard-method-combination generic methods))
  759. (defconst cl--generic-nnm-sample (cl--generic-no-next-method-function t t))
  760. (defconst cl--generic-cnm-sample
  761. (funcall (cl--generic-build-combined-method
  762. nil (list (cl--generic-make-method () () t #'identity)))))
  763. (defun cl--generic-isnot-nnm-p (cnm)
  764. "Return non-nil if CNM is the function that calls `cl-no-next-method'."
  765. ;; ¡Big Gross Ugly Hack!
  766. ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
  767. ;; it, and some packages use it, so we need to support it.
  768. (catch 'found
  769. (cl-assert (function-equal cnm cl--generic-cnm-sample))
  770. (if (byte-code-function-p cnm)
  771. (let ((cnm-constants (aref cnm 2))
  772. (sample-constants (aref cl--generic-cnm-sample 2)))
  773. (dotimes (i (length sample-constants))
  774. (when (function-equal (aref sample-constants i)
  775. cl--generic-nnm-sample)
  776. (throw 'found
  777. (not (function-equal (aref cnm-constants i)
  778. cl--generic-nnm-sample))))))
  779. (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
  780. (let ((cnm-env (cadr cnm)))
  781. (dolist (vb (cadr cl--generic-cnm-sample))
  782. (when (function-equal (cdr vb) cl--generic-nnm-sample)
  783. (throw 'found
  784. (not (function-equal (cdar cnm-env)
  785. cl--generic-nnm-sample))))
  786. (setq cnm-env (cdr cnm-env)))))
  787. (error "Haven't found no-next-method-sample in cnm-sample")))
  788. ;;; Define some pre-defined generic functions, used internally.
  789. (define-error 'cl-no-method "No method")
  790. (define-error 'cl-no-next-method "No next method" 'cl-no-method)
  791. (define-error 'cl-no-primary-method "No primary method" 'cl-no-method)
  792. (define-error 'cl-no-applicable-method "No applicable method"
  793. 'cl-no-method)
  794. (cl-defgeneric cl-no-next-method (generic method &rest args)
  795. "Function called when `cl-call-next-method' finds no next method."
  796. (signal 'cl-no-next-method `(,(cl--generic-name generic) ,method ,@args)))
  797. (cl-defgeneric cl-no-applicable-method (generic &rest args)
  798. "Function called when a method call finds no applicable method."
  799. (signal 'cl-no-applicable-method `(,(cl--generic-name generic) ,@args)))
  800. (cl-defgeneric cl-no-primary-method (generic &rest args)
  801. "Function called when a method call finds no primary method."
  802. (signal 'cl-no-primary-method `(,(cl--generic-name generic) ,@args)))
  803. (defun cl-call-next-method (&rest _args)
  804. "Function to call the next applicable method.
  805. Can only be used from within the lexical body of a primary or around method."
  806. (error "cl-call-next-method only allowed inside primary and around methods"))
  807. (defun cl-next-method-p ()
  808. "Return non-nil if there is a next method.
  809. Can only be used from within the lexical body of a primary or around method."
  810. (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
  811. (error "cl-next-method-p only allowed inside primary and around methods"))
  812. ;;;###autoload
  813. (defun cl-find-method (generic qualifiers specializers)
  814. (car (cl--generic-member-method
  815. specializers qualifiers
  816. (cl--generic-method-table (cl--generic generic)))))
  817. ;;; Add support for describe-function
  818. (defun cl--generic-search-method (met-name)
  819. "For `find-function-regexp-alist'. Searches for a cl-defmethod.
  820. MET-NAME is as returned by `cl--generic-load-hist-format'."
  821. (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
  822. (regexp-quote (format "%s" (car met-name)))
  823. "\\_>")))
  824. (or
  825. (re-search-forward
  826. (concat base-re "[^&\"\n]*"
  827. (mapconcat (lambda (qualifier)
  828. (regexp-quote (format "%S" qualifier)))
  829. (cadr met-name)
  830. "[ \t\n]*")
  831. (mapconcat (lambda (specializer)
  832. (regexp-quote
  833. (format "%S" (if (consp specializer)
  834. (nth 1 specializer) specializer))))
  835. (remq t (cddr met-name))
  836. "[ \t\n]*)[^&\"\n]*"))
  837. nil t)
  838. (re-search-forward base-re nil t))))
  839. ;; WORKAROUND: This can't be a defconst due to bug#21237.
  840. (defvar cl--generic-find-defgeneric-regexp "(\\(?:cl-\\)?defgeneric[ \t]+%s\\>")
  841. (with-eval-after-load 'find-func
  842. (defvar find-function-regexp-alist)
  843. (add-to-list 'find-function-regexp-alist
  844. `(cl-defmethod . ,#'cl--generic-search-method))
  845. (add-to-list 'find-function-regexp-alist
  846. `(cl-defgeneric . cl--generic-find-defgeneric-regexp)))
  847. (defun cl--generic-method-info (method)
  848. (let* ((specializers (cl--generic-method-specializers method))
  849. (qualifiers (cl--generic-method-qualifiers method))
  850. (uses-cnm (cl--generic-method-uses-cnm method))
  851. (function (cl--generic-method-function method))
  852. (args (help-function-arglist function 'names))
  853. (docstring (documentation function))
  854. (qual-string
  855. (if (null qualifiers) ""
  856. (cl-assert (consp qualifiers))
  857. (let ((s (prin1-to-string qualifiers)))
  858. (concat (substring s 1 -1) " "))))
  859. (doconly (if docstring
  860. (let ((split (help-split-fundoc docstring nil)))
  861. (if split (cdr split) docstring))))
  862. (combined-args ()))
  863. (if uses-cnm (setq args (cdr args)))
  864. (dolist (specializer specializers)
  865. (let ((arg (if (eq '&rest (car args))
  866. (intern (format "arg%d" (length combined-args)))
  867. (pop args))))
  868. (push (if (eq specializer t) arg (list arg specializer))
  869. combined-args)))
  870. (setq combined-args (append (nreverse combined-args) args))
  871. (list qual-string combined-args doconly)))
  872. (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
  873. (defun cl--generic-describe (function)
  874. ;; Supposedly this is called from help-fns, so help-fns should be loaded at
  875. ;; this point.
  876. (declare-function help-fns-short-filename "help-fns" (filename))
  877. (let ((generic (if (symbolp function) (cl--generic function))))
  878. (when generic
  879. (require 'help-mode) ;Needed for `help-function-def' button!
  880. (save-excursion
  881. (insert "\n\nThis is a generic function.\n\n")
  882. (insert (propertize "Implementations:\n\n" 'face 'bold))
  883. ;; Loop over fanciful generics
  884. (dolist (method (cl--generic-method-table generic))
  885. (let* ((info (cl--generic-method-info method)))
  886. ;; FIXME: Add hyperlinks for the types as well.
  887. (insert (format "%s%S" (nth 0 info) (nth 1 info)))
  888. (let* ((met-name (cl--generic-load-hist-format
  889. function
  890. (cl--generic-method-qualifiers method)
  891. (cl--generic-method-specializers method)))
  892. (file (find-lisp-object-file-name met-name 'cl-defmethod)))
  893. (when file
  894. (insert (substitute-command-keys " in `"))
  895. (help-insert-xref-button (help-fns-short-filename file)
  896. 'help-function-def met-name file
  897. 'cl-defmethod)
  898. (insert (substitute-command-keys "'.\n"))))
  899. (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
  900. (defun cl--generic-specializers-apply-to-type-p (specializers type)
  901. "Return non-nil if a method with SPECIALIZERS applies to TYPE."
  902. (let ((applies nil))
  903. (dolist (specializer specializers)
  904. (if (memq (car-safe specializer) '(subclass eieio--static))
  905. (setq specializer (nth 1 specializer)))
  906. ;; Don't include the methods that are "too generic", such as those
  907. ;; applying to `eieio-default-superclass'.
  908. (and (not (memq specializer '(t eieio-default-superclass)))
  909. (or (equal type specializer)
  910. (when (symbolp specializer)
  911. (let ((sclass (cl--find-class specializer))
  912. (tclass (cl--find-class type)))
  913. (when (and sclass tclass)
  914. (member specializer (cl--generic-class-parents tclass))))))
  915. (setq applies t)))
  916. applies))
  917. (defun cl-generic-all-functions (&optional type)
  918. "Return a list of all generic functions.
  919. Optional TYPE argument returns only those functions that contain
  920. methods for TYPE."
  921. (let ((l nil))
  922. (mapatoms
  923. (lambda (symbol)
  924. (let ((generic (and (fboundp symbol) (cl--generic symbol))))
  925. (and generic
  926. (catch 'found
  927. (if (null type) (throw 'found t))
  928. (dolist (method (cl--generic-method-table generic))
  929. (if (cl--generic-specializers-apply-to-type-p
  930. (cl--generic-method-specializers method) type)
  931. (throw 'found t))))
  932. (push symbol l)))))
  933. l))
  934. (defun cl--generic-method-documentation (function type)
  935. "Return info for all methods of FUNCTION (a symbol) applicable to TYPE.
  936. The value returned is a list of elements of the form
  937. \(QUALIFIERS ARGS DOC)."
  938. (let ((generic (cl--generic function))
  939. (docs ()))
  940. (when generic
  941. (dolist (method (cl--generic-method-table generic))
  942. (when (cl--generic-specializers-apply-to-type-p
  943. (cl--generic-method-specializers method) type)
  944. (push (cl--generic-method-info method) docs))))
  945. docs))
  946. (defun cl--generic-method-files (method)
  947. "Return a list of files where METHOD is defined by `cl-defmethod'.
  948. The list will have entries of the form (FILE . (METHOD ...))
  949. where (METHOD ...) contains the qualifiers and specializers of
  950. the method and is a suitable argument for
  951. `find-function-search-for-symbol'. Filenames are absolute."
  952. (let (result)
  953. (pcase-dolist (`(,file . ,defs) load-history)
  954. (dolist (def defs)
  955. (when (and (eq (car-safe def) 'cl-defmethod)
  956. (eq (cadr def) method))
  957. (push (cons file (cdr def)) result))))
  958. result))
  959. ;;; Support for (head <val>) specializers.
  960. ;; For both the `eql' and the `head' specializers, the dispatch
  961. ;; is unsatisfactory. Basically, in the "common&fast case", we end up doing
  962. ;;
  963. ;; (let ((tag (gethash value <tagcode-hashtable>)))
  964. ;; (funcall (gethash tag <method-cache>)))
  965. ;;
  966. ;; whereas we'd like to just do
  967. ;;
  968. ;; (funcall (gethash value <method-cache>)))
  969. ;;
  970. ;; but the problem is that the method-cache is normally "open ended", so
  971. ;; a nil means "not computed yet" and if we bump into it, we dutifully fill the
  972. ;; corresponding entry, whereas we'd want to just fallback on some default
  973. ;; effective method (so as not to fill the cache with lots of redundant
  974. ;; entries).
  975. (defvar cl--generic-head-used (make-hash-table :test #'eql))
  976. (cl-generic-define-generalizer cl--generic-head-generalizer
  977. 80 (lambda (name &rest _) `(gethash (car-safe ,name) cl--generic-head-used))
  978. (lambda (tag &rest _) (if (eq (car-safe tag) 'head) (list tag))))
  979. (cl-defmethod cl-generic-generalizers :extra "head" (specializer)
  980. "Support for (head VAL) specializers.
  981. These match if the argument is a cons cell whose car is `eql' to VAL."
  982. ;; We have to implement `head' here using the :extra qualifier,
  983. ;; since we can't use the `head' specializer to implement itself.
  984. (if (not (eq (car-safe specializer) 'head))
  985. (cl-call-next-method)
  986. (cl--generic-with-memoization
  987. (gethash (cadr specializer) cl--generic-head-used) specializer)
  988. (list cl--generic-head-generalizer)))
  989. (cl--generic-prefill-dispatchers 0 (head eql))
  990. ;;; Support for (eql <val>) specializers.
  991. (defvar cl--generic-eql-used (make-hash-table :test #'eql))
  992. (cl-generic-define-generalizer cl--generic-eql-generalizer
  993. 100 (lambda (name &rest _) `(gethash ,name cl--generic-eql-used))
  994. (lambda (tag &rest _) (if (eq (car-safe tag) 'eql) (list tag))))
  995. (cl-defmethod cl-generic-generalizers ((specializer (head eql)))
  996. "Support for (eql VAL) specializers.
  997. These match if the argument is `eql' to VAL."
  998. (puthash (cadr specializer) specializer cl--generic-eql-used)
  999. (list cl--generic-eql-generalizer))
  1000. (cl--generic-prefill-dispatchers 0 (eql nil))
  1001. (cl--generic-prefill-dispatchers window-system (eql nil))
  1002. (cl--generic-prefill-dispatchers (terminal-parameter nil 'xterm--get-selection)
  1003. (eql nil))
  1004. (cl--generic-prefill-dispatchers (terminal-parameter nil 'xterm--set-selection)
  1005. (eql nil))
  1006. ;;; Support for cl-defstructs specializers.
  1007. (defun cl--generic-struct-tag (name &rest _)
  1008. ;; Use exactly the same code as for `typeof'.
  1009. `(if ,name (type-of ,name) 'null))
  1010. (defun cl--generic-class-parents (class)
  1011. (let ((parents ())
  1012. (classes (list class)))
  1013. ;; BFS precedence. FIXME: Use a topological sort.
  1014. (while (let ((class (pop classes)))
  1015. (cl-pushnew (cl--class-name class) parents)
  1016. (setq classes
  1017. (append classes
  1018. (cl--class-parents class)))))
  1019. (nreverse parents)))
  1020. (defun cl--generic-struct-specializers (tag &rest _)
  1021. (and (symbolp tag)
  1022. (let ((class (get tag 'cl--class)))
  1023. (when (cl-typep class 'cl-structure-class)
  1024. (cl--generic-class-parents class)))))
  1025. (cl-generic-define-generalizer cl--generic-struct-generalizer
  1026. 50 #'cl--generic-struct-tag
  1027. #'cl--generic-struct-specializers)
  1028. (cl-defmethod cl-generic-generalizers :extra "cl-struct" (type)
  1029. "Support for dispatch on types defined by `cl-defstruct'."
  1030. (or
  1031. (when (symbolp type)
  1032. ;; Use the "cl--struct-class*" (inlinable) functions/macros rather than
  1033. ;; the "cl-struct-*" variants which aren't inlined, so that dispatch can
  1034. ;; take place without requiring cl-lib.
  1035. (let ((class (cl--find-class type)))
  1036. (and (cl-typep class 'cl-structure-class)
  1037. (or (null (cl--struct-class-type class))
  1038. (error "Can't dispatch on cl-struct %S: type is %S"
  1039. type (cl--struct-class-type class)))
  1040. (progn (cl-assert (null (cl--struct-class-named class))) t)
  1041. (list cl--generic-struct-generalizer))))
  1042. (cl-call-next-method)))
  1043. (cl--generic-prefill-dispatchers 0 cl--generic-generalizer)
  1044. ;;; Dispatch on "system types".
  1045. (defconst cl--generic-typeof-types
  1046. ;; Hand made from the source code of `type-of'.
  1047. '((integer number number-or-marker atom)
  1048. (symbol atom) (string array sequence atom)
  1049. (cons list sequence)
  1050. ;; Markers aren't `numberp', yet they are accepted wherever integers are
  1051. ;; accepted, pretty much.
  1052. (marker number-or-marker atom)
  1053. (overlay atom) (float number atom) (window-configuration atom)
  1054. (process atom) (window atom) (subr atom) (compiled-function function atom)
  1055. (buffer atom) (char-table array sequence atom)
  1056. (bool-vector array sequence atom)
  1057. (frame atom) (hash-table atom) (terminal atom)
  1058. (thread atom) (mutex atom) (condvar atom)
  1059. (font-spec atom) (font-entity atom) (font-object atom)
  1060. (vector array sequence atom)
  1061. ;; Plus, really hand made:
  1062. (null symbol list sequence atom))
  1063. "Alist of supertypes.
  1064. Each element has the form (TYPE . SUPERTYPES) where TYPE is one of
  1065. the symbols returned by `type-of', and SUPERTYPES is the list of its
  1066. supertypes from the most specific to least specific.")
  1067. (defconst cl--generic-all-builtin-types
  1068. (delete-dups (copy-sequence (apply #'append cl--generic-typeof-types))))
  1069. (cl-generic-define-generalizer cl--generic-typeof-generalizer
  1070. ;; FIXME: We could also change `type-of' to return `null' for nil.
  1071. 10 (lambda (name &rest _) `(if ,name (type-of ,name) 'null))
  1072. (lambda (tag &rest _)
  1073. (and (symbolp tag) (assq tag cl--generic-typeof-types))))
  1074. (cl-defmethod cl-generic-generalizers :extra "typeof" (type)
  1075. "Support for dispatch on builtin types.
  1076. See the full list and their hierarchy in `cl--generic-typeof-types'."
  1077. ;; FIXME: Add support for other types accepted by `cl-typep' such
  1078. ;; as `character', `face', `function', ...
  1079. (or
  1080. (and (memq type cl--generic-all-builtin-types)
  1081. (progn
  1082. ;; FIXME: While this wrinkle in the semantics can be occasionally
  1083. ;; problematic, this warning is more often annoying than helpful.
  1084. ;;(if (memq type '(vector array sequence))
  1085. ;; (message "`%S' also matches CL structs and EIEIO classes"
  1086. ;; type))
  1087. (list cl--generic-typeof-generalizer)))
  1088. (cl-call-next-method)))
  1089. (cl--generic-prefill-dispatchers 0 integer)
  1090. ;;; Dispatch on major mode.
  1091. ;; Two parts:
  1092. ;; - first define a specializer (derived-mode <mode>) to match symbols
  1093. ;; representing major modes, while obeying the major mode hierarchy.
  1094. ;; - then define a context-rewriter so you can write
  1095. ;; "&context (major-mode c-mode)" rather than
  1096. ;; "&context (major-mode (derived-mode c-mode))".
  1097. (defun cl--generic-derived-specializers (mode &rest _)
  1098. ;; FIXME: Handle (derived-mode <mode1> ... <modeN>)
  1099. (let ((specializers ()))
  1100. (while mode
  1101. (push `(derived-mode ,mode) specializers)
  1102. (setq mode (get mode 'derived-mode-parent)))
  1103. (nreverse specializers)))
  1104. (cl-generic-define-generalizer cl--generic-derived-generalizer
  1105. 90 (lambda (name) `(and (symbolp ,name) (functionp ,name) ,name))
  1106. #'cl--generic-derived-specializers)
  1107. (cl-defmethod cl-generic-generalizers ((_specializer (head derived-mode)))
  1108. "Support for (derived-mode MODE) specializers.
  1109. Used internally for the (major-mode MODE) context specializers."
  1110. (list cl--generic-derived-generalizer))
  1111. (cl-generic-define-context-rewriter major-mode (mode &rest modes)
  1112. `(major-mode ,(if (consp mode)
  1113. ;;E.g. could be (eql ...)
  1114. (progn (cl-assert (null modes)) mode)
  1115. `(derived-mode ,mode . ,modes))))
  1116. ;;; Support for unloading.
  1117. (cl-defmethod loadhist-unload-element ((x (head cl-defmethod)))
  1118. (pcase-let*
  1119. ((`(,name ,qualifiers . ,specializers) (cdr x))
  1120. (generic (cl-generic-ensure-function name 'noerror)))
  1121. (when generic
  1122. (let* ((mt (cl--generic-method-table generic))
  1123. (me (cl--generic-member-method specializers qualifiers mt)))
  1124. (when me
  1125. (setf (cl--generic-method-table generic) (delq (car me) mt)))))))
  1126. (provide 'cl-generic)
  1127. ;;; cl-generic.el ends here