Amend gitmerge to recognize the injunction "don't merge".
[emacs.git] / lisp / emacs-lisp / eieio.el
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-2017 Free Software Foundation, Inc.
6 ;; Author: Eric M. Ludlam <>
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
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 <>.
25 ;;; Commentary:
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.
32 ;; See eieio.texi for complete documentation on using this package.
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 ;;
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)
58 ;;; Defining a new class
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))
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)
239 "25.1"))))
241 ;; When using typep, (typep OBJ 'myclass) returns t for objects which
242 ;; are subclasses of myclass. For our predicates, however, it is
243 ;; important for EIEIO to be backwards compatible, where
244 ;; myobject-p, and myobject-child-p are different.
245 ;; "cl" uses this technique to specify symbols with specific typep
246 ;; test, so we can let typep have the CLOS documented behavior
247 ;; while keeping our above predicate clean.
249 (put ',name 'cl-deftype-satisfies #',testsym2)
251 (eieio-defclass-internal ',name ',superclasses ',slots ',options-and-doc)
253 ,@accessors
255 ;; Create the constructor function
256 ,(if (eieio--class-option-assoc options-and-doc :abstract)
257 ;; Abstract classes cannot be instantiated. Say so.
258 (let ((abs (eieio--class-option-assoc options-and-doc :abstract)))
259 (if (not (stringp abs))
260 (setq abs (format "Class %s is abstract" name)))
261 `(defun ,name (&rest _)
262 ,(format "You cannot create a new object of type `%S'." name)
263 (error ,abs)))
265 ;; Non-abstract classes need a constructor.
266 `(defun ,name (&rest slots)
267 ,(format "Create a new object of class type `%S'." name)
268 (declare (compiler-macro
269 (lambda (whole)
270 (if (not (stringp (car slots)))
271 whole
272 (macroexp--warn-and-return
273 (format "Obsolete name arg %S to constructor %S"
274 (car slots) (car whole))
275 ;; Keep the name arg, for backward compatibility,
276 ;; but hide it so we don't trigger indefinitely.
277 `(,(car whole) (identity ,(car slots))
278 ,@(cdr slots)))))))
279 (apply #'make-instance ',name slots))))))
282 ;;; Get/Set slots in an object.
284 (defmacro oref (obj slot)
285 "Retrieve the value stored in OBJ in the slot named by SLOT.
286 Slot is the name of the slot when created by `defclass' or the label
287 created by the :initarg tag."
288 (declare (debug (form symbolp)))
289 `(eieio-oref ,obj (quote ,slot)))
291 (defalias 'slot-value 'eieio-oref)
292 (defalias 'set-slot-value 'eieio-oset)
293 (make-obsolete 'set-slot-value "use (setf (slot-value ..) ..) instead" "25.1")
295 (defmacro oref-default (obj slot)
296 "Get the default value of OBJ (maybe a class) for SLOT.
297 The default value is the value installed in a class with the :initform
298 tag. SLOT can be the slot name, or the tag specified by the :initarg
299 tag in the `defclass' call."
300 (declare (debug (form symbolp)))
301 `(eieio-oref-default ,obj (quote ,slot)))
303 ;;; Handy CLOS macros
305 (defmacro with-slots (spec-list object &rest body)
306 "Bind SPEC-LIST lexically to slot values in OBJECT, and execute BODY.
307 This establishes a lexical environment for referring to the slots in
308 the instance named by the given slot-names as though they were
309 variables. Within such a context the value of the slot can be
310 specified by using its slot name, as if it were a lexically bound
311 variable. Both setf and setq can be used to set the value of the
312 slot.
314 SPEC-LIST is of a form similar to `let'. For example:
316 ((VAR1 SLOT1)
317 SLOT2
319 (VARN+1 SLOTN+1))
321 Where each VAR is the local variable given to the associated
322 SLOT. A slot specified without a variable name is given a
323 variable name of the same name as the slot."
324 (declare (indent 2) (debug (sexp sexp def-body)))
325 (require 'cl-lib)
326 ;; Transform the spec-list into a cl-symbol-macrolet spec-list.
327 (macroexp-let2 nil object object
328 `(cl-symbol-macrolet
329 ,(mapcar (lambda (entry)
330 (let ((var (if (listp entry) (car entry) entry))
331 (slot (if (listp entry) (cadr entry) entry)))
332 (list var `(slot-value ,object ',slot))))
333 spec-list)
334 ,@body)))
336 ;; Keep it as a non-inlined function, so the internals of object don't get
337 ;; hard-coded in random .elc files.
338 (defun eieio-pcase-slot-index-table (obj)
339 "Return some data structure from which can be extracted the slot offset."
340 (eieio--class-index-table
341 (symbol-value (eieio--object-class-tag obj))))
343 (defun eieio-pcase-slot-index-from-index-table (index-table slot)
344 "Find the index to pass to `aref' to access SLOT."
345 (let ((index (gethash slot index-table)))
346 (if index (+ (eval-when-compile
347 (length (cl-struct-slot-info 'eieio--object)))
348 index))))
350 (pcase-defmacro eieio (&rest fields)
351 "Pcase patterns to match EIEIO objects.
352 Elements of FIELDS can be of the form (NAME PAT) in which case the contents of
353 field NAME is matched against PAT, or they can be of the form NAME which
354 is a shorthand for (NAME NAME)."
355 (declare (debug (&rest [&or (sexp pcase-PAT) sexp])))
356 (let ((is (make-symbol "table")))
357 ;; FIXME: This generates a horrendous mess of redundant let bindings.
358 ;; `pcase' needs to be improved somehow to introduce let-bindings more
359 ;; sparingly, or the byte-compiler needs to be taught to optimize
360 ;; them away.
361 ;; FIXME: `pcase' does not do a good job here of sharing tests&code among
362 ;; various branches.
363 `(and (pred eieio-object-p)
364 (app eieio-pcase-slot-index-table ,is)
365 ,@(mapcar (lambda (field)
366 (let* ((name (if (consp field) (car field) field))
367 (pat (if (consp field) (cadr field) field))
368 (i (make-symbol "index")))
369 `(and (let (and ,i (pred natnump))
370 (eieio-pcase-slot-index-from-index-table
371 ,is ',name))
372 (app (pcase--flip aref ,i) ,pat))))
373 fields))))
375 ;;; Simple generators, and query functions. None of these would do
376 ;; well embedded into an object.
379 (define-obsolete-function-alias
380 'object-class-fast #'eieio-object-class "24.4")
382 (cl-defgeneric eieio-object-name-string (obj)
383 "Return a string which is OBJ's name."
384 (declare (obsolete eieio-named "25.1")))
386 (defun eieio-object-name (obj &optional extra)
387 "Return a printed representation for object OBJ.
388 If EXTRA, include that in the string returned to represent the symbol."
389 (cl-check-type obj eieio-object)
390 (format "#<%s %s%s>" (eieio-object-class obj)
391 (eieio-object-name-string obj) (or extra "")))
392 (define-obsolete-function-alias 'object-name #'eieio-object-name "24.4")
394 (defconst eieio--object-names (make-hash-table :test #'eq :weakness 'key))
396 ;; In the past, every EIEIO object had a `name' field, so we had the two method
397 ;; below "for free". Since this field is very rarely used, we got rid of it
398 ;; and instead we keep it in a weak hash-tables, for those very rare objects
399 ;; that use it.
400 (cl-defmethod eieio-object-name-string (obj)
401 (or (gethash obj eieio--object-names)
402 (symbol-name (eieio-object-class obj))))
403 (define-obsolete-function-alias
404 'object-name-string #'eieio-object-name-string "24.4")
406 (cl-defmethod eieio-object-set-name-string (obj name)
407 "Set the string which is OBJ's NAME."
408 (declare (obsolete eieio-named "25.1"))
409 (cl-check-type name string)
410 (setf (gethash obj eieio--object-names) name))
411 (define-obsolete-function-alias
412 'object-set-name-string 'eieio-object-set-name-string "24.4")
414 (defun eieio-object-class (obj)
415 "Return the class struct defining OBJ."
416 ;; FIXME: We say we return a "struct" but we return a symbol instead!
417 (cl-check-type obj eieio-object)
418 (eieio--class-name (eieio--object-class obj)))
419 (define-obsolete-function-alias 'object-class #'eieio-object-class "24.4")
420 ;; CLOS name, maybe?
421 (define-obsolete-function-alias 'class-of #'eieio-object-class "24.4")
423 (defun eieio-object-class-name (obj)
424 "Return a Lisp like symbol name for OBJ's class."
425 (cl-check-type obj eieio-object)
426 (eieio-class-name (eieio--object-class obj)))
427 (define-obsolete-function-alias
428 'object-class-name 'eieio-object-class-name "24.4")
430 (defun eieio-class-parents (class)
431 "Return parent classes to CLASS. (overload of variable).
433 The CLOS function `class-direct-superclasses' is aliased to this function."
434 (eieio--class-parents (eieio--class-object class)))
436 (define-obsolete-function-alias 'class-parents #'eieio-class-parents "24.4")
438 (defun eieio-class-children (class)
439 "Return child classes to CLASS.
440 The CLOS function `class-direct-subclasses' is aliased to this function."
441 (cl-check-type class class)
442 (eieio--class-children (cl--find-class class)))
443 (define-obsolete-function-alias
444 'class-children #'eieio-class-children "24.4")
446 ;; Official CLOS functions.
447 (define-obsolete-function-alias
448 'class-direct-superclasses #'eieio-class-parents "24.4")
449 (define-obsolete-function-alias
450 'class-direct-subclasses #'eieio-class-children "24.4")
452 (defmacro eieio-class-parent (class)
453 "Return first parent class to CLASS. (overload of variable)."
454 `(car (eieio-class-parents ,class)))
455 (define-obsolete-function-alias 'class-parent 'eieio-class-parent "24.4")
457 (defun same-class-p (obj class)
458 "Return t if OBJ is of class-type CLASS."
459 (setq class (eieio--class-object class))
460 (cl-check-type class eieio--class)
461 (cl-check-type obj eieio-object)
462 (eq (eieio--object-class obj) class))
464 (defun object-of-class-p (obj class)
465 "Return non-nil if OBJ is an instance of CLASS or CLASS' subclasses."
466 (cl-check-type obj eieio-object)
467 ;; class will be checked one layer down
468 (child-of-class-p (eieio--object-class obj) class))
469 ;; Backwards compatibility
470 (defalias 'obj-of-class-p 'object-of-class-p)
472 (defun child-of-class-p (child class)
473 "Return non-nil if CHILD class is a subclass of CLASS."
474 (setq child (eieio--class-object child))
475 (cl-check-type child eieio--class)
476 ;; `eieio-default-superclass' is never mentioned in eieio--class-parents,
477 ;; so we have to special case it here.
478 (or (eq class 'eieio-default-superclass)
479 (let ((p nil))
480 (setq class (eieio--class-object class))
481 (cl-check-type class eieio--class)
482 (while (and child (not (eq child class)))
483 (setq p (append p (eieio--class-parents child))
484 child (pop p)))
485 (if child t))))
487 (defun eieio-slot-descriptor-name (slot)
488 (cl--slot-descriptor-name slot))
490 (defun eieio-class-slots (class)
491 "Return list of slots available in instances of CLASS."
492 ;; FIXME: This only gives the instance slots and ignores the
493 ;; class-allocated slots.
494 (setq class (eieio--class-object class))
495 (cl-check-type class eieio--class)
496 (mapcar #'identity (eieio--class-slots class)))
498 (defun object-slots (obj)
499 "Return list of slot names available in OBJ."
500 (declare (obsolete eieio-class-slots "25.1"))
501 (cl-check-type obj eieio-object)
502 (mapcar #'cl--slot-descriptor-name
503 (eieio-class-slots (eieio--object-class obj))))
505 (defun eieio--class-slot-initarg (class slot)
506 "Fetch from CLASS, SLOT's :initarg."
507 (cl-check-type class eieio--class)
508 (let ((ia (eieio--class-initarg-tuples class))
509 (f nil))
510 (while (and ia (not f))
511 (if (eq (cdr (car ia)) slot)
512 (setq f (car (car ia))))
513 (setq ia (cdr ia)))
516 ;;; Object Set macros
518 (defmacro oset (obj slot value)
519 "Set the value in OBJ for slot SLOT to VALUE.
520 SLOT is the slot name as specified in `defclass' or the tag created
521 with in the :initarg slot. VALUE can be any Lisp object."
522 (declare (debug (form symbolp form)))
523 `(eieio-oset ,obj (quote ,slot) ,value))
525 (defmacro oset-default (class slot value)
526 "Set the default slot in CLASS for SLOT to VALUE.
527 The default value is usually set with the :initform tag during class
528 creation. This allows users to change the default behavior of classes
529 after they are created."
530 (declare (debug (form symbolp form)))
531 `(eieio-oset-default ,class (quote ,slot) ,value))
533 ;;; CLOS queries into classes and slots
535 (defun slot-boundp (object slot)
536 "Return non-nil if OBJECT's SLOT is bound.
537 Setting a slot's value makes it bound. Calling `slot-makeunbound' will
538 make a slot unbound.
539 OBJECT can be an instance or a class."
540 ;; Skip typechecking while retrieving this value.
541 (let ((eieio-skip-typecheck t))
542 ;; Return nil if the magic symbol is in there.
543 (not (eq (cond
544 ((eieio-object-p object) (eieio-oref object slot))
545 ((symbolp object) (eieio-oref-default object slot))
546 (t (signal 'wrong-type-argument (list 'eieio-object-p object))))
547 eieio-unbound))))
549 (defun slot-makeunbound (object slot)
550 "In OBJECT, make SLOT unbound."
551 (eieio-oset object slot eieio-unbound))
553 (defun slot-exists-p (object-or-class slot)
554 "Return non-nil if OBJECT-OR-CLASS has SLOT."
555 (let ((cv (cond ((eieio-object-p object-or-class)
556 (eieio--object-class object-or-class))
557 ((eieio--class-p object-or-class) object-or-class)
558 (t (find-class object-or-class 'error)))))
559 (or (gethash slot (eieio--class-index-table cv))
560 ;; FIXME: We could speed this up by adding class slots into the
561 ;; index-table (e.g. with a negative index?).
562 (let ((cs (eieio--class-class-slots cv))
563 found)
564 (dotimes (i (length cs))
565 (if (eq slot (cl--slot-descriptor-name (aref cs i)))
566 (setq found t)))
567 found))))
569 (defun find-class (symbol &optional errorp)
570 "Return the class that SYMBOL represents.
571 If there is no class, nil is returned if ERRORP is nil.
572 If ERRORP is non-nil, `wrong-argument-type' is signaled."
573 (let ((class (cl--find-class symbol)))
574 (cond
575 ((eieio--class-p class) class)
576 (errorp (signal 'wrong-type-argument (list 'class-p symbol))))))
578 ;;; Slightly more complex utility functions for objects
580 (defun object-assoc (key slot list)
581 "Return an object if KEY is `equal' to SLOT's value of an object in LIST.
582 LIST is a list of objects whose slots are searched.
583 Objects in LIST do not need to have a slot named SLOT, nor does
584 SLOT need to be bound. If these errors occur, those objects will
585 be ignored."
586 (cl-check-type list list)
587 (while (and list (not (condition-case nil
588 ;; This prevents errors for missing slots.
589 (equal key (eieio-oref (car list) slot))
590 (error nil))))
591 (setq list (cdr list)))
592 (car list))
594 (defun object-assoc-list (slot list)
595 "Return an association list with the contents of SLOT as the key element.
596 LIST must be a list of objects with SLOT in it.
597 This is useful when you need to do completing read on an object group."
598 (cl-check-type list list)
599 (let ((assoclist nil))
600 (while list
601 (setq assoclist (cons (cons (eieio-oref (car list) slot)
602 (car list))
603 assoclist))
604 (setq list (cdr list)))
605 (nreverse assoclist)))
607 (defun object-assoc-list-safe (slot list)
608 "Return an association list with the contents of SLOT as the key element.
609 LIST must be a list of objects, but those objects do not need to have
610 SLOT in it. If it does not, then that element is left out of the association
611 list."
612 (cl-check-type list list)
613 (let ((assoclist nil))
614 (while list
615 (if (slot-exists-p (car list) slot)
616 (setq assoclist (cons (cons (eieio-oref (car list) slot)
617 (car list))
618 assoclist)))
619 (setq list (cdr list)))
620 (nreverse assoclist)))
622 (defun object-add-to-list (object slot item &optional append)
623 "In OBJECT's SLOT, add ITEM to the list of elements.
624 Optional argument APPEND indicates we need to append to the list.
625 If ITEM already exists in the list in SLOT, then it is not added.
626 Comparison is done with `equal' through the `member' function call.
627 If SLOT is unbound, bind it to the list containing ITEM."
628 (let (ov)
629 ;; Find the originating list.
630 (if (not (slot-boundp object slot))
631 (setq ov (list item))
632 (setq ov (eieio-oref object slot))
633 ;; turn it into a list.
634 (unless (listp ov)
635 (setq ov (list ov)))
636 ;; Do the combination
637 (if (not (member item ov))
638 (setq ov
639 (if append
640 (append ov (list item))
641 (cons item ov)))))
642 ;; Set back into the slot.
643 (eieio-oset object slot ov)))
645 (defun object-remove-from-list (object slot item)
646 "In OBJECT's SLOT, remove occurrences of ITEM.
647 Deletion is done with `delete', which deletes by side effect,
648 and comparisons are done with `equal'.
649 If SLOT is unbound, do nothing."
650 (if (not (slot-boundp object slot))
652 (eieio-oset object slot (delete item (eieio-oref object slot)))))
654 ;;; Here are some CLOS items that need the CL package
657 ;; FIXME: Shouldn't this be a more complex gv-expander which extracts the
658 ;; common code between oref and oset, so as to reduce the redundant work done
659 ;; in (push foo (oref bar baz)), like we do for the `nth' expander?
660 (gv-define-simple-setter eieio-oref eieio-oset)
664 ;; We want all objects created by EIEIO to have some default set of
665 ;; behaviors so we can create object utilities, and allow various
666 ;; types of error checking. To do this, create the default EIEIO
667 ;; class, and when no parent class is specified, use this as the
668 ;; default. (But don't store it in the other classes as the default,
669 ;; allowing for transparent support.)
672 (defclass eieio-default-superclass nil
674 "Default parent class for classes with no specified parent class.
675 Its slots are automatically adopted by classes with no specified parents.
676 This class is not stored in the `parent' slot of a class vector."
677 :abstract t)
679 (setq eieio-default-superclass (cl--find-class 'eieio-default-superclass))
681 (define-obsolete-function-alias 'standard-class
682 'eieio-default-superclass "26.1")
684 (cl-defgeneric make-instance (class &rest initargs)
685 "Make a new instance of CLASS based on INITARGS.
686 For example:
688 (make-instance \\='foo)
690 INITARGS is a property list with keywords based on the `:initarg'
691 for each slot. For example:
693 (make-instance \\='foo :slot1 value1 :slotN valueN)")
695 (define-obsolete-function-alias 'constructor #'make-instance "25.1")
697 (cl-defmethod make-instance
698 ((class (subclass eieio-default-superclass)) &rest slots)
699 "Default constructor for CLASS `eieio-default-superclass'.
700 SLOTS are the initialization slots used by `initialize-instance'.
701 This static method is called when an object is constructed.
702 It allocates the vector used to represent an EIEIO object, and then
703 calls `initialize-instance' on that object."
704 (let* ((new-object (copy-sequence (eieio--class-default-object-cache
705 (eieio--class-object class)))))
706 (if (and slots
707 (let ((x (car slots)))
708 (or (stringp x) (null x))))
709 (funcall (if eieio-backward-compatibility #'ignore #'message)
710 "Obsolete name %S passed to %S constructor"
711 (pop slots) class))
712 ;; Call the initialize method on the new object with the slots
713 ;; that were passed down to us.
714 (initialize-instance new-object slots)
715 ;; Return the created object.
716 new-object))
718 ;; FIXME: CLOS uses "&rest INITARGS" instead.
719 (cl-defgeneric shared-initialize (obj slots)
720 "Set slots of OBJ with SLOTS which is a list of name/value pairs.
721 Called from the constructor routine.")
723 (cl-defmethod shared-initialize ((obj eieio-default-superclass) slots)
724 "Set slots of OBJ with SLOTS which is a list of name/value pairs.
725 Called from the constructor routine."
726 (while slots
727 (let ((rn (eieio--initarg-to-attribute (eieio--object-class obj)
728 (car slots))))
729 (if (not rn)
730 (slot-missing obj (car slots) 'oset (car (cdr slots)))
731 (eieio-oset obj rn (car (cdr slots)))))
732 (setq slots (cdr (cdr slots)))))
734 ;; FIXME: CLOS uses "&rest INITARGS" instead.
735 (cl-defgeneric initialize-instance (this &optional slots)
736 "Construct the new object THIS based on SLOTS.")
738 (cl-defmethod initialize-instance ((this eieio-default-superclass)
739 &optional slots)
740 "Construct the new object THIS based on SLOTS.
741 SLOTS is a tagged list where odd numbered elements are tags, and
742 even numbered elements are the values to store in the tagged slot.
743 If you overload the `initialize-instance', there you will need to
744 call `shared-initialize' yourself, or you can call `call-next-method'
745 to have this constructor called automatically. If these steps are
746 not taken, then new objects of your class will not have their values
747 dynamically set from SLOTS."
748 ;; First, see if any of our defaults are `lambda', and
749 ;; re-evaluate them and apply the value to our slots.
750 (let* ((this-class (eieio--object-class this))
751 (slots (eieio--class-slots this-class)))
752 (dotimes (i (length slots))
753 ;; For each slot, see if we need to evaluate it.
755 ;; Paul Landes said in an email:
756 ;; > CL evaluates it if it can, and otherwise, leaves it as
757 ;; > the quoted thing as you already have. This is by the
758 ;; > Sonya E. Keene book and other things I've look at on the
759 ;; > web.
760 (let* ((slot (aref slots i))
761 (initform (cl--slot-descriptor-initform slot))
762 (dflt (eieio-default-eval-maybe initform)))
763 (when (not (eq dflt initform))
764 ;; FIXME: We should be able to just do (aset this (+ i <cst>) dflt)!
765 (eieio-oset this (cl--slot-descriptor-name slot) dflt)))))
766 ;; Shared initialize will parse our slots for us.
767 (shared-initialize this slots))
769 (cl-defgeneric slot-missing (object slot-name _operation &optional _new-value)
770 "Method invoked when an attempt to access a slot in OBJECT fails.
771 SLOT-NAME is the name of the failed slot, OPERATION is the type of access
772 that was requested, and optional NEW-VALUE is the value that was desired
773 to be set.
775 This method is called from `oref', `oset', and other functions which
776 directly reference slots in EIEIO objects."
777 (signal 'invalid-slot-name
778 (list (if (eieio-object-p object) (eieio-object-name object) object)
779 slot-name)))
781 (cl-defgeneric slot-unbound (object class slot-name fn)
782 "Slot unbound is invoked during an attempt to reference an unbound slot.")
784 (cl-defmethod slot-unbound ((object eieio-default-superclass)
785 class slot-name fn)
786 "Slot unbound is invoked during an attempt to reference an unbound slot.
787 OBJECT is the instance of the object being reference. CLASS is the
788 class of OBJECT, and SLOT-NAME is the offending slot. This function
789 throws the signal `unbound-slot'. You can overload this function and
790 return the value to use in place of the unbound value.
791 Argument FN is the function signaling this error.
792 Use `slot-boundp' to determine if a slot is bound or not.
794 In CLOS, the argument list is (CLASS OBJECT SLOT-NAME), but
795 EIEIO can only dispatch on the first argument, so the first two are swapped."
796 (signal 'unbound-slot (list (eieio-class-name class)
797 (eieio-object-name object)
798 slot-name fn)))
800 (cl-defgeneric clone (obj &rest params)
801 "Make a copy of OBJ, and then supply PARAMS.
802 PARAMS is a parameter list of the same form used by `initialize-instance'.
804 When overloading `clone', be sure to call `call-next-method'
805 first and modify the returned object.")
807 (cl-defmethod clone ((obj eieio-default-superclass) &rest params)
808 "Make a copy of OBJ, and then apply PARAMS."
809 (let ((nobj (copy-sequence obj)))
810 (if (stringp (car params))
811 (funcall (if eieio-backward-compatibility #'ignore #'message)
812 "Obsolete name %S passed to clone" (pop params)))
813 (if params (shared-initialize nobj params))
814 nobj))
816 (cl-defgeneric destructor (_this &rest _params)
817 "Destructor for cleaning up any dynamic links to our object."
818 (declare (obsolete nil "26.1"))
819 ;; No cleanup... yet.
820 nil)
822 (cl-defgeneric object-print (this &rest _strings)
823 "Pretty printer for object THIS.
825 It is sometimes useful to put a summary of the object into the
826 default #<notation> string when using EIEIO browsing tools.
827 Implement this method to customize the summary."
828 (declare (obsolete cl-print-object "26.1"))
829 (format "%S" this))
831 (cl-defmethod object-print ((this eieio-default-superclass) &rest strings)
832 "Pretty printer for object THIS. Call function `object-name' with STRINGS.
833 The default method for printing object THIS is to use the
834 function `object-name'.
836 It is sometimes useful to put a summary of the object into the
837 default #<notation> string when using EIEIO browsing tools.
839 Implement this function and specify STRINGS in a call to
840 `call-next-method' to provide additional summary information.
841 When passing in extra strings from child classes, always remember
842 to prepend a space."
843 (eieio-object-name this (apply #'concat strings)))
846 (cl-defmethod cl-print-object ((object eieio-default-superclass) stream)
847 "Default printer for EIEIO objects."
848 ;; Fallback to the old `object-print'.
849 (princ (object-print object) stream))
851 (defvar eieio-print-depth 0
852 "When printing, keep track of the current indentation depth.")
854 (cl-defgeneric object-write (this &optional comment)
855 "Write out object THIS to the current stream.
856 Optional COMMENT will add comments to the beginning of the output.")
858 (cl-defmethod object-write ((this eieio-default-superclass) &optional comment)
859 "Write object THIS out to the current stream.
860 This writes out the vector version of this object. Complex and recursive
861 object are discouraged from being written.
862 If optional COMMENT is non-nil, include comments when outputting
863 this object."
864 (when comment
865 (princ ";; Object ")
866 (princ (eieio-object-name-string this))
867 (princ "\n")
868 (princ comment)
869 (princ "\n"))
870 (let* ((cl (eieio-object-class this))
871 (cv (cl--find-class cl)))
872 ;; Now output readable lisp to recreate this object
873 ;; It should look like this:
874 ;; (<constructor> <name> <slot> <slot> ... )
875 ;; Each slot's slot is writen using its :writer.
876 (princ (make-string (* eieio-print-depth 2) ? ))
877 (princ "(")
878 (princ (symbol-name (eieio--class-constructor (eieio-object-class this))))
879 (princ " ")
880 (prin1 (eieio-object-name-string this))
881 (princ "\n")
882 ;; Loop over all the public slots
883 (let ((slots (eieio--class-slots cv))
884 (eieio-print-depth (1+ eieio-print-depth)))
885 (dotimes (i (length slots))
886 (let ((slot (aref slots i)))
887 (when (slot-boundp this (cl--slot-descriptor-name slot))
888 (let ((i (eieio--class-slot-initarg
889 cv (cl--slot-descriptor-name slot)))
890 (v (eieio-oref this (cl--slot-descriptor-name slot))))
891 (unless (or (not i) (equal v (cl--slot-descriptor-initform slot)))
892 (unless (bolp)
893 (princ "\n"))
894 (princ (make-string (* eieio-print-depth 2) ? ))
895 (princ (symbol-name i))
896 (if (alist-get :printer (cl--slot-descriptor-props slot))
897 ;; Use our public printer
898 (progn
899 (princ " ")
900 (funcall (alist-get :printer
901 (cl--slot-descriptor-props slot))
903 ;; Use our generic override prin1 function.
904 (princ (if (or (eieio-object-p v)
905 (eieio-object-p (car-safe v)))
906 "\n" " "))
907 (eieio-override-prin1 v))))))))
908 (princ ")")
909 (when (= eieio-print-depth 0)
910 (princ "\n"))))
912 (defun eieio-override-prin1 (thing)
913 "Perform a `prin1' on THING taking advantage of object knowledge."
914 (cond ((eieio-object-p thing)
915 (object-write thing))
916 ((consp thing)
917 (eieio-list-prin1 thing))
918 ((eieio--class-p thing)
919 (princ (eieio--class-print-name thing)))
920 (t (prin1 thing))))
922 (defun eieio-list-prin1 (list)
923 "Display LIST where list may contain objects."
924 (if (not (eieio-object-p (car list)))
925 (progn
926 (princ "'")
927 (prin1 list))
928 (princ (make-string (* eieio-print-depth 2) ? ))
929 (princ "(list")
930 (let ((eieio-print-depth (1+ eieio-print-depth)))
931 (while list
932 (princ "\n")
933 (if (eieio-object-p (car list))
934 (object-write (car list))
935 (princ (make-string (* eieio-print-depth 2) ? ))
936 (eieio-override-prin1 (car list)))
937 (setq list (cdr list))))
938 (princ ")")))
941 ;;; Unimplemented functions from CLOS
943 (defun eieio-change-class (_obj _class)
944 "Change the class of OBJ to type CLASS.
945 This may create or delete slots, but does not affect the return value
946 of `eq'."
947 (error "EIEIO: `change-class' is unimplemented"))
948 (define-obsolete-function-alias 'change-class 'eieio-change-class "26.1")
950 ;; Hook ourselves into help system for describing classes and methods.
951 ;; FIXME: This is not actually needed any more since we can click on the
952 ;; hyperlink from the constructor's docstring to see the type definition.
953 (add-hook 'help-fns-describe-function-functions 'eieio-help-constructor)
955 (provide 'eieio)
957 ;;; eieio ends here