cl-generic.el 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. ;;; cl-generic.el --- CLOS-style generic functions for Elisp -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2015 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 adds methods
  73. ;; to cl-generic-combine-methods with a specializer that says it applies only
  74. ;; when some particular qualifier is used).
  75. ;; - A way to dispatch on the context (e.g. the major-mode, some global
  76. ;; variable, you name it).
  77. ;;; Code:
  78. ;; Note: For generic functions that dispatch on several arguments (i.e. those
  79. ;; which use the multiple-dispatch feature), we always use the same "tagcodes"
  80. ;; and the same set of arguments on which to dispatch. This works, but is
  81. ;; often suboptimal since after one dispatch, the remaining dispatches can
  82. ;; usually be simplified, or even completely skipped.
  83. (eval-when-compile (require 'cl-lib))
  84. (eval-when-compile (require 'cl-macs)) ;For cl--find-class.
  85. (eval-when-compile (require 'pcase))
  86. (cl-defstruct (cl--generic-generalizer
  87. (:constructor nil)
  88. (:constructor cl-generic-make-generalizer
  89. (priority tagcode-function specializers-function)))
  90. (priority nil :type integer)
  91. tagcode-function
  92. specializers-function)
  93. (defconst cl--generic-t-generalizer
  94. (cl-generic-make-generalizer
  95. 0 (lambda (_name) nil) (lambda (_tag) '(t))))
  96. (cl-defstruct (cl--generic-method
  97. (:constructor nil)
  98. (:constructor cl--generic-make-method
  99. (specializers qualifiers uses-cnm function))
  100. (:predicate nil))
  101. (specializers nil :read-only t :type list)
  102. (qualifiers nil :read-only t :type (list-of atom))
  103. ;; USES-CNM is a boolean indicating if FUNCTION expects an extra argument
  104. ;; holding the next-method.
  105. (uses-cnm nil :read-only t :type boolean)
  106. (function nil :read-only t :type function))
  107. (cl-defstruct (cl--generic
  108. (:constructor nil)
  109. (:constructor cl--generic-make (name))
  110. (:predicate nil))
  111. (name nil :type symbol :read-only t) ;Pointer back to the symbol.
  112. ;; `dispatches' holds a list of (ARGNUM . TAGCODES) where ARGNUM is the index
  113. ;; of the corresponding argument and TAGCODES is a list of (PRIORITY . EXP)
  114. ;; where the EXPs are expressions (to be `or'd together) to compute the tag
  115. ;; on which to dispatch and PRIORITY is the priority of each expression to
  116. ;; decide in which order to sort them.
  117. ;; The most important dispatch is last in the list (and the least is first).
  118. (dispatches nil :type (list-of (cons natnum (list-of generalizers))))
  119. (method-table nil :type (list-of cl--generic-method))
  120. (options nil :type list))
  121. (defun cl-generic-function-options (generic)
  122. "Return the options of the generic function GENERIC."
  123. (cl--generic-options generic))
  124. (defmacro cl--generic (name)
  125. `(get ,name 'cl--generic))
  126. (defun cl-generic-ensure-function (name)
  127. (let (generic
  128. (origname name))
  129. (while (and (null (setq generic (cl--generic name)))
  130. (fboundp name)
  131. (symbolp (symbol-function name)))
  132. (setq name (symbol-function name)))
  133. (unless (or (not (fboundp name))
  134. (autoloadp (symbol-function name))
  135. (and (functionp name) generic))
  136. (error "%s is already defined as something else than a generic function"
  137. origname))
  138. (if generic
  139. (cl-assert (eq name (cl--generic-name generic)))
  140. (setf (cl--generic name) (setq generic (cl--generic-make name)))
  141. (defalias name (cl--generic-make-function generic)))
  142. generic))
  143. ;;;###autoload
  144. (defmacro cl-defgeneric (name args &rest options-and-methods)
  145. "Create a generic function NAME.
  146. DOC-STRING is the base documentation for this class. A generic
  147. function has no body, as its purpose is to decide which method body
  148. is appropriate to use. Specific methods are defined with `cl-defmethod'.
  149. With this implementation the ARGS are currently ignored.
  150. OPTIONS-AND-METHODS currently understands:
  151. - (:documentation DOCSTRING)
  152. - (declare DECLARATIONS)
  153. - (:argument-precedence-order &rest ARGS)
  154. - (:method [QUALIFIERS...] ARGS &rest BODY)
  155. BODY, if present, is used as the body of a default method.
  156. \(fn NAME ARGS [DOC-STRING] [OPTIONS-AND-METHODS...] &rest BODY)"
  157. (declare (indent 2) (doc-string 3))
  158. (let* ((doc (if (stringp (car-safe options-and-methods))
  159. (pop options-and-methods)))
  160. (declarations nil)
  161. (methods ())
  162. (options ())
  163. next-head)
  164. (while (progn (setq next-head (car-safe (car options-and-methods)))
  165. (or (keywordp next-head)
  166. (eq next-head 'declare)))
  167. (pcase next-head
  168. (`:documentation
  169. (when doc (error "Multiple doc strings for %S" name))
  170. (setq doc (cadr (pop options-and-methods))))
  171. (`declare
  172. (when declarations (error "Multiple ‘declare’ for %S" name))
  173. (setq declarations (pop options-and-methods)))
  174. (`:method (push (cdr (pop options-and-methods)) methods))
  175. (_ (push (pop options-and-methods) options))))
  176. (when options-and-methods
  177. ;; Anything remaining is assumed to be a default method body.
  178. (push `(,args ,@options-and-methods) methods))
  179. (when (eq 'setf (car-safe name))
  180. (require 'gv)
  181. (setq name (gv-setter (cadr name))))
  182. `(progn
  183. ,@(mapcar (lambda (declaration)
  184. (let ((f (cdr (assq (car declaration)
  185. defun-declarations-alist))))
  186. (cond
  187. (f (apply (car f) name args (cdr declaration)))
  188. (t (message "Warning: Unknown defun property ‘%S’ in %S"
  189. (car declaration) name)
  190. nil))))
  191. (cdr declarations))
  192. (defalias ',name
  193. (cl-generic-define ',name ',args ',(nreverse options))
  194. ,(help-add-fundoc-usage doc args))
  195. ,@(mapcar (lambda (method) `(cl-defmethod ,name ,@method))
  196. (nreverse methods)))))
  197. ;;;###autoload
  198. (defun cl-generic-define (name args options)
  199. (pcase-let* ((generic (cl-generic-ensure-function name))
  200. (`(,spec-args . ,_) (cl--generic-split-args args))
  201. (mandatory (mapcar #'car spec-args))
  202. (apo (assq :argument-precedence-order options)))
  203. (unless (fboundp name)
  204. ;; If the generic function was fmakunbound, throw away previous methods.
  205. (setf (cl--generic-dispatches generic) nil)
  206. (setf (cl--generic-method-table generic) nil))
  207. (when apo
  208. (dolist (arg (cdr apo))
  209. (let ((pos (memq arg mandatory)))
  210. (unless pos (error "%S is not a mandatory argument" arg))
  211. (let* ((argno (- (length mandatory) (length pos)))
  212. (dispatches (cl--generic-dispatches generic))
  213. (dispatch (or (assq argno dispatches) (list argno))))
  214. (setf (cl--generic-dispatches generic)
  215. (cons dispatch (delq dispatch dispatches)))))))
  216. (setf (cl--generic-options generic) options)
  217. (cl--generic-make-function generic)))
  218. (defmacro cl-generic-current-method-specializers ()
  219. "List of (VAR . TYPE) where TYPE is var's specializer.
  220. This macro can only be used within the lexical scope of a cl-generic method."
  221. (error "cl-generic-current-method-specializers used outside of a method"))
  222. (eval-and-compile ;Needed while compiling the cl-defmethod calls below!
  223. (defun cl--generic-fgrep (vars sexp) ;Copied from pcase.el.
  224. "Check which of the symbols VARS appear in SEXP."
  225. (let ((res '()))
  226. (while (consp sexp)
  227. (dolist (var (cl--generic-fgrep vars (pop sexp)))
  228. (unless (memq var res) (push var res))))
  229. (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
  230. res))
  231. (defun cl--generic-split-args (args)
  232. "Return (SPEC-ARGS . PLAIN-ARGS)."
  233. (let ((plain-args ())
  234. (specializers nil)
  235. (mandatory t))
  236. (dolist (arg args)
  237. (push (pcase arg
  238. ((or '&optional '&rest '&key) (setq mandatory nil) arg)
  239. ('&context
  240. (unless mandatory
  241. (error "&context not immediately after mandatory args"))
  242. (setq mandatory 'context) nil)
  243. ((let 'nil mandatory) arg)
  244. ((let 'context mandatory)
  245. (unless (consp arg)
  246. (error "Invalid &context arg: %S" arg))
  247. (push `((&context . ,(car arg)) . ,(cadr arg)) specializers)
  248. nil)
  249. (`(,name . ,type)
  250. (push (cons name (car type)) specializers)
  251. name)
  252. (_
  253. (push (cons arg t) specializers)
  254. arg))
  255. plain-args))
  256. (cons (nreverse specializers)
  257. (nreverse (delq nil plain-args)))))
  258. (defun cl--generic-lambda (args body)
  259. "Make the lambda expression for a method with ARGS and BODY."
  260. (pcase-let* ((`(,spec-args . ,plain-args)
  261. (cl--generic-split-args args))
  262. (fun `(cl-function (lambda ,plain-args ,@body)))
  263. (macroenv (cons `(cl-generic-current-method-specializers
  264. . ,(lambda () spec-args))
  265. macroexpand-all-environment)))
  266. (require 'cl-lib) ;Needed to expand `cl-flet' and `cl-function'.
  267. ;; First macroexpand away the cl-function stuff (e.g. &key and
  268. ;; destructuring args, `declare' and whatnot).
  269. (pcase (macroexpand fun macroenv)
  270. (`#'(lambda ,args . ,body)
  271. (let* ((parsed-body (macroexp-parse-body body))
  272. (cnm (make-symbol "cl--cnm"))
  273. (nmp (make-symbol "cl--nmp"))
  274. (nbody (macroexpand-all
  275. `(cl-flet ((cl-call-next-method ,cnm)
  276. (cl-next-method-p ,nmp))
  277. ,@(cdr parsed-body))
  278. macroenv))
  279. ;; FIXME: Rather than `grep' after the fact, the
  280. ;; macroexpansion should directly set some flag when cnm
  281. ;; is used.
  282. ;; FIXME: Also, optimize the case where call-next-method is
  283. ;; only called with explicit arguments.
  284. (uses-cnm (cl--generic-fgrep (list cnm nmp) nbody)))
  285. (cons (not (not uses-cnm))
  286. `#'(lambda (,@(if uses-cnm (list cnm)) ,@args)
  287. ,@(car parsed-body)
  288. ,(if (not (memq nmp uses-cnm))
  289. nbody
  290. `(let ((,nmp (lambda ()
  291. (cl--generic-isnot-nnm-p ,cnm))))
  292. ,nbody))))))
  293. (f (error "Unexpected macroexpansion result: %S" f))))))
  294. ;;;###autoload
  295. (defmacro cl-defmethod (name args &rest body)
  296. "Define a new method for generic function NAME.
  297. I.e. it defines the implementation of NAME to use for invocations where the
  298. value of the dispatch argument matches the specified TYPE.
  299. The dispatch argument has to be one of the mandatory arguments, and
  300. all methods of NAME have to use the same argument for dispatch.
  301. The dispatch argument and TYPE are specified in ARGS where the corresponding
  302. formal argument appears as (VAR TYPE) rather than just VAR.
  303. The optional second argument QUALIFIER is a specifier that
  304. modifies how the method is combined with other methods, including:
  305. :before - Method will be called before the primary
  306. :after - Method will be called after the primary
  307. :around - Method will be called around everything else
  308. The absence of QUALIFIER means this is a \"primary\" method.
  309. Other than a type, TYPE can also be of the form `(eql VAL)' in
  310. which case this method will be invoked when the argument is `eql' to VAL.
  311. \(fn NAME [QUALIFIER] ARGS &rest [DOCSTRING] BODY)"
  312. (declare (doc-string 3) (indent 2)
  313. (debug
  314. (&define ; this means we are defining something
  315. [&or name ("setf" :name setf name)]
  316. ;; ^^ This is the methods symbol
  317. [ &optional keywordp ] ; this is key :before etc
  318. list ; arguments
  319. [ &optional stringp ] ; documentation string
  320. def-body))) ; part to be debugged
  321. (let ((qualifiers nil))
  322. (while (not (listp args))
  323. (push args qualifiers)
  324. (setq args (pop body)))
  325. (when (eq 'setf (car-safe name))
  326. (require 'gv)
  327. (setq name (gv-setter (cadr name))))
  328. (pcase-let* ((`(,uses-cnm . ,fun) (cl--generic-lambda args body)))
  329. `(progn
  330. ,(and (get name 'byte-obsolete-info)
  331. (or (not (fboundp 'byte-compile-warning-enabled-p))
  332. (byte-compile-warning-enabled-p 'obsolete))
  333. (let* ((obsolete (get name 'byte-obsolete-info)))
  334. (macroexp--warn-and-return
  335. (macroexp--obsolete-warning name obsolete "generic function")
  336. nil)))
  337. ;; You could argue that `defmethod' modifies rather than defines the
  338. ;; function, so warnings like "not known to be defined" are fair game.
  339. ;; But in practice, it's common to use `cl-defmethod'
  340. ;; without a previous `cl-defgeneric'.
  341. (declare-function ,name "")
  342. (cl-generic-define-method ',name ',(nreverse qualifiers) ',args
  343. ,uses-cnm ,fun)))))
  344. (defun cl--generic-member-method (specializers qualifiers methods)
  345. (while
  346. (and methods
  347. (let ((m (car methods)))
  348. (not (and (equal (cl--generic-method-specializers m) specializers)
  349. (equal (cl--generic-method-qualifiers m) qualifiers)))))
  350. (setq methods (cdr methods)))
  351. methods)
  352. ;;;###autoload
  353. (defun cl-generic-define-method (name qualifiers args uses-cnm function)
  354. (pcase-let*
  355. ((generic (cl-generic-ensure-function name))
  356. (`(,spec-args . ,_) (cl--generic-split-args args))
  357. (specializers (mapcar (lambda (spec-arg)
  358. (if (eq '&context (car-safe (car spec-arg)))
  359. spec-arg (cdr spec-arg)))
  360. spec-args))
  361. (method (cl--generic-make-method
  362. specializers qualifiers uses-cnm function))
  363. (mt (cl--generic-method-table generic))
  364. (me (cl--generic-member-method specializers qualifiers mt))
  365. (dispatches (cl--generic-dispatches generic))
  366. (i 0))
  367. (dolist (spec-arg spec-args)
  368. (let* ((key (if (eq '&context (car-safe (car spec-arg)))
  369. (car spec-arg) i))
  370. (generalizers (cl-generic-generalizers (cdr spec-arg)))
  371. (x (assoc key dispatches)))
  372. (unless x
  373. (setq x (cons key (cl-generic-generalizers t)))
  374. (setf (cl--generic-dispatches generic)
  375. (setq dispatches (cons x dispatches))))
  376. (dolist (generalizer generalizers)
  377. (unless (member generalizer (cdr x))
  378. (setf (cdr x)
  379. (sort (cons generalizer (cdr x))
  380. (lambda (x y)
  381. (> (cl--generic-generalizer-priority x)
  382. (cl--generic-generalizer-priority y)))))))
  383. (setq i (1+ i))))
  384. ;; We used to (setcar me method), but that can cause false positives in
  385. ;; the hash-consing table of the method-builder (bug#20644).
  386. ;; See the related FIXME in cl--generic-build-combined-method.
  387. (setf (cl--generic-method-table generic) (cons method (delq (car me) mt)))
  388. (cl-pushnew `(cl-defmethod . (,(cl--generic-name generic) . ,specializers))
  389. current-load-list :test #'equal)
  390. ;; FIXME: Try to avoid re-constructing a new function if the old one
  391. ;; is still valid (e.g. still empty method cache)?
  392. (let ((gfun (cl--generic-make-function generic))
  393. ;; Prevent `defalias' from recording this as the definition site of
  394. ;; the generic function.
  395. current-load-list)
  396. ;; For aliases, cl--generic-name gives us the actual name.
  397. (let ((purify-flag
  398. ;; BEWARE! Don't purify this function definition, since that leads
  399. ;; to memory corruption if the hash-tables it holds are modified
  400. ;; (the GC doesn't trace those pointers).
  401. nil))
  402. ;; But do use `defalias', so that it interacts properly with nadvice,
  403. ;; e.g. for tracing/debug-on-entry.
  404. (defalias (cl--generic-name generic) gfun)))))
  405. (defmacro cl--generic-with-memoization (place &rest code)
  406. (declare (indent 1) (debug t))
  407. (gv-letplace (getter setter) place
  408. `(or ,getter
  409. ,(macroexp-let2 nil val (macroexp-progn code)
  410. `(progn
  411. ,(funcall setter val)
  412. ,val)))))
  413. (defvar cl--generic-dispatchers (make-hash-table :test #'equal))
  414. (defun cl--generic-get-dispatcher (dispatch)
  415. (cl--generic-with-memoization
  416. (gethash dispatch cl--generic-dispatchers)
  417. ;; (message "cl--generic-get-dispatcher (%S)" dispatch)
  418. (let* ((dispatch-arg (car dispatch))
  419. (generalizers (cdr dispatch))
  420. (lexical-binding t)
  421. (tagcodes
  422. (mapcar (lambda (generalizer)
  423. (funcall (cl--generic-generalizer-tagcode-function
  424. generalizer)
  425. 'arg))
  426. generalizers))
  427. (typescodes
  428. (mapcar
  429. (lambda (generalizer)
  430. `(funcall ',(cl--generic-generalizer-specializers-function
  431. generalizer)
  432. ,(funcall (cl--generic-generalizer-tagcode-function
  433. generalizer)
  434. 'arg)))
  435. generalizers))
  436. (tag-exp
  437. ;; Minor optimization: since this tag-exp is
  438. ;; only used to lookup the method-cache, it
  439. ;; doesn't matter if the default value is some
  440. ;; constant or nil.
  441. `(or ,@(if (macroexp-const-p (car (last tagcodes)))
  442. (butlast tagcodes)
  443. tagcodes)))
  444. (fixedargs '(arg))
  445. (dispatch-idx dispatch-arg)
  446. (bindings nil))
  447. (when (eq '&context (car-safe dispatch-arg))
  448. (setq bindings `((arg ,(cdr dispatch-arg))))
  449. (setq fixedargs nil)
  450. (setq dispatch-idx 0))
  451. (dotimes (i dispatch-idx)
  452. (push (make-symbol (format "arg%d" (- dispatch-idx i 1))) fixedargs))
  453. ;; FIXME: For generic functions with a single method (or with 2 methods,
  454. ;; one of which always matches), using a tagcode + hash-table is
  455. ;; overkill: better just use a `cl-typep' test.
  456. (byte-compile
  457. `(lambda (generic dispatches-left methods)
  458. (let ((method-cache (make-hash-table :test #'eql)))
  459. (lambda (,@fixedargs &rest args)
  460. (let ,bindings
  461. (apply (cl--generic-with-memoization
  462. (gethash ,tag-exp method-cache)
  463. (cl--generic-cache-miss
  464. generic ',dispatch-arg dispatches-left methods
  465. ,(if (cdr typescodes)
  466. `(append ,@typescodes) (car typescodes))))
  467. ,@fixedargs args)))))))))
  468. (defun cl--generic-make-function (generic)
  469. (cl--generic-make-next-function generic
  470. (cl--generic-dispatches generic)
  471. (cl--generic-method-table generic)))
  472. (defun cl--generic-make-next-function (generic dispatches methods)
  473. (let* ((dispatch
  474. (progn
  475. (while (and dispatches
  476. (let ((x (nth 1 (car dispatches))))
  477. ;; No need to dispatch for t specializers.
  478. (or (null x) (equal x cl--generic-t-generalizer))))
  479. (setq dispatches (cdr dispatches)))
  480. (pop dispatches))))
  481. (if (not (and dispatch
  482. ;; If there's no method left, there's no point checking
  483. ;; further arguments.
  484. methods))
  485. (cl--generic-build-combined-method generic methods)
  486. (let ((dispatcher (cl--generic-get-dispatcher dispatch)))
  487. (funcall dispatcher generic dispatches methods)))))
  488. (defvar cl--generic-combined-method-memoization
  489. (make-hash-table :test #'equal :weakness 'value)
  490. "Table storing previously built combined-methods.
  491. This is particularly useful when many different tags select the same set
  492. of methods, since this table then allows us to share a single combined-method
  493. for all those different tags in the method-cache.")
  494. (define-error 'cl--generic-cyclic-definition "Cyclic definition: %S")
  495. (defun cl--generic-build-combined-method (generic methods)
  496. (if (null methods)
  497. ;; Special case needed to fix a circularity during bootstrap.
  498. (cl--generic-standard-method-combination generic methods)
  499. (let ((f
  500. (cl--generic-with-memoization
  501. ;; FIXME: Since the fields of `generic' are modified, this
  502. ;; hash-table won't work right, because the hashes will change!
  503. ;; It's not terribly serious, but reduces the effectiveness of
  504. ;; the table.
  505. (gethash (cons generic methods)
  506. cl--generic-combined-method-memoization)
  507. (puthash (cons generic methods) :cl--generic--under-construction
  508. cl--generic-combined-method-memoization)
  509. (condition-case nil
  510. (cl-generic-combine-methods generic methods)
  511. ;; Special case needed to fix a circularity during bootstrap.
  512. (cl--generic-cyclic-definition
  513. (cl--generic-standard-method-combination generic methods))))))
  514. (if (eq f :cl--generic--under-construction)
  515. (signal 'cl--generic-cyclic-definition
  516. (list (cl--generic-name generic)))
  517. f))))
  518. (defun cl--generic-no-next-method-function (generic method)
  519. (lambda (&rest args)
  520. (apply #'cl-no-next-method generic method args)))
  521. (defun cl-generic-call-method (generic method &optional fun)
  522. "Return a function that calls METHOD.
  523. FUN is the function that should be called when METHOD calls
  524. `call-next-method'."
  525. (if (not (cl--generic-method-uses-cnm method))
  526. (cl--generic-method-function method)
  527. (let ((met-fun (cl--generic-method-function method))
  528. (next (or fun (cl--generic-no-next-method-function
  529. generic method))))
  530. (lambda (&rest args)
  531. (apply met-fun
  532. ;; FIXME: This sucks: passing just `next' would
  533. ;; be a lot more efficient than the lambda+apply
  534. ;; quasi-η, but we need this to implement the
  535. ;; "if call-next-method is called with no
  536. ;; arguments, then use the previous arguments".
  537. (lambda (&rest cnm-args)
  538. (apply next (or cnm-args args)))
  539. args)))))
  540. ;; Standard CLOS name.
  541. (defalias 'cl-method-qualifiers #'cl--generic-method-qualifiers)
  542. (defun cl--generic-standard-method-combination (generic methods)
  543. (let ((mets-by-qual ()))
  544. (dolist (method methods)
  545. (let ((qualifiers (cl-method-qualifiers method)))
  546. (if (eq (car qualifiers) :extra) (setq qualifiers (cddr qualifiers)))
  547. (unless (member qualifiers '(() (:after) (:before) (:around)))
  548. (error "Unsupported qualifiers in function %S: %S"
  549. (cl--generic-name generic) qualifiers))
  550. (push method (alist-get (car qualifiers) mets-by-qual))))
  551. (cond
  552. ((null mets-by-qual)
  553. (lambda (&rest args)
  554. (apply #'cl-no-applicable-method generic args)))
  555. ((null (alist-get nil mets-by-qual))
  556. (lambda (&rest args)
  557. (apply #'cl-no-primary-method generic args)))
  558. (t
  559. (let* ((fun nil)
  560. (ab-call (lambda (m) (cl-generic-call-method generic m)))
  561. (before
  562. (mapcar ab-call (reverse (cdr (assoc :before mets-by-qual)))))
  563. (after (mapcar ab-call (cdr (assoc :after mets-by-qual)))))
  564. (dolist (method (cdr (assoc nil mets-by-qual)))
  565. (setq fun (cl-generic-call-method generic method fun)))
  566. (when (or after before)
  567. (let ((next fun))
  568. (setq fun (lambda (&rest args)
  569. (dolist (bf before)
  570. (apply bf args))
  571. (prog1
  572. (apply next args)
  573. (dolist (af after)
  574. (apply af args)))))))
  575. (dolist (method (cdr (assoc :around mets-by-qual)))
  576. (setq fun (cl-generic-call-method generic method fun)))
  577. fun)))))
  578. (defun cl--generic-cache-miss (generic
  579. dispatch-arg dispatches-left methods-left types)
  580. (let ((methods '()))
  581. (dolist (method methods-left)
  582. (let* ((specializer (or (if (integerp dispatch-arg)
  583. (nth dispatch-arg
  584. (cl--generic-method-specializers method))
  585. (cdr (assoc dispatch-arg
  586. (cl--generic-method-specializers method))))
  587. t))
  588. (m (member specializer types)))
  589. (when m
  590. (push (cons (length m) method) methods))))
  591. ;; Sort the methods, most specific first.
  592. ;; It would be tempting to sort them once and for all in the method-table
  593. ;; rather than here, but the order might depend on the actual argument
  594. ;; (e.g. for multiple inheritance with defclass).
  595. (setq methods (nreverse (mapcar #'cdr (sort methods #'car-less-than-car))))
  596. (cl--generic-make-next-function generic dispatches-left methods)))
  597. (cl-defgeneric cl-generic-generalizers (specializer)
  598. "Return a list of generalizers for a given SPECIALIZER.
  599. To each kind of `specializer', corresponds a `generalizer' which describes
  600. how to extract a \"tag\" from an object which will then let us check if this
  601. object matches the specializer. A typical example of a \"tag\" would be the
  602. type of an object. It's called a `generalizer' because it
  603. takes a specific object and returns a more general approximation,
  604. denoting a set of objects to which it belongs.
  605. A generalizer gives us the chunk of code which the
  606. dispatch function needs to use to extract the \"tag\" of an object, as well
  607. as a function which turns this tag into an ordered list of
  608. `specializers' that this object matches.
  609. The code which extracts the tag should be as fast as possible.
  610. The tags should be chosen according to the following rules:
  611. - The tags should not be too specific: similar objects which match the
  612. same list of specializers should ideally use the same (`eql') tag.
  613. This insures that the cached computation of the applicable
  614. methods for one object can be reused for other objects.
  615. - Corollary: objects which don't match any of the relevant specializers
  616. should ideally all use the same tag (typically nil).
  617. This insures that this cache does not grow unnecessarily large.
  618. - Two different generalizers G1 and G2 should not use the same tag
  619. unless they use it for the same set of objects. IOW, if G1.tag(X1) =
  620. G2.tag(X2) then G1.tag(X1) = G2.tag(X1) = G1.tag(X2) = G2.tag(X2).
  621. - If G1.priority > G2.priority and G1.tag(X1) = G1.tag(X2) and this tag is
  622. non-nil, then you have to make sure that the G2.tag(X1) = G2.tag(X2).
  623. This is because the method-cache is only indexed with the first non-nil
  624. tag (by order of decreasing priority).")
  625. (cl-defgeneric cl-generic-combine-methods (generic methods)
  626. "Build the effective method made of METHODS.
  627. It should return a function that expects the same arguments as the methods, and
  628. calls those methods in some appropriate order.
  629. GENERIC is the generic function (mostly used for its name).
  630. METHODS is the list of the selected methods.
  631. The METHODS list is sorted from most specific first to most generic last.
  632. The function can use `cl-generic-call-method' to create functions that call those
  633. methods.")
  634. ;; Temporary definition to let the next defmethod succeed.
  635. (fset 'cl-generic-generalizers
  636. (lambda (_specializer) (list cl--generic-t-generalizer)))
  637. (fset 'cl-generic-combine-methods #'cl--generic-standard-method-combination)
  638. (cl-defmethod cl-generic-generalizers (specializer)
  639. "Support for the catch-all t specializer."
  640. (if (eq specializer t) (list cl--generic-t-generalizer)
  641. (error "Unknown specializer %S" specializer)))
  642. (eval-when-compile
  643. ;; This macro is brittle and only really important in order to be
  644. ;; able to preload cl-generic without also preloading the byte-compiler,
  645. ;; So we use `eval-when-compile' so as not keep it available longer than
  646. ;; strictly needed.
  647. (defmacro cl--generic-prefill-dispatchers (arg-or-context specializer)
  648. (unless (integerp arg-or-context)
  649. (setq arg-or-context `(&context . ,arg-or-context)))
  650. (unless (fboundp 'cl--generic-get-dispatcher)
  651. (require 'cl-generic))
  652. (let ((fun (cl--generic-get-dispatcher
  653. `(,arg-or-context ,@(cl-generic-generalizers specializer)
  654. ,cl--generic-t-generalizer))))
  655. ;; Recompute dispatch at run-time, since the generalizers may be slightly
  656. ;; different (e.g. byte-compiled rather than interpreted).
  657. ;; FIXME: There is a risk that the run-time generalizer is not equivalent
  658. ;; to the compile-time one, in which case `fun' may not be correct
  659. ;; any more!
  660. `(let ((dispatch `(,',arg-or-context
  661. ,@(cl-generic-generalizers ',specializer)
  662. ,cl--generic-t-generalizer)))
  663. ;; (message "Prefilling for %S with \n%S" dispatch ',fun)
  664. (puthash dispatch ',fun cl--generic-dispatchers)))))
  665. (cl-defmethod cl-generic-combine-methods (generic methods)
  666. "Standard support for :after, :before, :around, and `:extra NAME' qualifiers."
  667. (cl--generic-standard-method-combination generic methods))
  668. (defconst cl--generic-nnm-sample (cl--generic-no-next-method-function t t))
  669. (defconst cl--generic-cnm-sample
  670. (funcall (cl--generic-build-combined-method
  671. nil (list (cl--generic-make-method () () t #'identity)))))
  672. (defun cl--generic-isnot-nnm-p (cnm)
  673. "Return non-nil if CNM is the function that calls `cl-no-next-method'."
  674. ;; ¡Big Gross Ugly Hack!
  675. ;; `next-method-p' just sucks, we should let it die. But EIEIO did support
  676. ;; it, and some packages use it, so we need to support it.
  677. (catch 'found
  678. (cl-assert (function-equal cnm cl--generic-cnm-sample))
  679. (if (byte-code-function-p cnm)
  680. (let ((cnm-constants (aref cnm 2))
  681. (sample-constants (aref cl--generic-cnm-sample 2)))
  682. (dotimes (i (length sample-constants))
  683. (when (function-equal (aref sample-constants i)
  684. cl--generic-nnm-sample)
  685. (throw 'found
  686. (not (function-equal (aref cnm-constants i)
  687. cl--generic-nnm-sample))))))
  688. (cl-assert (eq 'closure (car-safe cl--generic-cnm-sample)))
  689. (let ((cnm-env (cadr cnm)))
  690. (dolist (vb (cadr cl--generic-cnm-sample))
  691. (when (function-equal (cdr vb) cl--generic-nnm-sample)
  692. (throw 'found
  693. (not (function-equal (cdar cnm-env)
  694. cl--generic-nnm-sample))))
  695. (setq cnm-env (cdr cnm-env)))))
  696. (error "Haven't found no-next-method-sample in cnm-sample")))
  697. ;;; Define some pre-defined generic functions, used internally.
  698. (define-error 'cl-no-method "No method for %S")
  699. (define-error 'cl-no-next-method "No next method for %S" 'cl-no-method)
  700. (define-error 'cl-no-primary-method "No primary method for %S" 'cl-no-method)
  701. (define-error 'cl-no-applicable-method "No applicable method for %S"
  702. 'cl-no-method)
  703. (cl-defgeneric cl-no-next-method (generic method &rest args)
  704. "Function called when `cl-call-next-method' finds no next method."
  705. (signal 'cl-no-next-method `(,(cl--generic-name generic) ,method ,@args)))
  706. (cl-defgeneric cl-no-applicable-method (generic &rest args)
  707. "Function called when a method call finds no applicable method."
  708. (signal 'cl-no-applicable-method `(,(cl--generic-name generic) ,@args)))
  709. (cl-defgeneric cl-no-primary-method (generic &rest args)
  710. "Function called when a method call finds no primary method."
  711. (signal 'cl-no-primary-method `(,(cl--generic-name generic) ,@args)))
  712. (defun cl-call-next-method (&rest _args)
  713. "Function to call the next applicable method.
  714. Can only be used from within the lexical body of a primary or around method."
  715. (error "cl-call-next-method only allowed inside primary and around methods"))
  716. (defun cl-next-method-p ()
  717. "Return non-nil if there is a next method.
  718. Can only be used from within the lexical body of a primary or around method."
  719. (declare (obsolete "make sure there's always a next method, or catch `cl-no-next-method' instead" "25.1"))
  720. (error "cl-next-method-p only allowed inside primary and around methods"))
  721. ;;;###autoload
  722. (defun cl-find-method (generic qualifiers specializers)
  723. (car (cl--generic-member-method
  724. specializers qualifiers
  725. (cl--generic-method-table (cl--generic generic)))))
  726. ;;; Add support for describe-function
  727. (defun cl--generic-search-method (met-name)
  728. "For `find-function-regexp-alist'. Searches for a cl-defmethod.
  729. MET-NAME is a cons (SYMBOL . SPECIALIZERS)."
  730. (let ((base-re (concat "(\\(?:cl-\\)?defmethod[ \t]+"
  731. (regexp-quote (format "%s" (car met-name)))
  732. "\\_>")))
  733. (or
  734. (re-search-forward
  735. (concat base-re "[^&\"\n]*"
  736. (mapconcat (lambda (specializer)
  737. (regexp-quote
  738. (format "%S" (if (consp specializer)
  739. (nth 1 specializer) specializer))))
  740. (remq t (cdr met-name))
  741. "[ \t\n]*)[^&\"\n]*"))
  742. nil t)
  743. (re-search-forward base-re nil t))))
  744. ;; WORKAROUND: This can't be a defconst due to bug#21237.
  745. (defvar cl--generic-find-defgeneric-regexp "(\\(?:cl-\\)?defgeneric[ \t]+%s\\>")
  746. (with-eval-after-load 'find-func
  747. (defvar find-function-regexp-alist)
  748. (add-to-list 'find-function-regexp-alist
  749. `(cl-defmethod . ,#'cl--generic-search-method))
  750. (add-to-list 'find-function-regexp-alist
  751. `(cl-defgeneric . cl--generic-find-defgeneric-regexp)))
  752. (defun cl--generic-method-info (method)
  753. (let* ((specializers (cl--generic-method-specializers method))
  754. (qualifiers (cl--generic-method-qualifiers method))
  755. (uses-cnm (cl--generic-method-uses-cnm method))
  756. (function (cl--generic-method-function method))
  757. (args (help-function-arglist function 'names))
  758. (docstring (documentation function))
  759. (qual-string
  760. (if (null qualifiers) ""
  761. (cl-assert (consp qualifiers))
  762. (let ((s (prin1-to-string qualifiers)))
  763. (concat (substring s 1 -1) " "))))
  764. (doconly (if docstring
  765. (let ((split (help-split-fundoc docstring nil)))
  766. (if split (cdr split) docstring))))
  767. (combined-args ()))
  768. (if uses-cnm (setq args (cdr args)))
  769. (dolist (specializer specializers)
  770. (let ((arg (if (eq '&rest (car args))
  771. (intern (format "arg%d" (length combined-args)))
  772. (pop args))))
  773. (push (if (eq specializer t) arg (list arg specializer))
  774. combined-args)))
  775. (setq combined-args (append (nreverse combined-args) args))
  776. (list qual-string combined-args doconly)))
  777. (add-hook 'help-fns-describe-function-functions #'cl--generic-describe)
  778. (defun cl--generic-describe (function)
  779. ;; Supposedly this is called from help-fns, so help-fns should be loaded at
  780. ;; this point.
  781. (declare-function help-fns-short-filename "help-fns" (filename))
  782. (let ((generic (if (symbolp function) (cl--generic function))))
  783. (when generic
  784. (require 'help-mode) ;Needed for `help-function-def' button!
  785. (save-excursion
  786. (insert "\n\nThis is a generic function.\n\n")
  787. (insert (propertize "Implementations:\n\n" 'face 'bold))
  788. ;; Loop over fanciful generics
  789. (dolist (method (cl--generic-method-table generic))
  790. (let* ((info (cl--generic-method-info method)))
  791. ;; FIXME: Add hyperlinks for the types as well.
  792. (insert (format "%s%S" (nth 0 info) (nth 1 info)))
  793. (let* ((met-name (cons function
  794. (cl--generic-method-specializers method)))
  795. (file (find-lisp-object-file-name met-name 'cl-defmethod)))
  796. (when file
  797. (insert (substitute-command-keys " in ‘"))
  798. (help-insert-xref-button (help-fns-short-filename file)
  799. 'help-function-def met-name file
  800. 'cl-defmethod)
  801. (insert (substitute-command-keys "’.\n"))))
  802. (insert "\n" (or (nth 2 info) "Undocumented") "\n\n")))))))
  803. (defun cl--generic-specializers-apply-to-type-p (specializers type)
  804. "Return non-nil if a method with SPECIALIZERS applies to TYPE."
  805. (let ((applies nil))
  806. (dolist (specializer specializers)
  807. (if (memq (car-safe specializer) '(subclass eieio--static))
  808. (setq specializer (nth 1 specializer)))
  809. ;; Don't include the methods that are "too generic", such as those
  810. ;; applying to `eieio-default-superclass'.
  811. (and (not (memq specializer '(t eieio-default-superclass)))
  812. (or (equal type specializer)
  813. (when (symbolp specializer)
  814. (let ((sclass (cl--find-class specializer))
  815. (tclass (cl--find-class type)))
  816. (when (and sclass tclass)
  817. (member specializer (cl--generic-class-parents tclass))))))
  818. (setq applies t)))
  819. applies))
  820. (defun cl--generic-all-functions (&optional type)
  821. "Return a list of all generic functions.
  822. Optional TYPE argument returns only those functions that contain
  823. methods for TYPE."
  824. (let ((l nil))
  825. (mapatoms
  826. (lambda (symbol)
  827. (let ((generic (and (fboundp symbol) (cl--generic symbol))))
  828. (and generic
  829. (catch 'found
  830. (if (null type) (throw 'found t))
  831. (dolist (method (cl--generic-method-table generic))
  832. (if (cl--generic-specializers-apply-to-type-p
  833. (cl--generic-method-specializers method) type)
  834. (throw 'found t))))
  835. (push symbol l)))))
  836. l))
  837. (defun cl--generic-method-documentation (function type)
  838. "Return info for all methods of FUNCTION (a symbol) applicable to TYPE.
  839. The value returned is a list of elements of the form
  840. \(QUALIFIERS ARGS DOC)."
  841. (let ((generic (cl--generic function))
  842. (docs ()))
  843. (when generic
  844. (dolist (method (cl--generic-method-table generic))
  845. (when (cl--generic-specializers-apply-to-type-p
  846. (cl--generic-method-specializers method) type)
  847. (push (cl--generic-method-info method) docs))))
  848. docs))
  849. ;;; Support for (head <val>) specializers.
  850. ;; For both the `eql' and the `head' specializers, the dispatch
  851. ;; is unsatisfactory. Basically, in the "common&fast case", we end up doing
  852. ;;
  853. ;; (let ((tag (gethash value <tagcode-hashtable>)))
  854. ;; (funcall (gethash tag <method-cache>)))
  855. ;;
  856. ;; whereas we'd like to just do
  857. ;;
  858. ;; (funcall (gethash value <method-cache>)))
  859. ;;
  860. ;; but the problem is that the method-cache is normally "open ended", so
  861. ;; a nil means "not computed yet" and if we bump into it, we dutifully fill the
  862. ;; corresponding entry, whereas we'd want to just fallback on some default
  863. ;; effective method (so as not to fill the cache with lots of redundant
  864. ;; entries).
  865. (defvar cl--generic-head-used (make-hash-table :test #'eql))
  866. (defconst cl--generic-head-generalizer
  867. (cl-generic-make-generalizer
  868. 80 (lambda (name) `(gethash (car-safe ,name) cl--generic-head-used))
  869. (lambda (tag) (if (eq (car-safe tag) 'head) (list tag)))))
  870. (cl-defmethod cl-generic-generalizers :extra "head" (specializer)
  871. "Support for the `(head VAL)' specializers."
  872. ;; We have to implement `head' here using the :extra qualifier,
  873. ;; since we can't use the `head' specializer to implement itself.
  874. (if (not (eq (car-safe specializer) 'head))
  875. (cl-call-next-method)
  876. (cl--generic-with-memoization
  877. (gethash (cadr specializer) cl--generic-head-used) specializer)
  878. (list cl--generic-head-generalizer)))
  879. (cl--generic-prefill-dispatchers 0 (head eql))
  880. ;;; Support for (eql <val>) specializers.
  881. (defvar cl--generic-eql-used (make-hash-table :test #'eql))
  882. (defconst cl--generic-eql-generalizer
  883. (cl-generic-make-generalizer
  884. 100 (lambda (name) `(gethash ,name cl--generic-eql-used))
  885. (lambda (tag) (if (eq (car-safe tag) 'eql) (list tag)))))
  886. (cl-defmethod cl-generic-generalizers ((specializer (head eql)))
  887. "Support for the `(eql VAL)' specializers."
  888. (puthash (cadr specializer) specializer cl--generic-eql-used)
  889. (list cl--generic-eql-generalizer))
  890. (cl--generic-prefill-dispatchers 0 (eql nil))
  891. (cl--generic-prefill-dispatchers window-system (eql nil))
  892. ;;; Support for cl-defstructs specializers.
  893. (defun cl--generic-struct-tag (name)
  894. ;; It's tempting to use (and (vectorp ,name) (aref ,name 0))
  895. ;; but that would suffer from some problems:
  896. ;; - the vector may have size 0.
  897. ;; - when called on an actual vector (rather than an object), we'd
  898. ;; end up returning an arbitrary value, possibly colliding with
  899. ;; other tagcode's values.
  900. ;; - it can also result in returning all kinds of irrelevant
  901. ;; values which would end up filling up the method-cache with
  902. ;; lots of irrelevant/redundant entries.
  903. ;; FIXME: We could speed this up by introducing a dedicated
  904. ;; vector type at the C level, so we could do something like
  905. ;; (and (vector-objectp ,name) (aref ,name 0))
  906. `(and (vectorp ,name)
  907. (> (length ,name) 0)
  908. (let ((tag (aref ,name 0)))
  909. (and (symbolp tag)
  910. (eq (symbol-function tag) :quick-object-witness-check)
  911. tag))))
  912. (defun cl--generic-class-parents (class)
  913. (let ((parents ())
  914. (classes (list class)))
  915. ;; BFS precedence. FIXME: Use a topological sort.
  916. (while (let ((class (pop classes)))
  917. (cl-pushnew (cl--class-name class) parents)
  918. (setq classes
  919. (append classes
  920. (cl--class-parents class)))))
  921. (nreverse parents)))
  922. (defun cl--generic-struct-specializers (tag)
  923. (and (symbolp tag) (boundp tag)
  924. (let ((class (symbol-value tag)))
  925. (when (cl-typep class 'cl-structure-class)
  926. (cl--generic-class-parents class)))))
  927. (defconst cl--generic-struct-generalizer
  928. (cl-generic-make-generalizer
  929. 50 #'cl--generic-struct-tag
  930. #'cl--generic-struct-specializers))
  931. (cl-defmethod cl-generic-generalizers :extra "cl-struct" (type)
  932. "Support for dispatch on cl-struct types."
  933. (or
  934. (when (symbolp type)
  935. ;; Use the "cl--struct-class*" (inlinable) functions/macros rather than
  936. ;; the "cl-struct-*" variants which aren't inlined, so that dispatch can
  937. ;; take place without requiring cl-lib.
  938. (let ((class (cl--find-class type)))
  939. (and (cl-typep class 'cl-structure-class)
  940. (or (null (cl--struct-class-type class))
  941. (error "Can't dispatch on cl-struct %S: type is %S"
  942. type (cl--struct-class-type class)))
  943. (progn (cl-assert (null (cl--struct-class-named class))) t)
  944. (list cl--generic-struct-generalizer))))
  945. (cl-call-next-method)))
  946. (cl--generic-prefill-dispatchers 0 cl--generic-generalizer)
  947. ;;; Dispatch on "system types".
  948. (defconst cl--generic-typeof-types
  949. ;; Hand made from the source code of `type-of'.
  950. '((integer number) (symbol) (string array sequence) (cons list sequence)
  951. ;; Markers aren't `numberp', yet they are accepted wherever integers are
  952. ;; accepted, pretty much.
  953. (marker) (overlay) (float number) (window-configuration)
  954. (process) (window) (subr) (compiled-function) (buffer)
  955. (char-table array sequence)
  956. (bool-vector array sequence)
  957. (frame) (hash-table) (font-spec) (font-entity) (font-object)
  958. (vector array sequence)
  959. ;; Plus, hand made:
  960. (null symbol list sequence)
  961. (list sequence)
  962. (array sequence)
  963. (sequence)
  964. (number)))
  965. (defconst cl--generic-typeof-generalizer
  966. (cl-generic-make-generalizer
  967. ;; FIXME: We could also change `type-of' to return `null' for nil.
  968. 10 (lambda (name) `(if ,name (type-of ,name) 'null))
  969. (lambda (tag) (and (symbolp tag) (assq tag cl--generic-typeof-types)))))
  970. (cl-defmethod cl-generic-generalizers :extra "typeof" (type)
  971. "Support for dispatch on builtin types."
  972. ;; FIXME: Add support for other types accepted by `cl-typep' such
  973. ;; as `character', `atom', `face', `function', ...
  974. (or
  975. (and (assq type cl--generic-typeof-types)
  976. (progn
  977. (if (memq type '(vector array sequence))
  978. (message "‘%S’ also matches CL structs and EIEIO classes" type))
  979. (list cl--generic-typeof-generalizer)))
  980. (cl-call-next-method)))
  981. (cl--generic-prefill-dispatchers 0 integer)
  982. ;; Local variables:
  983. ;; generated-autoload-file: "cl-loaddefs.el"
  984. ;; End:
  985. (provide 'cl-generic)
  986. ;;; cl-generic.el ends here