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