PageRenderTime 61ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/lisp/emacs-lisp/eieio.el

http://github.com/davidswelt/aquamacs-emacs
Emacs Lisp | 1010 lines | 703 code | 141 blank | 166 comment | 30 complexity | 0b63d336593430e3ea3169af9fee46e2 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.0, GPL-2.0, AGPL-3.0
  1. ;;; eieio.el --- Enhanced Implementation of Emacs Interpreted Objects -*- lexical-binding:t -*-
  2. ;;; or maybe Eric's Implementation of Emacs Interpreted Objects
  3. ;; Copyright (C) 1995-1996, 1998-2016 Free Software Foundation, Inc.
  4. ;; Author: Eric M. Ludlam <zappo@gnu.org>
  5. ;; Version: 1.4
  6. ;; Keywords: OO, lisp
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;;
  20. ;; EIEIO is a series of Lisp routines which implements a subset of
  21. ;; CLOS, the Common Lisp Object System. In addition, EIEIO also adds
  22. ;; a few new features which help it integrate more strongly with the
  23. ;; Emacs running environment.
  24. ;;
  25. ;; See eieio.texi for complete documentation on using this package.
  26. ;;
  27. ;; Note: the implementation of the c3 algorithm is based on:
  28. ;; Kim Barrett et al.: A Monotonic Superclass Linearization for Dylan
  29. ;; Retrieved from:
  30. ;; http://192.220.96.201/dylan/linearization-oopsla96.html
  31. ;; @TODO - fix :initform to be a form, not a quoted value
  32. ;; @TODO - Prefix non-clos functions with `eieio-'.
  33. ;; TODO: better integrate CL's defstructs and classes. E.g. make it possible
  34. ;; to create a new class that inherits from a struct.
  35. ;;; Code:
  36. (defvar eieio-version "1.4"
  37. "Current version of EIEIO.")
  38. (defun eieio-version ()
  39. "Display the current version of EIEIO."
  40. (interactive)
  41. (message eieio-version))
  42. (require 'eieio-core)
  43. ;;; Defining a new class
  44. ;;
  45. (defmacro defclass (name superclasses slots &rest options-and-doc)
  46. "Define NAME as a new class derived from SUPERCLASS with SLOTS.
  47. OPTIONS-AND-DOC is used as the class' options and base documentation.
  48. SUPERCLASSES is a list of superclasses to inherit from, with SLOTS
  49. being the slots residing in that class definition. Supported tags are:
  50. :initform - Initializing form.
  51. :initarg - Tag used during initialization.
  52. :accessor - Tag used to create a function to access this slot.
  53. :allocation - Specify where the value is stored.
  54. Defaults to `:instance', but could also be `:class'.
  55. :writer - A function symbol which will `write' an object's slot.
  56. :reader - A function symbol which will `read' an object.
  57. :type - The type of data allowed in this slot (see `typep').
  58. :documentation
  59. - A string documenting use of this slot.
  60. The following are extensions on CLOS:
  61. :custom - When customizing an object, the custom :type. Public only.
  62. :label - A text string label used for a slot when customizing.
  63. :group - Name of a customization group this slot belongs in.
  64. :printer - A function to call to print the value of a slot.
  65. See `eieio-override-prin1' as an example.
  66. A class can also have optional options. These options happen in place
  67. of documentation (including a :documentation tag), in addition to
  68. documentation, or not at all. Supported options are:
  69. :documentation - The doc-string used for this class.
  70. Options added to EIEIO:
  71. :allow-nil-initform - Non-nil to skip typechecking of null initforms.
  72. :custom-groups - List of custom group names. Organizes slots into
  73. reasonable groups for customizations.
  74. :abstract - Non-nil to prevent instances of this class.
  75. If a string, use as an error string if someone does
  76. try to make an instance.
  77. :method-invocation-order
  78. - Control the method invocation order if there is
  79. multiple inheritance. Valid values are:
  80. :breadth-first - The default.
  81. :depth-first
  82. Options in CLOS not supported in EIEIO:
  83. :metaclass - Class to use in place of `standard-class'
  84. :default-initargs - Initargs to use when initializing new objects of
  85. this class.
  86. Due to the way class options are set up, you can add any tags you wish,
  87. and reference them using the function `class-option'."
  88. (declare (doc-string 4))
  89. (cl-check-type superclasses list)
  90. (cond ((and (stringp (car options-and-doc))
  91. (/= 1 (% (length options-and-doc) 2)))
  92. (error "Too many arguments to `defclass'"))
  93. ((and (symbolp (car options-and-doc))
  94. (/= 0 (% (length options-and-doc) 2)))
  95. (error "Too many arguments to `defclass'")))
  96. (if (stringp (car options-and-doc))
  97. (setq options-and-doc
  98. (cons :documentation options-and-doc)))
  99. ;; Make sure the method invocation order is a valid value.
  100. (let ((io (eieio--class-option-assoc options-and-doc
  101. :method-invocation-order)))
  102. (when (and io (not (member io '(:depth-first :breadth-first :c3))))
  103. (error "Method invocation order %s is not allowed" io)))
  104. (let ((testsym1 (intern (concat (symbol-name name) "-p")))
  105. (testsym2 (intern (format "%s--eieio-childp" name)))
  106. (accessors ()))
  107. ;; Collect the accessors we need to define.
  108. (pcase-dolist (`(,sname . ,soptions) slots)
  109. (let* ((acces (plist-get soptions :accessor))
  110. (initarg (plist-get soptions :initarg))
  111. (reader (plist-get soptions :reader))
  112. (writer (plist-get soptions :writer))
  113. (alloc (plist-get soptions :allocation))
  114. (label (plist-get soptions :label)))
  115. ;; Update eieio--known-slot-names already in case we compile code which
  116. ;; uses this before the class is loaded.
  117. (cl-pushnew sname eieio--known-slot-names)
  118. (if eieio-error-unsupported-class-tags
  119. (let ((tmp soptions))
  120. (while tmp
  121. (if (not (member (car tmp) '(:accessor
  122. :initform
  123. :initarg
  124. :documentation
  125. :protection
  126. :reader
  127. :writer
  128. :allocation
  129. :type
  130. :custom
  131. :label
  132. :group
  133. :printer
  134. :allow-nil-initform
  135. :custom-groups)))
  136. (signal 'invalid-slot-type (list (car tmp))))
  137. (setq tmp (cdr (cdr tmp))))))
  138. ;; Make sure the :allocation parameter has a valid value.
  139. (if (not (memq alloc '(nil :class :instance)))
  140. (signal 'invalid-slot-type (list :allocation alloc)))
  141. ;; Label is nil, or a string
  142. (if (not (or (null label) (stringp label)))
  143. (signal 'invalid-slot-type (list :label label)))
  144. ;; Is there an initarg, but allocation of class?
  145. (if (and initarg (eq alloc :class))
  146. (message "Class allocated slots do not need :initarg"))
  147. ;; Anyone can have an accessor function. This creates a function
  148. ;; of the specified name, and also performs a `defsetf' if applicable
  149. ;; so that users can `setf' the space returned by this function.
  150. (when acces
  151. (push `(cl-defmethod (setf ,acces) (value (this ,name))
  152. (eieio-oset this ',sname value))
  153. accessors)
  154. (push `(cl-defmethod ,acces ((this ,name))
  155. ,(format
  156. "Retrieve the slot `%S' from an object of class `%S'."
  157. sname name)
  158. ;; FIXME: Why is this different from the :reader case?
  159. (if (slot-boundp this ',sname) (eieio-oref this ',sname)))
  160. accessors)
  161. (when (and eieio-backward-compatibility (eq alloc :class))
  162. ;; FIXME: How could I declare this *method* as obsolete.
  163. (push `(cl-defmethod ,acces ((this (subclass ,name)))
  164. ,(format
  165. "Retrieve the class slot `%S' from a class `%S'.
  166. This method is obsolete."
  167. sname name)
  168. (if (slot-boundp this ',sname)
  169. (eieio-oref-default this ',sname)))
  170. accessors)))
  171. ;; If a writer is defined, then create a generic method of that
  172. ;; name whose purpose is to set the value of the slot.
  173. (if writer
  174. (push `(cl-defmethod ,writer ((this ,name) value)
  175. ,(format "Set the slot `%S' of an object of class `%S'."
  176. sname name)
  177. (setf (slot-value this ',sname) value))
  178. accessors))
  179. ;; If a reader is defined, then create a generic method
  180. ;; of that name whose purpose is to access this slot value.
  181. (if reader
  182. (push `(cl-defmethod ,reader ((this ,name))
  183. ,(format "Access the slot `%S' from object of class `%S'."
  184. sname name)
  185. (slot-value this ',sname))
  186. accessors))
  187. ))
  188. `(progn
  189. ;; This test must be created right away so we can have self-
  190. ;; referencing classes. ei, a class whose slot can contain only
  191. ;; pointers to itself.
  192. ;; Create the test functions.
  193. (defalias ',testsym1 (eieio-make-class-predicate ',name))
  194. (defalias ',testsym2 (eieio-make-child-predicate ',name))
  195. ,@(when eieio-backward-compatibility
  196. (let ((f (intern (format "%s-child-p" name))))
  197. `((defalias ',f ',testsym2)
  198. (make-obsolete
  199. ',f ,(format "use (cl-typep ... '%s) instead" name)
  200. "25.1"))))
  201. ;; When using typep, (typep OBJ 'myclass) returns t for objects which
  202. ;; are subclasses of myclass. For our predicates, however, it is
  203. ;; important for EIEIO to be backwards compatible, where
  204. ;; myobject-p, and myobject-child-p are different.
  205. ;; "cl" uses this technique to specify symbols with specific typep
  206. ;; test, so we can let typep have the CLOS documented behavior
  207. ;; while keeping our above predicate clean.
  208. (put ',name 'cl-deftype-satisfies #',testsym2)
  209. (eieio-defclass-internal ',name ',superclasses ',slots ',options-and-doc)
  210. ,@accessors
  211. ;; Create the constructor function
  212. ,(if (eieio--class-option-assoc options-and-doc :abstract)
  213. ;; Abstract classes cannot be instantiated. Say so.
  214. (let ((abs (eieio--class-option-assoc options-and-doc :abstract)))
  215. (if (not (stringp abs))
  216. (setq abs (format "Class %s is abstract" name)))
  217. `(defun ,name (&rest _)
  218. ,(format "You cannot create a new object of type `%S'." name)
  219. (error ,abs)))
  220. ;; Non-abstract classes need a constructor.
  221. `(defun ,name (&rest slots)
  222. ,(format "Create a new object of class type `%S'." name)
  223. (declare (compiler-macro
  224. (lambda (whole)
  225. (if (not (stringp (car slots)))
  226. whole
  227. (macroexp--warn-and-return
  228. (format "Obsolete name arg %S to constructor %S"
  229. (car slots) (car whole))
  230. ;; Keep the name arg, for backward compatibility,
  231. ;; but hide it so we don't trigger indefinitely.
  232. `(,(car whole) (identity ,(car slots))
  233. ,@(cdr slots)))))))
  234. (apply #'make-instance ',name slots))))))
  235. ;;; Get/Set slots in an object.
  236. ;;
  237. (defmacro oref (obj slot)
  238. "Retrieve the value stored in OBJ in the slot named by SLOT.
  239. Slot is the name of the slot when created by `defclass' or the label
  240. created by the :initarg tag."
  241. (declare (debug (form symbolp)))
  242. `(eieio-oref ,obj (quote ,slot)))
  243. (defalias 'slot-value 'eieio-oref)
  244. (defalias 'set-slot-value 'eieio-oset)
  245. (make-obsolete 'set-slot-value "use (setf (slot-value ..) ..) instead" "25.1")
  246. (defmacro oref-default (obj slot)
  247. "Get the default value of OBJ (maybe a class) for SLOT.
  248. The default value is the value installed in a class with the :initform
  249. tag. SLOT can be the slot name, or the tag specified by the :initarg
  250. tag in the `defclass' call."
  251. (declare (debug (form symbolp)))
  252. `(eieio-oref-default ,obj (quote ,slot)))
  253. ;;; Handy CLOS macros
  254. ;;
  255. (defmacro with-slots (spec-list object &rest body)
  256. "Bind SPEC-LIST lexically to slot values in OBJECT, and execute BODY.
  257. This establishes a lexical environment for referring to the slots in
  258. the instance named by the given slot-names as though they were
  259. variables. Within such a context the value of the slot can be
  260. specified by using its slot name, as if it were a lexically bound
  261. variable. Both setf and setq can be used to set the value of the
  262. slot.
  263. SPEC-LIST is of a form similar to `let'. For example:
  264. ((VAR1 SLOT1)
  265. SLOT2
  266. SLOTN
  267. (VARN+1 SLOTN+1))
  268. Where each VAR is the local variable given to the associated
  269. SLOT. A slot specified without a variable name is given a
  270. variable name of the same name as the slot."
  271. (declare (indent 2) (debug (sexp sexp def-body)))
  272. (require 'cl-lib)
  273. ;; Transform the spec-list into a cl-symbol-macrolet spec-list.
  274. (macroexp-let2 nil object object
  275. `(cl-symbol-macrolet
  276. ,(mapcar (lambda (entry)
  277. (let ((var (if (listp entry) (car entry) entry))
  278. (slot (if (listp entry) (cadr entry) entry)))
  279. (list var `(slot-value ,object ',slot))))
  280. spec-list)
  281. ,@body)))
  282. ;; Keep it as a non-inlined function, so the internals of object don't get
  283. ;; hard-coded in random .elc files.
  284. (defun eieio-pcase-slot-index-table (obj)
  285. "Return some data structure from which can be extracted the slot offset."
  286. (eieio--class-index-table
  287. (symbol-value (eieio--object-class-tag obj))))
  288. (defun eieio-pcase-slot-index-from-index-table (index-table slot)
  289. "Find the index to pass to `aref' to access SLOT."
  290. (let ((index (gethash slot index-table)))
  291. (if index (+ (eval-when-compile
  292. (length (cl-struct-slot-info 'eieio--object)))
  293. index))))
  294. (pcase-defmacro eieio (&rest fields)
  295. "Pcase patterns to match EIEIO objects.
  296. Elements of FIELDS can be of the form (NAME PAT) in which case the contents of
  297. field NAME is matched against PAT, or they can be of the form NAME which
  298. is a shorthand for (NAME NAME)."
  299. (declare (debug (&rest [&or (sexp pcase-PAT) sexp])))
  300. (let ((is (make-symbol "table")))
  301. ;; FIXME: This generates a horrendous mess of redundant let bindings.
  302. ;; `pcase' needs to be improved somehow to introduce let-bindings more
  303. ;; sparingly, or the byte-compiler needs to be taught to optimize
  304. ;; them away.
  305. ;; FIXME: `pcase' does not do a good job here of sharing tests&code among
  306. ;; various branches.
  307. `(and (pred eieio-object-p)
  308. (app eieio-pcase-slot-index-table ,is)
  309. ,@(mapcar (lambda (field)
  310. (let* ((name (if (consp field) (car field) field))
  311. (pat (if (consp field) (cadr field) field))
  312. (i (make-symbol "index")))
  313. `(and (let (and ,i (pred natnump))
  314. (eieio-pcase-slot-index-from-index-table
  315. ,is ',name))
  316. (app (pcase--flip aref ,i) ,pat))))
  317. fields))))
  318. ;;; Simple generators, and query functions. None of these would do
  319. ;; well embedded into an object.
  320. ;;
  321. (define-obsolete-function-alias
  322. 'object-class-fast #'eieio-object-class "24.4")
  323. (cl-defgeneric eieio-object-name-string (obj)
  324. "Return a string which is OBJ's name."
  325. (declare (obsolete eieio-named "25.1")))
  326. (defun eieio-object-name (obj &optional extra)
  327. "Return a printed representation for object OBJ.
  328. If EXTRA, include that in the string returned to represent the symbol."
  329. (cl-check-type obj eieio-object)
  330. (format "#<%s %s%s>" (eieio-object-class obj)
  331. (eieio-object-name-string obj) (or extra "")))
  332. (define-obsolete-function-alias 'object-name #'eieio-object-name "24.4")
  333. (defconst eieio--object-names (make-hash-table :test #'eq :weakness 'key))
  334. ;; In the past, every EIEIO object had a `name' field, so we had the two method
  335. ;; below "for free". Since this field is very rarely used, we got rid of it
  336. ;; and instead we keep it in a weak hash-tables, for those very rare objects
  337. ;; that use it.
  338. (cl-defmethod eieio-object-name-string (obj)
  339. (or (gethash obj eieio--object-names)
  340. (symbol-name (eieio-object-class obj))))
  341. (define-obsolete-function-alias
  342. 'object-name-string #'eieio-object-name-string "24.4")
  343. (cl-defmethod eieio-object-set-name-string (obj name)
  344. "Set the string which is OBJ's NAME."
  345. (declare (obsolete eieio-named "25.1"))
  346. (cl-check-type name string)
  347. (setf (gethash obj eieio--object-names) name))
  348. (define-obsolete-function-alias
  349. 'object-set-name-string 'eieio-object-set-name-string "24.4")
  350. (defun eieio-object-class (obj)
  351. "Return the class struct defining OBJ."
  352. ;; FIXME: We say we return a "struct" but we return a symbol instead!
  353. (cl-check-type obj eieio-object)
  354. (eieio--class-name (eieio--object-class obj)))
  355. (define-obsolete-function-alias 'object-class #'eieio-object-class "24.4")
  356. ;; CLOS name, maybe?
  357. (define-obsolete-function-alias 'class-of #'eieio-object-class "24.4")
  358. (defun eieio-object-class-name (obj)
  359. "Return a Lisp like symbol name for OBJ's class."
  360. (cl-check-type obj eieio-object)
  361. (eieio-class-name (eieio--object-class obj)))
  362. (define-obsolete-function-alias
  363. 'object-class-name 'eieio-object-class-name "24.4")
  364. (defun eieio-class-parents (class)
  365. "Return parent classes to CLASS. (overload of variable).
  366. The CLOS function `class-direct-superclasses' is aliased to this function."
  367. (eieio--class-parents (eieio--class-object class)))
  368. (define-obsolete-function-alias 'class-parents #'eieio-class-parents "24.4")
  369. (defun eieio-class-children (class)
  370. "Return child classes to CLASS.
  371. The CLOS function `class-direct-subclasses' is aliased to this function."
  372. (cl-check-type class class)
  373. (eieio--class-children (cl--find-class class)))
  374. (define-obsolete-function-alias
  375. 'class-children #'eieio-class-children "24.4")
  376. ;; Official CLOS functions.
  377. (define-obsolete-function-alias
  378. 'class-direct-superclasses #'eieio-class-parents "24.4")
  379. (define-obsolete-function-alias
  380. 'class-direct-subclasses #'eieio-class-children "24.4")
  381. (defmacro eieio-class-parent (class)
  382. "Return first parent class to CLASS. (overload of variable)."
  383. `(car (eieio-class-parents ,class)))
  384. (define-obsolete-function-alias 'class-parent 'eieio-class-parent "24.4")
  385. (defun same-class-p (obj class)
  386. "Return t if OBJ is of class-type CLASS."
  387. (setq class (eieio--class-object class))
  388. (cl-check-type class eieio--class)
  389. (cl-check-type obj eieio-object)
  390. (eq (eieio--object-class obj) class))
  391. (defun object-of-class-p (obj class)
  392. "Return non-nil if OBJ is an instance of CLASS or CLASS' subclasses."
  393. (cl-check-type obj eieio-object)
  394. ;; class will be checked one layer down
  395. (child-of-class-p (eieio--object-class obj) class))
  396. ;; Backwards compatibility
  397. (defalias 'obj-of-class-p 'object-of-class-p)
  398. (defun child-of-class-p (child class)
  399. "Return non-nil if CHILD class is a subclass of CLASS."
  400. (setq child (eieio--class-object child))
  401. (cl-check-type child eieio--class)
  402. ;; `eieio-default-superclass' is never mentioned in eieio--class-parents,
  403. ;; so we have to special case it here.
  404. (or (eq class 'eieio-default-superclass)
  405. (let ((p nil))
  406. (setq class (eieio--class-object class))
  407. (cl-check-type class eieio--class)
  408. (while (and child (not (eq child class)))
  409. (setq p (append p (eieio--class-parents child))
  410. child (pop p)))
  411. (if child t))))
  412. (defun eieio-slot-descriptor-name (slot)
  413. (cl--slot-descriptor-name slot))
  414. (defun eieio-class-slots (class)
  415. "Return list of slots available in instances of CLASS."
  416. ;; FIXME: This only gives the instance slots and ignores the
  417. ;; class-allocated slots.
  418. (setq class (eieio--class-object class))
  419. (cl-check-type class eieio--class)
  420. (mapcar #'identity (eieio--class-slots class)))
  421. (defun object-slots (obj)
  422. "Return list of slot names available in OBJ."
  423. (declare (obsolete eieio-class-slots "25.1"))
  424. (cl-check-type obj eieio-object)
  425. (mapcar #'cl--slot-descriptor-name
  426. (eieio-class-slots (eieio--object-class obj))))
  427. (defun eieio--class-slot-initarg (class slot)
  428. "Fetch from CLASS, SLOT's :initarg."
  429. (cl-check-type class eieio--class)
  430. (let ((ia (eieio--class-initarg-tuples class))
  431. (f nil))
  432. (while (and ia (not f))
  433. (if (eq (cdr (car ia)) slot)
  434. (setq f (car (car ia))))
  435. (setq ia (cdr ia)))
  436. f))
  437. ;;; Object Set macros
  438. ;;
  439. (defmacro oset (obj slot value)
  440. "Set the value in OBJ for slot SLOT to VALUE.
  441. SLOT is the slot name as specified in `defclass' or the tag created
  442. with in the :initarg slot. VALUE can be any Lisp object."
  443. (declare (debug (form symbolp form)))
  444. `(eieio-oset ,obj (quote ,slot) ,value))
  445. (defmacro oset-default (class slot value)
  446. "Set the default slot in CLASS for SLOT to VALUE.
  447. The default value is usually set with the :initform tag during class
  448. creation. This allows users to change the default behavior of classes
  449. after they are created."
  450. (declare (debug (form symbolp form)))
  451. `(eieio-oset-default ,class (quote ,slot) ,value))
  452. ;;; CLOS queries into classes and slots
  453. ;;
  454. (defun slot-boundp (object slot)
  455. "Return non-nil if OBJECT's SLOT is bound.
  456. Setting a slot's value makes it bound. Calling `slot-makeunbound' will
  457. make a slot unbound.
  458. OBJECT can be an instance or a class."
  459. ;; Skip typechecking while retrieving this value.
  460. (let ((eieio-skip-typecheck t))
  461. ;; Return nil if the magic symbol is in there.
  462. (not (eq (cond
  463. ((eieio-object-p object) (eieio-oref object slot))
  464. ((symbolp object) (eieio-oref-default object slot))
  465. (t (signal 'wrong-type-argument (list 'eieio-object-p object))))
  466. eieio-unbound))))
  467. (defun slot-makeunbound (object slot)
  468. "In OBJECT, make SLOT unbound."
  469. (eieio-oset object slot eieio-unbound))
  470. (defun slot-exists-p (object-or-class slot)
  471. "Return non-nil if OBJECT-OR-CLASS has SLOT."
  472. (let ((cv (cond ((eieio-object-p object-or-class)
  473. (eieio--object-class object-or-class))
  474. ((eieio--class-p object-or-class) object-or-class)
  475. (t (find-class object-or-class 'error)))))
  476. (or (gethash slot (eieio--class-index-table cv))
  477. ;; FIXME: We could speed this up by adding class slots into the
  478. ;; index-table (e.g. with a negative index?).
  479. (let ((cs (eieio--class-class-slots cv))
  480. found)
  481. (dotimes (i (length cs))
  482. (if (eq slot (cl--slot-descriptor-name (aref cs i)))
  483. (setq found t)))
  484. found))))
  485. (defun find-class (symbol &optional errorp)
  486. "Return the class that SYMBOL represents.
  487. If there is no class, nil is returned if ERRORP is nil.
  488. If ERRORP is non-nil, `wrong-argument-type' is signaled."
  489. (let ((class (cl--find-class symbol)))
  490. (cond
  491. ((eieio--class-p class) class)
  492. (errorp (signal 'wrong-type-argument (list 'class-p symbol))))))
  493. ;;; Slightly more complex utility functions for objects
  494. ;;
  495. (defun object-assoc (key slot list)
  496. "Return an object if KEY is `equal' to SLOT's value of an object in LIST.
  497. LIST is a list of objects whose slots are searched.
  498. Objects in LIST do not need to have a slot named SLOT, nor does
  499. SLOT need to be bound. If these errors occur, those objects will
  500. be ignored."
  501. (cl-check-type list list)
  502. (while (and list (not (condition-case nil
  503. ;; This prevents errors for missing slots.
  504. (equal key (eieio-oref (car list) slot))
  505. (error nil))))
  506. (setq list (cdr list)))
  507. (car list))
  508. (defun object-assoc-list (slot list)
  509. "Return an association list with the contents of SLOT as the key element.
  510. LIST must be a list of objects with SLOT in it.
  511. This is useful when you need to do completing read on an object group."
  512. (cl-check-type list list)
  513. (let ((assoclist nil))
  514. (while list
  515. (setq assoclist (cons (cons (eieio-oref (car list) slot)
  516. (car list))
  517. assoclist))
  518. (setq list (cdr list)))
  519. (nreverse assoclist)))
  520. (defun object-assoc-list-safe (slot list)
  521. "Return an association list with the contents of SLOT as the key element.
  522. LIST must be a list of objects, but those objects do not need to have
  523. SLOT in it. If it does not, then that element is left out of the association
  524. list."
  525. (cl-check-type list list)
  526. (let ((assoclist nil))
  527. (while list
  528. (if (slot-exists-p (car list) slot)
  529. (setq assoclist (cons (cons (eieio-oref (car list) slot)
  530. (car list))
  531. assoclist)))
  532. (setq list (cdr list)))
  533. (nreverse assoclist)))
  534. (defun object-add-to-list (object slot item &optional append)
  535. "In OBJECT's SLOT, add ITEM to the list of elements.
  536. Optional argument APPEND indicates we need to append to the list.
  537. If ITEM already exists in the list in SLOT, then it is not added.
  538. Comparison is done with `equal' through the `member' function call.
  539. If SLOT is unbound, bind it to the list containing ITEM."
  540. (let (ov)
  541. ;; Find the originating list.
  542. (if (not (slot-boundp object slot))
  543. (setq ov (list item))
  544. (setq ov (eieio-oref object slot))
  545. ;; turn it into a list.
  546. (unless (listp ov)
  547. (setq ov (list ov)))
  548. ;; Do the combination
  549. (if (not (member item ov))
  550. (setq ov
  551. (if append
  552. (append ov (list item))
  553. (cons item ov)))))
  554. ;; Set back into the slot.
  555. (eieio-oset object slot ov)))
  556. (defun object-remove-from-list (object slot item)
  557. "In OBJECT's SLOT, remove occurrences of ITEM.
  558. Deletion is done with `delete', which deletes by side effect,
  559. and comparisons are done with `equal'.
  560. If SLOT is unbound, do nothing."
  561. (if (not (slot-boundp object slot))
  562. nil
  563. (eieio-oset object slot (delete item (eieio-oref object slot)))))
  564. ;;; Here are some CLOS items that need the CL package
  565. ;;
  566. ;; FIXME: Shouldn't this be a more complex gv-expander which extracts the
  567. ;; common code between oref and oset, so as to reduce the redundant work done
  568. ;; in (push foo (oref bar baz)), like we do for the `nth' expander?
  569. (gv-define-simple-setter eieio-oref eieio-oset)
  570. ;;;
  571. ;; We want all objects created by EIEIO to have some default set of
  572. ;; behaviors so we can create object utilities, and allow various
  573. ;; types of error checking. To do this, create the default EIEIO
  574. ;; class, and when no parent class is specified, use this as the
  575. ;; default. (But don't store it in the other classes as the default,
  576. ;; allowing for transparent support.)
  577. ;;
  578. (defclass eieio-default-superclass nil
  579. nil
  580. "Default parent class for classes with no specified parent class.
  581. Its slots are automatically adopted by classes with no specified parents.
  582. This class is not stored in the `parent' slot of a class vector."
  583. :abstract t)
  584. (setq eieio-default-superclass (cl--find-class 'eieio-default-superclass))
  585. (defalias 'standard-class 'eieio-default-superclass)
  586. (cl-defgeneric make-instance (class &rest initargs)
  587. "Make a new instance of CLASS based on INITARGS.
  588. For example:
  589. (make-instance \\='foo)
  590. INITARGS is a property list with keywords based on the `:initarg'
  591. for each slot. For example:
  592. (make-instance \\='foo :slot1 value1 :slotN valueN)")
  593. (define-obsolete-function-alias 'constructor #'make-instance "25.1")
  594. (cl-defmethod make-instance
  595. ((class (subclass eieio-default-superclass)) &rest slots)
  596. "Default constructor for CLASS `eieio-default-superclass'.
  597. SLOTS are the initialization slots used by `initialize-instance'.
  598. This static method is called when an object is constructed.
  599. It allocates the vector used to represent an EIEIO object, and then
  600. calls `initialize-instance' on that object."
  601. (let* ((new-object (copy-sequence (eieio--class-default-object-cache
  602. (eieio--class-object class)))))
  603. (if (and slots
  604. (let ((x (car slots)))
  605. (or (stringp x) (null x))))
  606. (funcall (if eieio-backward-compatibility #'ignore #'message)
  607. "Obsolete name %S passed to %S constructor"
  608. (pop slots) class))
  609. ;; Call the initialize method on the new object with the slots
  610. ;; that were passed down to us.
  611. (initialize-instance new-object slots)
  612. ;; Return the created object.
  613. new-object))
  614. ;; FIXME: CLOS uses "&rest INITARGS" instead.
  615. (cl-defgeneric shared-initialize (obj slots)
  616. "Set slots of OBJ with SLOTS which is a list of name/value pairs.
  617. Called from the constructor routine.")
  618. (cl-defmethod shared-initialize ((obj eieio-default-superclass) slots)
  619. "Set slots of OBJ with SLOTS which is a list of name/value pairs.
  620. Called from the constructor routine."
  621. (while slots
  622. (let ((rn (eieio--initarg-to-attribute (eieio--object-class obj)
  623. (car slots))))
  624. (if (not rn)
  625. (slot-missing obj (car slots) 'oset (car (cdr slots)))
  626. (eieio-oset obj rn (car (cdr slots)))))
  627. (setq slots (cdr (cdr slots)))))
  628. ;; FIXME: CLOS uses "&rest INITARGS" instead.
  629. (cl-defgeneric initialize-instance (this &optional slots)
  630. "Construct the new object THIS based on SLOTS.")
  631. (cl-defmethod initialize-instance ((this eieio-default-superclass)
  632. &optional slots)
  633. "Construct the new object THIS based on SLOTS.
  634. SLOTS is a tagged list where odd numbered elements are tags, and
  635. even numbered elements are the values to store in the tagged slot.
  636. If you overload the `initialize-instance', there you will need to
  637. call `shared-initialize' yourself, or you can call `call-next-method'
  638. to have this constructor called automatically. If these steps are
  639. not taken, then new objects of your class will not have their values
  640. dynamically set from SLOTS."
  641. ;; First, see if any of our defaults are `lambda', and
  642. ;; re-evaluate them and apply the value to our slots.
  643. (let* ((this-class (eieio--object-class this))
  644. (slots (eieio--class-slots this-class)))
  645. (dotimes (i (length slots))
  646. ;; For each slot, see if we need to evaluate it.
  647. ;;
  648. ;; Paul Landes said in an email:
  649. ;; > CL evaluates it if it can, and otherwise, leaves it as
  650. ;; > the quoted thing as you already have. This is by the
  651. ;; > Sonya E. Keene book and other things I've look at on the
  652. ;; > web.
  653. (let* ((slot (aref slots i))
  654. (initform (cl--slot-descriptor-initform slot))
  655. (dflt (eieio-default-eval-maybe initform)))
  656. (when (not (eq dflt initform))
  657. ;; FIXME: We should be able to just do (aset this (+ i <cst>) dflt)!
  658. (eieio-oset this (cl--slot-descriptor-name slot) dflt)))))
  659. ;; Shared initialize will parse our slots for us.
  660. (shared-initialize this slots))
  661. (cl-defgeneric slot-missing (object slot-name operation &optional new-value)
  662. "Method invoked when an attempt to access a slot in OBJECT fails.")
  663. (cl-defmethod slot-missing ((object eieio-default-superclass) slot-name
  664. _operation &optional _new-value)
  665. "Method invoked when an attempt to access a slot in OBJECT fails.
  666. SLOT-NAME is the name of the failed slot, OPERATION is the type of access
  667. that was requested, and optional NEW-VALUE is the value that was desired
  668. to be set.
  669. This method is called from `oref', `oset', and other functions which
  670. directly reference slots in EIEIO objects."
  671. (signal 'invalid-slot-name (list (eieio-object-name object)
  672. slot-name)))
  673. (cl-defgeneric slot-unbound (object class slot-name fn)
  674. "Slot unbound is invoked during an attempt to reference an unbound slot.")
  675. (cl-defmethod slot-unbound ((object eieio-default-superclass)
  676. class slot-name fn)
  677. "Slot unbound is invoked during an attempt to reference an unbound slot.
  678. OBJECT is the instance of the object being reference. CLASS is the
  679. class of OBJECT, and SLOT-NAME is the offending slot. This function
  680. throws the signal `unbound-slot'. You can overload this function and
  681. return the value to use in place of the unbound value.
  682. Argument FN is the function signaling this error.
  683. Use `slot-boundp' to determine if a slot is bound or not.
  684. In CLOS, the argument list is (CLASS OBJECT SLOT-NAME), but
  685. EIEIO can only dispatch on the first argument, so the first two are swapped."
  686. (signal 'unbound-slot (list (eieio-class-name class)
  687. (eieio-object-name object)
  688. slot-name fn)))
  689. (cl-defgeneric clone (obj &rest params)
  690. "Make a copy of OBJ, and then supply PARAMS.
  691. PARAMS is a parameter list of the same form used by `initialize-instance'.
  692. When overloading `clone', be sure to call `call-next-method'
  693. first and modify the returned object.")
  694. (cl-defmethod clone ((obj eieio-default-superclass) &rest params)
  695. "Make a copy of OBJ, and then apply PARAMS."
  696. (let ((nobj (copy-sequence obj)))
  697. (if (stringp (car params))
  698. (funcall (if eieio-backward-compatibility #'ignore #'message)
  699. "Obsolete name %S passed to clone" (pop params)))
  700. (if params (shared-initialize nobj params))
  701. nobj))
  702. (cl-defgeneric destructor (this &rest params)
  703. "Destructor for cleaning up any dynamic links to our object.")
  704. (cl-defmethod destructor ((_this eieio-default-superclass) &rest _params)
  705. "Destructor for cleaning up any dynamic links to our object.
  706. Argument THIS is the object being destroyed. PARAMS are additional
  707. ignored parameters."
  708. ;; No cleanup... yet.
  709. )
  710. (cl-defgeneric object-print (this &rest strings)
  711. "Pretty printer for object THIS. Call function `object-name' with STRINGS.
  712. It is sometimes useful to put a summary of the object into the
  713. default #<notation> string when using EIEIO browsing tools.
  714. Implement this method to customize the summary.")
  715. (cl-defmethod object-print ((this eieio-default-superclass) &rest strings)
  716. "Pretty printer for object THIS. Call function `object-name' with STRINGS.
  717. The default method for printing object THIS is to use the
  718. function `object-name'.
  719. It is sometimes useful to put a summary of the object into the
  720. default #<notation> string when using EIEIO browsing tools.
  721. Implement this function and specify STRINGS in a call to
  722. `call-next-method' to provide additional summary information.
  723. When passing in extra strings from child classes, always remember
  724. to prepend a space."
  725. (eieio-object-name this (apply #'concat strings)))
  726. (defvar eieio-print-depth 0
  727. "When printing, keep track of the current indentation depth.")
  728. (cl-defgeneric object-write (this &optional comment)
  729. "Write out object THIS to the current stream.
  730. Optional COMMENT will add comments to the beginning of the output.")
  731. (cl-defmethod object-write ((this eieio-default-superclass) &optional comment)
  732. "Write object THIS out to the current stream.
  733. This writes out the vector version of this object. Complex and recursive
  734. object are discouraged from being written.
  735. If optional COMMENT is non-nil, include comments when outputting
  736. this object."
  737. (when comment
  738. (princ ";; Object ")
  739. (princ (eieio-object-name-string this))
  740. (princ "\n")
  741. (princ comment)
  742. (princ "\n"))
  743. (let* ((cl (eieio-object-class this))
  744. (cv (cl--find-class cl)))
  745. ;; Now output readable lisp to recreate this object
  746. ;; It should look like this:
  747. ;; (<constructor> <name> <slot> <slot> ... )
  748. ;; Each slot's slot is writen using its :writer.
  749. (princ (make-string (* eieio-print-depth 2) ? ))
  750. (princ "(")
  751. (princ (symbol-name (eieio--class-constructor (eieio-object-class this))))
  752. (princ " ")
  753. (prin1 (eieio-object-name-string this))
  754. (princ "\n")
  755. ;; Loop over all the public slots
  756. (let ((slots (eieio--class-slots cv))
  757. (eieio-print-depth (1+ eieio-print-depth)))
  758. (dotimes (i (length slots))
  759. (let ((slot (aref slots i)))
  760. (when (slot-boundp this (cl--slot-descriptor-name slot))
  761. (let ((i (eieio--class-slot-initarg
  762. cv (cl--slot-descriptor-name slot)))
  763. (v (eieio-oref this (cl--slot-descriptor-name slot))))
  764. (unless (or (not i) (equal v (cl--slot-descriptor-initform slot)))
  765. (unless (bolp)
  766. (princ "\n"))
  767. (princ (make-string (* eieio-print-depth 2) ? ))
  768. (princ (symbol-name i))
  769. (if (alist-get :printer (cl--slot-descriptor-props slot))
  770. ;; Use our public printer
  771. (progn
  772. (princ " ")
  773. (funcall (alist-get :printer
  774. (cl--slot-descriptor-props slot))
  775. v))
  776. ;; Use our generic override prin1 function.
  777. (princ (if (or (eieio-object-p v)
  778. (eieio-object-p (car-safe v)))
  779. "\n" " "))
  780. (eieio-override-prin1 v))))))))
  781. (princ ")")
  782. (when (= eieio-print-depth 0)
  783. (princ "\n"))))
  784. (defun eieio-override-prin1 (thing)
  785. "Perform a `prin1' on THING taking advantage of object knowledge."
  786. (cond ((eieio-object-p thing)
  787. (object-write thing))
  788. ((consp thing)
  789. (eieio-list-prin1 thing))
  790. ((eieio--class-p thing)
  791. (princ (eieio--class-print-name thing)))
  792. (t (prin1 thing))))
  793. (defun eieio-list-prin1 (list)
  794. "Display LIST where list may contain objects."
  795. (if (not (eieio-object-p (car list)))
  796. (progn
  797. (princ "'")
  798. (prin1 list))
  799. (princ (make-string (* eieio-print-depth 2) ? ))
  800. (princ "(list")
  801. (let ((eieio-print-depth (1+ eieio-print-depth)))
  802. (while list
  803. (princ "\n")
  804. (if (eieio-object-p (car list))
  805. (object-write (car list))
  806. (princ (make-string (* eieio-print-depth 2) ? ))
  807. (eieio-override-prin1 (car list)))
  808. (setq list (cdr list))))
  809. (princ ")")))
  810. ;;; Unimplemented functions from CLOS
  811. ;;
  812. (defun change-class (_obj _class)
  813. "Change the class of OBJ to type CLASS.
  814. This may create or delete slots, but does not affect the return value
  815. of `eq'."
  816. (error "EIEIO: `change-class' is unimplemented"))
  817. ;; Hook ourselves into help system for describing classes and methods.
  818. ;; FIXME: This is not actually needed any more since we can click on the
  819. ;; hyperlink from the constructor's docstring to see the type definition.
  820. (add-hook 'help-fns-describe-function-functions 'eieio-help-constructor)
  821. ;;; Interfacing with edebug
  822. ;;
  823. (defun eieio-edebug-prin1-to-string (print-function object &optional noescape)
  824. "Display EIEIO OBJECT in fancy format.
  825. Used as advice around `edebug-prin1-to-string', held in the
  826. variable PRINT-FUNCTION. Optional argument NOESCAPE is passed to
  827. `prin1-to-string' when appropriate."
  828. (cond ((eieio--class-p object) (eieio--class-print-name object))
  829. ((eieio-object-p object) (object-print object))
  830. ((and (listp object) (or (eieio--class-p (car object))
  831. (eieio-object-p (car object))))
  832. (concat "(" (mapconcat
  833. (lambda (x) (eieio-edebug-prin1-to-string print-function x))
  834. object " ")
  835. ")"))
  836. (t (funcall print-function object noescape))))
  837. (advice-add 'edebug-prin1-to-string
  838. :around #'eieio-edebug-prin1-to-string)
  839. ;;; Start of automatically extracted autoloads.
  840. ;;;### (autoloads nil "eieio-custom" "eieio-custom.el" "e8d466f8eee341f3da967c2931b28043")
  841. ;;; Generated autoloads from eieio-custom.el
  842. (autoload 'customize-object "eieio-custom" "\
  843. Customize OBJ in a custom buffer.
  844. Optional argument GROUP is the sub-group of slots to display.
  845. \(fn OBJ &optional GROUP)" nil nil)
  846. ;;;***
  847. ;;;### (autoloads nil "eieio-opt" "eieio-opt.el" "0b9c6be48520da2085812f6e7fed9792")
  848. ;;; Generated autoloads from eieio-opt.el
  849. (autoload 'eieio-browse "eieio-opt" "\
  850. Create an object browser window to show all objects.
  851. If optional ROOT-CLASS, then start with that, otherwise start with
  852. variable `eieio-default-superclass'.
  853. \(fn &optional ROOT-CLASS)" t nil)
  854. (define-obsolete-function-alias 'eieio-help-class 'cl--describe-class "25.1")
  855. (autoload 'eieio-help-constructor "eieio-opt" "\
  856. Describe CTR if it is a class constructor.
  857. \(fn CTR)" nil nil)
  858. ;;;***
  859. ;;; End of automatically extracted autoloads.
  860. (provide 'eieio)
  861. ;;; eieio ends here