Merge branch 'seq-let'
[emacs.git] / lisp / emacs-lisp / eieio-core.el
blobbf3f44206c468f0288e553d7788e5fbd82d15cdf
1 ;;; eieio-core.el --- Core implementation for eieio -*- lexical-binding:t -*-
3 ;; Copyright (C) 1995-1996, 1998-2015 Free Software Foundation, Inc.
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6 ;; Version: 1.4
7 ;; Keywords: OO, lisp
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; The "core" part of EIEIO is the implementation for the object
27 ;; system (such as eieio-defclass, or eieio-defmethod) but not the
28 ;; base classes for the object system, which are defined in EIEIO.
30 ;; See the commentary for eieio.el for more about EIEIO itself.
32 ;;; Code:
34 (require 'cl-lib)
35 (require 'pcase)
37 ;;;
38 ;; A few functions that are better in the official EIEIO src, but
39 ;; used from the core.
40 (declare-function slot-unbound "eieio")
41 (declare-function slot-missing "eieio")
42 (declare-function child-of-class-p "eieio")
43 (declare-function same-class-p "eieio")
44 (declare-function object-of-class-p "eieio")
47 ;;;
48 ;; Variable declarations.
50 (defvar eieio-hook nil
51 "This hook is executed, then cleared each time `defclass' is called.")
53 (defvar eieio-error-unsupported-class-tags nil
54 "Non-nil to throw an error if an encountered tag is unsupported.
55 This may prevent classes from CLOS applications from being used with EIEIO
56 since EIEIO does not support all CLOS tags.")
58 (defvar eieio-skip-typecheck nil
59 "If non-nil, skip all slot typechecking.
60 Set this to t permanently if a program is functioning well to get a
61 small speed increase. This variable is also used internally to handle
62 default setting for optimization purposes.")
64 (defvar eieio-optimize-primary-methods-flag t
65 "Non-nil means to optimize the method dispatch on primary methods.")
67 (defvar eieio-backward-compatibility t
68 "If nil, drop support for some behaviors of older versions of EIEIO.
69 Currently under control of this var:
70 - Define every class as a var whose value is the class symbol.
71 - Define <class>-child-p and <class>-list-p predicates.
72 - Allow object names in constructors.")
74 (defconst eieio-unbound
75 (if (and (boundp 'eieio-unbound) (symbolp eieio-unbound))
76 eieio-unbound
77 (make-symbol "unbound"))
78 "Uninterned symbol representing an unbound slot in an object.")
80 ;; This is a bootstrap for eieio-default-superclass so it has a value
81 ;; while it is being built itself.
82 (defvar eieio-default-superclass nil)
84 (progn
85 ;; Arrange for field access not to bother checking if the access is indeed
86 ;; made to an eieio--class object.
87 (cl-declaim (optimize (safety 0)))
89 (cl-defstruct (eieio--class
90 (:constructor nil)
91 (:constructor eieio--class-make (name))
92 (:include cl--class)
93 (:copier nil))
94 children
95 initarg-tuples ;; initarg tuples list
96 (class-slots nil :type eieio--slot)
97 class-allocation-values ;; class allocated value vector
98 default-object-cache ;; what a newly created object would look like.
99 ; This will speed up instantiation time as
100 ; only a `copy-sequence' will be needed, instead of
101 ; looping over all the values and setting them from
102 ; the default.
103 options ;; storage location of tagged class option
104 ; Stored outright without modifications or stripping
106 ;; Set it back to the default value.
107 (cl-declaim (optimize (safety 1))))
110 (cl-defstruct (eieio--object
111 (:type vector) ;We manage our own tagging system.
112 (:constructor nil)
113 (:copier nil))
114 ;; `class-tag' holds a symbol, which is not the class name, but is instead
115 ;; properly prefixed as an internal EIEIO thingy and which holds the class
116 ;; object/struct in its `symbol-value' slot.
117 class-tag)
119 (eval-when-compile
120 (defconst eieio--object-num-slots
121 (length (cl-struct-slot-info 'eieio--object))))
123 (defsubst eieio--object-class (obj)
124 (symbol-value (eieio--object-class-tag obj)))
127 ;;; Important macros used internally in eieio.
129 (defmacro eieio--class-v (class) ;Use a macro, so it acts as a GV place.
130 "Internal: Return the class vector from the CLASS symbol."
131 (declare (debug t))
132 ;; No check: If eieio gets this far, it has probably been checked already.
133 `(get ,class 'eieio-class-definition))
135 (defsubst eieio--class-object (class)
136 "Return the class object."
137 (if (symbolp class)
138 ;; Keep the symbol if class-v is nil, for better error messages.
139 (or (eieio--class-v class) class)
140 class))
142 (defun class-p (class)
143 "Return non-nil if CLASS is a valid class vector.
144 CLASS is a symbol." ;FIXME: Is it a vector or a symbol?
145 (and (symbolp class) (eieio--class-p (eieio--class-v class))))
147 (defun eieio--class-print-name (class)
148 "Return a printed representation of CLASS."
149 (format "#<class %s>" (eieio-class-name class)))
151 (defun eieio-class-name (class)
152 "Return a Lisp like symbol name for CLASS."
153 (setq class (eieio--class-object class))
154 (cl-check-type class eieio--class)
155 (eieio--class-name class))
156 (define-obsolete-function-alias 'class-name #'eieio-class-name "24.4")
158 (defalias 'eieio--class-constructor #'identity
159 "Return the symbol representing the constructor of CLASS.")
161 (defmacro eieio--class-option-assoc (list option)
162 "Return from LIST the found OPTION, or nil if it doesn't exist."
163 `(car-safe (cdr (memq ,option ,list))))
165 (defsubst eieio--class-option (class option)
166 "Return the value stored for CLASS' OPTION.
167 Return nil if that option doesn't exist."
168 (eieio--class-option-assoc (eieio--class-options class) option))
170 (defun eieio-object-p (obj)
171 "Return non-nil if OBJ is an EIEIO object."
172 (and (vectorp obj)
173 (> (length obj) 0)
174 (let ((tag (eieio--object-class-tag obj)))
175 (and (symbolp tag)
176 ;; (eq (symbol-function tag) :quick-object-witness-check)
177 (boundp tag)
178 (eieio--class-p (symbol-value tag))))))
180 (define-obsolete-function-alias 'object-p 'eieio-object-p "25.1")
182 (defun class-abstract-p (class)
183 "Return non-nil if CLASS is abstract.
184 Abstract classes cannot be instantiated."
185 (eieio--class-option (eieio--class-v class) :abstract))
187 (defsubst eieio--class-method-invocation-order (class)
188 "Return the invocation order of CLASS.
189 Abstract classes cannot be instantiated."
190 (or (eieio--class-option class :method-invocation-order)
191 :breadth-first))
196 ;; Class Creation
198 (defvar eieio-defclass-autoload-map (make-hash-table)
199 "Symbol map of superclasses we find in autoloads.")
201 ;; We autoload this because it's used in `make-autoload'.
202 ;;;###autoload
203 (defun eieio-defclass-autoload (cname _superclasses filename doc)
204 "Create autoload symbols for the EIEIO class CNAME.
205 SUPERCLASSES are the superclasses that CNAME inherits from.
206 DOC is the docstring for CNAME.
207 This function creates a mock-class for CNAME and adds it into
208 SUPERCLASSES as children.
209 It creates an autoload function for CNAME's constructor."
210 ;; Assume we've already debugged inputs.
212 ;; We used to store the list of superclasses in the `parent' slot (as a list
213 ;; of class names). But now this slot holds a list of class objects, and
214 ;; those parents may not exist yet, so the corresponding class objects may
215 ;; simply not exist yet. So instead we just don't store the list of parents
216 ;; here in eieio-defclass-autoload at all, since it seems that they're just
217 ;; not needed before the class is actually loaded.
218 (let* ((oldc (eieio--class-v cname))
219 (newc (eieio--class-make cname)))
220 (if (eieio--class-p oldc)
221 nil ;; Do nothing if we already have this class.
223 ;; turn this into a usable self-pointing symbol
224 (when eieio-backward-compatibility
225 (set cname cname)
226 (make-obsolete-variable cname (format "use '%s instead" cname) "25.1"))
228 ;; Store the new class vector definition into the symbol. We need to
229 ;; do this first so that we can call defmethod for the accessor.
230 ;; The vector will be updated by the following while loop and will not
231 ;; need to be stored a second time.
232 (setf (eieio--class-v cname) newc)
234 ;; Create an autoload on top of our constructor function.
235 (autoload cname filename doc nil nil)
236 (autoload (intern (format "%s-p" cname)) filename "" nil nil)
237 (when eieio-backward-compatibility
238 (autoload (intern (format "%s-child-p" cname)) filename "" nil nil)
239 (autoload (intern (format "%s-list-p" cname)) filename "" nil nil)))))
241 (defsubst eieio-class-un-autoload (cname)
242 "If class CNAME is in an autoload state, load its file."
243 (autoload-do-load (symbol-function cname))) ; cname
245 (cl-deftype list-of (elem-type)
246 `(and list
247 (satisfies (lambda (list)
248 (cl-every (lambda (elem) (cl-typep elem ',elem-type))
249 list)))))
252 (defun eieio-make-class-predicate (class)
253 (lambda (obj)
254 (:documentation
255 (format "Return non-nil if OBJ is an object of type `%S'.\n\n(fn OBJ)"
256 class))
257 (and (eieio-object-p obj)
258 (same-class-p obj class))))
260 (defun eieio-make-child-predicate (class)
261 (lambda (obj)
262 (:documentation
263 (format "Return non-nil if OBJ is an object of type `%S' or a subclass.
264 \n(fn OBJ)" class))
265 (and (eieio-object-p obj)
266 (object-of-class-p obj class))))
268 (defun eieio-defclass-internal (cname superclasses slots options)
269 "Define CNAME as a new subclass of SUPERCLASSES.
270 SLOTS are the slots residing in that class definition, and OPTIONS
271 holds the class options.
272 See `defclass' for more information."
273 ;; Run our eieio-hook each time, and clear it when we are done.
274 ;; This way people can add hooks safely if they want to modify eieio
275 ;; or add definitions when eieio is loaded or something like that.
276 (run-hooks 'eieio-hook)
277 (setq eieio-hook nil)
279 (let* ((oldc (let ((c (eieio--class-v cname))) (if (eieio--class-p c) c)))
280 (newc (or oldc
281 ;; Reuse `oldc' instead of creating a new one, so that
282 ;; existing references stay valid. E.g. when
283 ;; reloading the file that does the `defclass', we don't
284 ;; want to create a new class object.
285 (eieio--class-make cname)))
286 (groups nil) ;; list of groups id'd from slots
287 (clearparent nil))
289 ;; If this class already existed, and we are updating its structure,
290 ;; make sure we keep the old child list. This can cause bugs, but
291 ;; if no new slots are created, it also saves time, and prevents
292 ;; method table breakage, particularly when the users is only
293 ;; byte compiling an EIEIO file.
294 (if oldc
295 (progn
296 (cl-assert (eq newc oldc))
297 ;; Reset the fields.
298 (setf (eieio--class-parents newc) nil)
299 (setf (eieio--class-slots newc) nil)
300 (setf (eieio--class-initarg-tuples newc) nil)
301 (setf (eieio--class-class-slots newc) nil))
302 ;; If the old class did not exist, but did exist in the autoload map,
303 ;; then adopt those children. This is like the above, but deals with
304 ;; autoloads nicely.
305 (let ((children (gethash cname eieio-defclass-autoload-map)))
306 (when children
307 (setf (eieio--class-children newc) children)
308 (remhash cname eieio-defclass-autoload-map))))
310 (if superclasses
311 (progn
312 (dolist (p superclasses)
313 (if (not (and p (symbolp p)))
314 (error "Invalid parent class %S" p)
315 (let ((c (eieio--class-v p)))
316 (if (not (eieio--class-p c))
317 ;; bad class
318 (error "Given parent class %S is not a class" p)
319 ;; good parent class...
320 ;; save new child in parent
321 (cl-pushnew cname (eieio--class-children c))
322 ;; Get custom groups, and store them into our local copy.
323 (mapc (lambda (g) (cl-pushnew g groups :test #'equal))
324 (eieio--class-option c :custom-groups))
325 ;; Save parent in child.
326 (push c (eieio--class-parents newc))))))
327 ;; Reverse the list of our parents so that they are prioritized in
328 ;; the same order as specified in the code.
329 (cl-callf nreverse (eieio--class-parents newc)))
330 ;; If there is nothing to loop over, then inherit from the
331 ;; default superclass.
332 (unless (eq cname 'eieio-default-superclass)
333 ;; adopt the default parent here, but clear it later...
334 (setq clearparent t)
335 ;; save new child in parent
336 (cl-pushnew cname (eieio--class-children eieio-default-superclass))
337 ;; save parent in child
338 (setf (eieio--class-parents newc) (list eieio-default-superclass))))
340 ;; turn this into a usable self-pointing symbol; FIXME: Why?
341 (when eieio-backward-compatibility
342 (set cname cname)
343 (make-obsolete-variable cname (format "use '%s instead" cname) "25.1"))
345 ;; Create a handy list of the class test too
346 (when eieio-backward-compatibility
347 (let ((csym (intern (concat (symbol-name cname) "-list-p"))))
348 (defalias csym
349 `(lambda (obj)
350 ,(format
351 "Test OBJ to see if it a list of objects which are a child of type %s"
352 cname)
353 (when (listp obj)
354 (let ((ans t)) ;; nil is valid
355 ;; Loop over all the elements of the input list, test
356 ;; each to make sure it is a child of the desired object class.
357 (while (and obj ans)
358 (setq ans (and (eieio-object-p (car obj))
359 (object-of-class-p (car obj) ,cname)))
360 (setq obj (cdr obj)))
361 ans))))
362 (make-obsolete csym (format "use (cl-typep ... '(list-of %s)) instead"
363 cname)
364 "25.1")))
366 ;; Before adding new slots, let's add all the methods and classes
367 ;; in from the parent class.
368 (eieio-copy-parents-into-subclass newc)
370 ;; Store the new class vector definition into the symbol. We need to
371 ;; do this first so that we can call defmethod for the accessor.
372 ;; The vector will be updated by the following while loop and will not
373 ;; need to be stored a second time.
374 (setf (eieio--class-v cname) newc)
376 ;; Query each slot in the declaration list and mangle into the
377 ;; class structure I have defined.
378 (pcase-dolist (`(,name . ,slot) slots)
379 (let* ((init (or (plist-get slot :initform)
380 (if (member :initform slot) nil
381 eieio-unbound)))
382 (initarg (plist-get slot :initarg))
383 (docstr (plist-get slot :documentation))
384 (prot (plist-get slot :protection))
385 (alloc (plist-get slot :allocation))
386 (type (plist-get slot :type))
387 (custom (plist-get slot :custom))
388 (label (plist-get slot :label))
389 (customg (plist-get slot :group))
390 (printer (plist-get slot :printer))
392 (skip-nil (eieio--class-option-assoc options :allow-nil-initform))
395 ;; Clean up the meaning of protection.
396 (setq prot
397 (pcase prot
398 ((or 'nil 'public ':public) nil)
399 ((or 'protected ':protected) 'protected)
400 ((or 'private ':private) 'private)
401 (_ (signal 'invalid-slot-type (list :protection prot)))))
403 ;; The default type specifier is supposed to be t, meaning anything.
404 (if (not type) (setq type t))
406 ;; intern the symbol so we can use it blankly
407 (if eieio-backward-compatibility
408 (and initarg (not (keywordp initarg))
409 (progn
410 (set initarg initarg)
411 (make-obsolete-variable
412 initarg (format "use '%s instead" initarg) "25.1"))))
414 ;; The customgroup should be a list of symbols.
415 (cond ((and (null customg) custom)
416 (setq customg '(default)))
417 ((not (listp customg))
418 (setq customg (list customg))))
419 ;; The customgroup better be a list of symbols.
420 (dolist (cg customg)
421 (unless (symbolp cg)
422 (signal 'invalid-slot-type (list :group cg))))
424 ;; First up, add this slot into our new class.
425 (eieio--add-new-slot
426 newc (cl--make-slot-descriptor
427 name init type
428 `(,@(if docstr `((:documentation . ,docstr)))
429 ,@(if custom `((:custom . ,custom)))
430 ,@(if label `((:label . ,label)))
431 ,@(if customg `((:group . ,customg)))
432 ,@(if printer `((:printer . ,printer)))
433 ,@(if prot `((:protection . ,prot)))))
434 initarg alloc 'defaultoverride skip-nil)
436 ;; We need to id the group, and store them in a group list attribute.
437 (dolist (cg customg)
438 (cl-pushnew cg groups :test #'equal))
441 ;; Now that everything has been loaded up, all our lists are backwards!
442 ;; Fix that up now and then them into vectors.
443 (cl-callf (lambda (slots) (apply #'vector (nreverse slots)))
444 (eieio--class-slots newc))
445 (cl-callf nreverse (eieio--class-initarg-tuples newc))
447 ;; The storage for class-class-allocation-type needs to be turned into
448 ;; a vector now.
449 (cl-callf (lambda (slots) (apply #'vector slots))
450 (eieio--class-class-slots newc))
452 ;; Also, setup the class allocated values.
453 (let* ((slots (eieio--class-class-slots newc))
454 (n (length slots))
455 (v (make-vector n nil)))
456 (dotimes (i n)
457 (setf (aref v i) (eieio-default-eval-maybe
458 (cl--slot-descriptor-initform (aref slots i)))))
459 (setf (eieio--class-class-allocation-values newc) v))
461 ;; Attach slot symbols into a hashtable, and store the index of
462 ;; this slot as the value this table.
463 (let* ((slots (eieio--class-slots newc))
464 ;; (cslots (eieio--class-class-slots newc))
465 (oa (make-hash-table :test #'eq)))
466 ;; (dotimes (cnt (length cslots))
467 ;; (setf (gethash (cl--slot-descriptor-name (aref cslots cnt)) oa) (- -1 cnt)))
468 (dotimes (cnt (length slots))
469 (setf (gethash (cl--slot-descriptor-name (aref slots cnt)) oa) cnt))
470 (setf (eieio--class-index-table newc) oa))
472 ;; Set up a specialized doc string.
473 ;; Use stored value since it is calculated in a non-trivial way
474 (let ((docstring (eieio--class-option-assoc options :documentation)))
475 (setf (eieio--class-docstring newc) docstring)
476 (when eieio-backward-compatibility
477 (put cname 'variable-documentation docstring)))
479 ;; Save the file location where this class is defined.
480 (add-to-list 'current-load-list `(eieio-defclass . ,cname))
482 ;; We have a list of custom groups. Store them into the options.
483 (let ((g (eieio--class-option-assoc options :custom-groups)))
484 (mapc (lambda (cg) (cl-pushnew cg g :test 'equal)) groups)
485 (if (memq :custom-groups options)
486 (setcar (cdr (memq :custom-groups options)) g)
487 (setq options (cons :custom-groups (cons g options)))))
489 ;; Set up the options we have collected.
490 (setf (eieio--class-options newc) options)
492 ;; if this is a superclass, clear out parent (which was set to the
493 ;; default superclass eieio-default-superclass)
494 (if clearparent (setf (eieio--class-parents newc) nil))
496 ;; Create the cached default object.
497 (let ((cache (make-vector (+ (length (eieio--class-slots newc))
498 (eval-when-compile eieio--object-num-slots))
499 nil))
500 ;; We don't strictly speaking need to use a symbol, but the old
501 ;; code used the class's name rather than the class's object, so
502 ;; we follow this preference for using a symbol, which is probably
503 ;; convenient to keep the printed representation of such Elisp
504 ;; objects readable.
505 (tag (intern (format "eieio-class-tag--%s" cname))))
506 (set tag newc)
507 (fset tag :quick-object-witness-check)
508 (setf (eieio--object-class-tag cache) tag)
509 (let ((eieio-skip-typecheck t))
510 ;; All type-checking has been done to our satisfaction
511 ;; before this call. Don't waste our time in this call..
512 (eieio-set-defaults cache t))
513 (setf (eieio--class-default-object-cache newc) cache))
515 ;; Return our new class object
516 ;; newc
517 cname
520 (defsubst eieio-eval-default-p (val)
521 "Whether the default value VAL should be evaluated for use."
522 (and (consp val) (symbolp (car val)) (fboundp (car val))))
524 (defun eieio--perform-slot-validation-for-default (slot skipnil)
525 "For SLOT, signal if its type does not match its default value.
526 If SKIPNIL is non-nil, then if default value is nil return t instead."
527 (let ((value (cl--slot-descriptor-initform slot))
528 (spec (cl--slot-descriptor-type slot)))
529 (if (not (or (eieio-eval-default-p value) ;FIXME: Why?
530 eieio-skip-typecheck
531 (and skipnil (null value))
532 (eieio--perform-slot-validation spec value)))
533 (signal 'invalid-slot-type (list (cl--slot-descriptor-name slot) spec value)))))
535 (defun eieio--slot-override (old new skipnil)
536 (cl-assert (eq (cl--slot-descriptor-name old) (cl--slot-descriptor-name new)))
537 ;; There is a match, and we must override the old value.
538 (let* ((a (cl--slot-descriptor-name old))
539 (tp (cl--slot-descriptor-type old))
540 (d (cl--slot-descriptor-initform new))
541 (type (cl--slot-descriptor-type new))
542 (oprops (cl--slot-descriptor-props old))
543 (nprops (cl--slot-descriptor-props new))
544 (custg (alist-get :group nprops)))
545 ;; If type is passed in, is it the same?
546 (if (not (eq type t))
547 (if (not (equal type tp))
548 (error
549 "Child slot type `%s' does not match inherited type `%s' for `%s'"
550 type tp a))
551 (setf (cl--slot-descriptor-type new) tp))
552 ;; If we have a repeat, only update the initarg...
553 (unless (eq d eieio-unbound)
554 (eieio--perform-slot-validation-for-default new skipnil)
555 (setf (cl--slot-descriptor-initform old) d))
557 ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
558 ;; checked and SHOULD match the superclass
559 ;; protection. Otherwise an error is thrown. However
560 ;; I wonder if a more flexible schedule might be
561 ;; implemented.
563 ;; EML - We used to have (if prot... here,
564 ;; but a prot of 'nil means public.
566 (let ((super-prot (alist-get :protection oprops))
567 (prot (alist-get :protection nprops)))
568 (if (not (eq prot super-prot))
569 (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
570 prot super-prot a)))
571 ;; End original PLN
573 ;; PLN Tue Jun 26 11:57:06 2007 :
574 ;; Do a non redundant combination of ancient custom
575 ;; groups and new ones.
576 (when custg
577 (let* ((list1 (alist-get :group oprops)))
578 (dolist (elt custg)
579 (unless (memq elt list1)
580 (push elt list1)))
581 (setf (alist-get :group (cl--slot-descriptor-props old)) list1)))
582 ;; End PLN
584 ;; PLN Mon Jun 25 22:44:34 2007 : If a new cust is
585 ;; set, simply replaces the old one.
586 (dolist (prop '(:custom :label :documentation :printer))
587 (when (alist-get prop (cl--slot-descriptor-props new))
588 (setf (alist-get prop (cl--slot-descriptor-props old))
589 (alist-get prop (cl--slot-descriptor-props new))))
591 ) ))
593 (defun eieio--add-new-slot (newc slot init alloc
594 &optional defaultoverride skipnil)
595 "Add into NEWC attribute SLOT.
596 If a slot of that name already exists in NEWC, then do nothing. If it doesn't exist,
597 INIT is the initarg, if any.
598 Argument ALLOC specifies if the slot is allocated per instance, or per class.
599 If optional DEFAULTOVERRIDE is non-nil, then if A exists in NEWC,
600 we must override its value for a default.
601 Optional argument SKIPNIL indicates if type checking should be skipped
602 if default value is nil."
603 ;; Make sure we duplicate those items that are sequences.
604 (let* ((a (cl--slot-descriptor-name slot))
605 (d (cl--slot-descriptor-initform slot))
606 (old (car (cl-member a (eieio--class-slots newc)
607 :key #'cl--slot-descriptor-name)))
608 (cold (car (cl-member a (eieio--class-class-slots newc)
609 :key #'cl--slot-descriptor-name))))
610 (condition-case nil
611 (if (sequencep d) (setq d (copy-sequence d)))
612 ;; This copy can fail on a cons cell with a non-cons in the cdr. Let's
613 ;; skip it if it doesn't work.
614 (error nil))
615 ;; (if (sequencep type) (setq type (copy-sequence type)))
616 ;; (if (sequencep cust) (setq cust (copy-sequence cust)))
617 ;; (if (sequencep custg) (setq custg (copy-sequence custg)))
619 ;; To prevent override information w/out specification of storage,
620 ;; we need to do this little hack.
621 (if cold (setq alloc :class))
623 (if (memq alloc '(nil :instance))
624 ;; In this case, we modify the INSTANCE version of a given slot.
625 (progn
626 ;; Only add this element if it is so-far unique
627 (if (not old)
628 (progn
629 (eieio--perform-slot-validation-for-default slot skipnil)
630 (push slot (eieio--class-slots newc))
632 ;; When defaultoverride is true, we are usually adding new local
633 ;; attributes which must override the default value of any slot
634 ;; passed in by one of the parent classes.
635 (when defaultoverride
636 (eieio--slot-override old slot skipnil)))
637 (when init
638 (cl-pushnew (cons init a) (eieio--class-initarg-tuples newc)
639 :test #'equal)))
641 ;; CLASS ALLOCATED SLOTS
642 (if (not cold)
643 (progn
644 (eieio--perform-slot-validation-for-default slot skipnil)
645 ;; Here we have found a :class version of a slot. This
646 ;; requires a very different approach.
647 (push slot (eieio--class-class-slots newc)))
648 (when defaultoverride
649 ;; There is a match, and we must override the old value.
650 (eieio--slot-override cold slot skipnil))))))
652 (defun eieio-copy-parents-into-subclass (newc)
653 "Copy into NEWC the slots of PARENTS.
654 Follow the rules of not overwriting early parents when applying to
655 the new child class."
656 (let ((sn (eieio--class-option-assoc (eieio--class-options newc)
657 :allow-nil-initform)))
658 (dolist (pcv (eieio--class-parents newc))
659 ;; First, duplicate all the slots of the parent.
660 (let ((pslots (eieio--class-slots pcv))
661 (pinit (eieio--class-initarg-tuples pcv)))
662 (dotimes (i (length pslots))
663 (let* ((sd (cl--copy-slot-descriptor (aref pslots i)))
664 (init (car (rassq (cl--slot-descriptor-name sd) pinit))))
665 (eieio--add-new-slot newc sd init nil nil sn))
666 )) ;; while/let
667 ;; Now duplicate all the class alloc slots.
668 (let ((pcslots (eieio--class-class-slots pcv)))
669 (dotimes (i (length pcslots))
670 (eieio--add-new-slot newc (cl--copy-slot-descriptor
671 (aref pcslots i))
672 nil :class sn)
673 )))))
676 ;;; Slot type validation
678 ;; This is a hideous hack for replacing `typep' from cl-macs, to avoid
679 ;; requiring the CL library at run-time. It can be eliminated if/when
680 ;; `typep' is merged into Emacs core.
682 (defun eieio--perform-slot-validation (spec value)
683 "Return non-nil if SPEC does not match VALUE."
684 (or (eq spec t) ; t always passes
685 (eq value eieio-unbound) ; unbound always passes
686 (cl-typep value spec)))
688 (defun eieio--validate-slot-value (class slot-idx value slot)
689 "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
690 Checks the :type specifier.
691 SLOT is the slot that is being checked, and is only used when throwing
692 an error."
693 (if eieio-skip-typecheck
695 ;; Trim off object IDX junk added in for the object index.
696 (setq slot-idx (- slot-idx (eval-when-compile eieio--object-num-slots)))
697 (let ((st (cl--slot-descriptor-type (aref (eieio--class-slots class)
698 slot-idx))))
699 (if (not (eieio--perform-slot-validation st value))
700 (signal 'invalid-slot-type
701 (list (eieio--class-name class) slot st value))))))
703 (defun eieio--validate-class-slot-value (class slot-idx value slot)
704 "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
705 Checks the :type specifier.
706 SLOT is the slot that is being checked, and is only used when throwing
707 an error."
708 (if eieio-skip-typecheck
710 (let ((st (cl--slot-descriptor-type (aref (eieio--class-class-slots class)
711 slot-idx))))
712 (if (not (eieio--perform-slot-validation st value))
713 (signal 'invalid-slot-type
714 (list (eieio--class-name class) slot st value))))))
716 (defun eieio-barf-if-slot-unbound (value instance slotname fn)
717 "Throw a signal if VALUE is a representation of an UNBOUND slot.
718 INSTANCE is the object being referenced. SLOTNAME is the offending
719 slot. If the slot is ok, return VALUE.
720 Argument FN is the function calling this verifier."
721 (if (and (eq value eieio-unbound) (not eieio-skip-typecheck))
722 (slot-unbound instance (eieio--object-class instance) slotname fn)
723 value))
726 ;;; Get/Set slots in an object.
728 (defun eieio-oref (obj slot)
729 "Return the value in OBJ at SLOT in the object vector."
730 (cl-check-type slot symbol)
731 (cl-check-type obj (or eieio-object class))
732 (let* ((class (cond ((symbolp obj)
733 (error "eieio-oref called on a class: %s" obj)
734 (let ((c (eieio--class-v obj)))
735 (if (eieio--class-p c) (eieio-class-un-autoload obj))
737 (t (eieio--object-class obj))))
738 (c (eieio--slot-name-index class slot)))
739 (if (not c)
740 ;; It might be missing because it is a :class allocated slot.
741 ;; Let's check that info out.
742 (if (setq c (eieio--class-slot-name-index class slot))
743 ;; Oref that slot.
744 (aref (eieio--class-class-allocation-values class) c)
745 ;; The slot-missing method is a cool way of allowing an object author
746 ;; to intercept missing slot definitions. Since it is also the LAST
747 ;; thing called in this fn, its return value would be retrieved.
748 (slot-missing obj slot 'oref)
749 ;;(signal 'invalid-slot-name (list (eieio-object-name obj) slot))
751 (cl-check-type obj eieio-object)
752 (eieio-barf-if-slot-unbound (aref obj c) obj slot 'oref))))
755 (defun eieio-oref-default (obj slot)
756 "Do the work for the macro `oref-default' with similar parameters.
757 Fills in OBJ's SLOT with its default value."
758 (cl-check-type obj (or eieio-object class))
759 (cl-check-type slot symbol)
760 (let* ((cl (cond ((symbolp obj) (eieio--class-v obj))
761 (t (eieio--object-class obj))))
762 (c (eieio--slot-name-index cl slot)))
763 (if (not c)
764 ;; It might be missing because it is a :class allocated slot.
765 ;; Let's check that info out.
766 (if (setq c
767 (eieio--class-slot-name-index cl slot))
768 ;; Oref that slot.
769 (aref (eieio--class-class-allocation-values cl)
771 (slot-missing obj slot 'oref-default)
772 ;;(signal 'invalid-slot-name (list (class-name cl) slot))
774 (eieio-barf-if-slot-unbound
775 (let ((val (cl--slot-descriptor-initform
776 (aref (eieio--class-slots cl)
777 (- c (eval-when-compile eieio--object-num-slots))))))
778 (eieio-default-eval-maybe val))
779 obj (eieio--class-name cl) 'oref-default))))
781 (defun eieio-default-eval-maybe (val)
782 "Check VAL, and return what `oref-default' would provide."
783 ;; FIXME: What the hell is this supposed to do? Shouldn't it evaluate
784 ;; variables as well? Why not just always call `eval'?
785 (cond
786 ;; Is it a function call? If so, evaluate it.
787 ((eieio-eval-default-p val)
788 (eval val))
789 ;;;; check for quoted things, and unquote them
790 ;;((and (consp val) (eq (car val) 'quote))
791 ;; (car (cdr val)))
792 ;; return it verbatim
793 (t val)))
795 (defun eieio-oset (obj slot value)
796 "Do the work for the macro `oset'.
797 Fills in OBJ's SLOT with VALUE."
798 (cl-check-type obj eieio-object)
799 (cl-check-type slot symbol)
800 (let* ((class (eieio--object-class obj))
801 (c (eieio--slot-name-index class slot)))
802 (if (not c)
803 ;; It might be missing because it is a :class allocated slot.
804 ;; Let's check that info out.
805 (if (setq c
806 (eieio--class-slot-name-index class slot))
807 ;; Oset that slot.
808 (progn
809 (eieio--validate-class-slot-value class c value slot)
810 (aset (eieio--class-class-allocation-values class)
811 c value))
812 ;; See oref for comment on `slot-missing'
813 (slot-missing obj slot 'oset value)
814 ;;(signal 'invalid-slot-name (list (eieio-object-name obj) slot))
816 (eieio--validate-slot-value class c value slot)
817 (aset obj c value))))
819 (defun eieio-oset-default (class slot value)
820 "Do the work for the macro `oset-default'.
821 Fills in the default value in CLASS' in SLOT with VALUE."
822 (setq class (eieio--class-object class))
823 (cl-check-type class eieio--class)
824 (cl-check-type slot symbol)
825 (let* ((c (eieio--slot-name-index class slot)))
826 (if (not c)
827 ;; It might be missing because it is a :class allocated slot.
828 ;; Let's check that info out.
829 (if (setq c (eieio--class-slot-name-index class slot))
830 (progn
831 ;; Oref that slot.
832 (eieio--validate-class-slot-value class c value slot)
833 (aset (eieio--class-class-allocation-values class) c
834 value))
835 (signal 'invalid-slot-name (list (eieio--class-name class) slot)))
836 ;; `oset-default' on an instance-allocated slot is allowed by EIEIO but
837 ;; not by CLOS and is mildly inconsistent with the :initform thingy, so
838 ;; it'd be nice to get of it. This said, it is/was used at one place by
839 ;; gnus/registry.el, so it might be used elsewhere as well, so let's
840 ;; keep it for now.
841 ;; FIXME: Generate a compile-time warning for it!
842 ;; (error "Can't `oset-default' an instance-allocated slot: %S of %S"
843 ;; slot class)
844 (eieio--validate-slot-value class c value slot)
845 ;; Set this into the storage for defaults.
846 (if (eieio-eval-default-p value)
847 (error "Can't set default to a sexp that gets evaluated again"))
848 (setf (cl--slot-descriptor-initform
849 ;; FIXME: Apparently we set it both in `slots' and in
850 ;; `object-cache', which seems redundant.
851 (aref (eieio--class-slots class)
852 (- c (eval-when-compile eieio--object-num-slots))))
853 value)
854 ;; Take the value, and put it into our cache object.
855 (eieio-oset (eieio--class-default-object-cache class)
856 slot value)
860 ;;; EIEIO internal search functions
862 (defun eieio--slot-name-index (class slot)
863 "In CLASS find the index of the named SLOT.
864 The slot is a symbol which is installed in CLASS by the `defclass' call.
865 If SLOT is the value created with :initarg instead,
866 reverse-lookup that name, and recurse with the associated slot value."
867 ;; Removed checks to outside this call
868 (let* ((fsi (gethash slot (eieio--class-index-table class))))
869 (if (integerp fsi)
870 (+ (eval-when-compile eieio--object-num-slots) fsi)
871 (let ((fn (eieio--initarg-to-attribute class slot)))
872 (if fn
873 ;; Accessing a slot via its :initarg is accepted by EIEIO
874 ;; (but not CLOS) but is a bad idea (for one: it's slower).
875 ;; FIXME: We should emit a compile-time warning when this happens!
876 (eieio--slot-name-index class fn)
877 nil)))))
879 (defun eieio--class-slot-name-index (class slot)
880 "In CLASS find the index of the named SLOT.
881 The slot is a symbol which is installed in CLASS by the `defclass'
882 call. If SLOT is the value created with :initarg instead,
883 reverse-lookup that name, and recurse with the associated slot value."
884 ;; This will happen less often, and with fewer slots. Do this the
885 ;; storage cheap way.
886 (let ((index nil)
887 (slots (eieio--class-class-slots class)))
888 (dotimes (i (length slots))
889 (if (eq slot (cl--slot-descriptor-name (aref slots i)))
890 (setq index i)))
891 index))
894 ;; Way to assign slots based on a list. Used for constructors, or
895 ;; even resetting an object at run-time
897 (defun eieio-set-defaults (obj &optional set-all)
898 "Take object OBJ, and reset all slots to their defaults.
899 If SET-ALL is non-nil, then when a default is nil, that value is
900 reset. If SET-ALL is nil, the slots are only reset if the default is
901 not nil."
902 (let ((slots (eieio--class-slots (eieio--object-class obj))))
903 (dotimes (i (length slots))
904 (let* ((name (cl--slot-descriptor-name (aref slots i)))
905 (df (eieio-oref-default obj name)))
906 (if (or df set-all)
907 (eieio-oset obj name df))))))
909 (defun eieio--initarg-to-attribute (class initarg)
910 "For CLASS, convert INITARG to the actual attribute name.
911 If there is no translation, pass it in directly (so we can cheat if
912 need be... May remove that later...)"
913 (let ((tuple (assoc initarg (eieio--class-initarg-tuples class))))
914 (if tuple
915 (cdr tuple)
916 nil)))
919 ;; Method Invocation order: C3
920 (defun eieio--c3-candidate (class remaining-inputs)
921 "Return CLASS if it can go in the result now, otherwise nil."
922 ;; Ensure CLASS is not in any position but the first in any of the
923 ;; element lists of REMAINING-INPUTS.
924 (and (not (let ((found nil))
925 (while (and remaining-inputs (not found))
926 (setq found (member class (cdr (car remaining-inputs)))
927 remaining-inputs (cdr remaining-inputs)))
928 found))
929 class))
931 (defun eieio--c3-merge-lists (reversed-partial-result remaining-inputs)
932 "Merge REVERSED-PARTIAL-RESULT REMAINING-INPUTS in a consistent order, if possible.
933 If a consistent order does not exist, signal an error."
934 (setq remaining-inputs (delq nil remaining-inputs))
935 (if (null remaining-inputs)
936 ;; If all remaining inputs are empty lists, we are done.
937 (nreverse reversed-partial-result)
938 ;; Otherwise, we try to find the next element of the result. This
939 ;; is achieved by considering the first element of each
940 ;; (non-empty) input list and accepting a candidate if it is
941 ;; consistent with the rests of the input lists.
942 (let* ((found nil)
943 (tail remaining-inputs)
944 (next (progn
945 (while (and tail (not found))
946 (setq found (eieio--c3-candidate (caar tail)
947 remaining-inputs)
948 tail (cdr tail)))
949 found)))
950 (if next
951 ;; The graph is consistent so far, add NEXT to result and
952 ;; merge input lists, dropping NEXT from their heads where
953 ;; applicable.
954 (eieio--c3-merge-lists
955 (cons next reversed-partial-result)
956 (mapcar (lambda (l) (if (eq (cl-first l) next) (cl-rest l) l))
957 remaining-inputs))
958 ;; The graph is inconsistent, give up
959 (signal 'inconsistent-class-hierarchy (list remaining-inputs))))))
961 (defsubst eieio--class/struct-parents (class)
962 (or (eieio--class-parents class)
963 `(,eieio-default-superclass)))
965 (defun eieio--class-precedence-c3 (class)
966 "Return all parents of CLASS in c3 order."
967 (let ((parents (eieio--class-parents (eieio--class-v class))))
968 (eieio--c3-merge-lists
969 (list class)
970 (append
972 (mapcar #'eieio--class-precedence-c3 parents)
973 `((,eieio-default-superclass)))
974 (list parents))))
977 ;; Method Invocation Order: Depth First
979 (defun eieio--class-precedence-dfs (class)
980 "Return all parents of CLASS in depth-first order."
981 (let* ((parents (eieio--class-parents class))
982 (classes (copy-sequence
983 (apply #'append
984 (list class)
986 (mapcar
987 (lambda (parent)
988 (cons parent
989 (eieio--class-precedence-dfs parent)))
990 parents)
991 `((,eieio-default-superclass))))))
992 (tail classes))
993 ;; Remove duplicates.
994 (while tail
995 (setcdr tail (delq (car tail) (cdr tail)))
996 (setq tail (cdr tail)))
997 classes))
1000 ;; Method Invocation Order: Breadth First
1001 (defun eieio--class-precedence-bfs (class)
1002 "Return all parents of CLASS in breadth-first order."
1003 (let* ((result)
1004 (queue (eieio--class/struct-parents class)))
1005 (while queue
1006 (let ((head (pop queue)))
1007 (unless (member head result)
1008 (push head result)
1009 (unless (eq head eieio-default-superclass)
1010 (setq queue (append queue (eieio--class/struct-parents head)))))))
1011 (cons class (nreverse result)))
1015 ;; Method Invocation Order
1017 (defun eieio--class-precedence-list (class)
1018 "Return (transitively closed) list of parents of CLASS.
1019 The order, in which the parents are returned depends on the
1020 method invocation orders of the involved classes."
1021 (if (or (null class) (eq class eieio-default-superclass))
1023 (unless (eieio--class-default-object-cache class)
1024 (eieio-class-un-autoload (eieio--class-name class)))
1025 (cl-case (eieio--class-method-invocation-order class)
1026 (:depth-first
1027 (eieio--class-precedence-dfs class))
1028 (:breadth-first
1029 (eieio--class-precedence-bfs class))
1030 (:c3
1031 (eieio--class-precedence-c3 class))))
1033 (define-obsolete-function-alias
1034 'class-precedence-list 'eieio--class-precedence-list "24.4")
1037 ;;; Here are some special types of errors
1039 (define-error 'invalid-slot-name "Invalid slot name")
1040 (define-error 'invalid-slot-type "Invalid slot type")
1041 (define-error 'unbound-slot "Unbound slot")
1042 (define-error 'inconsistent-class-hierarchy "Inconsistent class hierarchy")
1044 ;;; Hooking into cl-generic.
1046 (require 'cl-generic)
1048 ;;;; General support to dispatch based on the type of the argument.
1050 (defconst eieio--generic-generalizer
1051 (cl-generic-make-generalizer
1052 ;; Use the exact same tagcode as for cl-struct, so that methods
1053 ;; that dispatch on both kinds of objects get to share this
1054 ;; part of the dispatch code.
1055 50 #'cl--generic-struct-tag
1056 (lambda (tag)
1057 (and (symbolp tag) (boundp tag) (eieio--class-p (symbol-value tag))
1058 (mapcar #'eieio--class-name
1059 (eieio--class-precedence-list (symbol-value tag)))))))
1061 (cl-defmethod cl-generic-generalizers :extra "class" (specializer)
1062 ;; CLHS says:
1063 ;; A class must be defined before it can be used as a parameter
1064 ;; specializer in a defmethod form.
1065 ;; So we can ignore types that are not known to denote classes.
1067 (and (eieio--class-p (eieio--class-object specializer))
1068 (list eieio--generic-generalizer))
1069 (cl-call-next-method)))
1071 ;;;; Dispatch for arguments which are classes.
1073 ;; Since EIEIO does not support metaclasses, users can't easily use the
1074 ;; "dispatch on argument type" for class arguments. That's why EIEIO's
1075 ;; `defmethod' added the :static qualifier. For cl-generic, such a qualifier
1076 ;; would not make much sense (e.g. to which argument should it apply?).
1077 ;; Instead, we add a new "subclass" specializer.
1079 (defun eieio--generic-subclass-specializers (tag)
1080 (when (eieio--class-p tag)
1081 (mapcar (lambda (class)
1082 `(subclass ,(eieio--class-name class)))
1083 (eieio--class-precedence-list tag))))
1085 (defconst eieio--generic-subclass-generalizer
1086 (cl-generic-make-generalizer
1087 60 (lambda (name) `(and (symbolp ,name) (eieio--class-v ,name)))
1088 #'eieio--generic-subclass-specializers))
1090 (cl-defmethod cl-generic-generalizers ((_specializer (head subclass)))
1091 (list eieio--generic-subclass-generalizer))
1094 ;;;### (autoloads nil "eieio-compat" "eieio-compat.el" "0609a7bdcd6f38876b7f5647047ddca9")
1095 ;;; Generated autoloads from eieio-compat.el
1097 (autoload 'eieio--defalias "eieio-compat" "\
1098 Like `defalias', but with less side-effects.
1099 More specifically, it has no side-effects at all when the new function
1100 definition is the same (`eq') as the old one.
1102 \(fn NAME BODY)" nil nil)
1104 (autoload 'defgeneric "eieio-compat" "\
1105 Create a generic function METHOD.
1106 DOC-STRING is the base documentation for this class. A generic
1107 function has no body, as its purpose is to decide which method body
1108 is appropriate to use. Uses `defmethod' to create methods, and calls
1109 `defgeneric' for you. With this implementation the ARGS are
1110 currently ignored. You can use `defgeneric' to apply specialized
1111 top level documentation to a method.
1113 \(fn METHOD ARGS &optional DOC-STRING)" nil t)
1115 (function-put 'defgeneric 'doc-string-elt '3)
1117 (make-obsolete 'defgeneric 'cl-defgeneric '"25.1")
1119 (autoload 'defmethod "eieio-compat" "\
1120 Create a new METHOD through `defgeneric' with ARGS.
1122 The optional second argument KEY is a specifier that
1123 modifies how the method is called, including:
1124 :before - Method will be called before the :primary
1125 :primary - The default if not specified
1126 :after - Method will be called after the :primary
1127 :static - First arg could be an object or class
1128 The next argument is the ARGLIST. The ARGLIST specifies the arguments
1129 to the method as with `defun'. The first argument can have a type
1130 specifier, such as:
1131 ((VARNAME CLASS) ARG2 ...)
1132 where VARNAME is the name of the local variable for the method being
1133 created. The CLASS is a class symbol for a class made with `defclass'.
1134 A DOCSTRING comes after the ARGLIST, and is optional.
1135 All the rest of the args are the BODY of the method. A method will
1136 return the value of the last form in the BODY.
1138 Summary:
1140 (defmethod mymethod [:before | :primary | :after | :static]
1141 ((typearg class-name) arg2 &optional opt &rest rest)
1142 \"doc-string\"
1143 body)
1145 \(fn METHOD &rest ARGS)" nil t)
1147 (function-put 'defmethod 'doc-string-elt '3)
1149 (make-obsolete 'defmethod 'cl-defmethod '"25.1")
1151 (autoload 'eieio--defgeneric-init-form "eieio-compat" "\
1154 \(fn METHOD DOC-STRING)" nil nil)
1156 (autoload 'eieio--defmethod "eieio-compat" "\
1159 \(fn METHOD KIND ARGCLASS CODE)" nil nil)
1161 (autoload 'eieio-defmethod "eieio-compat" "\
1162 Obsolete work part of an old version of the `defmethod' macro.
1164 \(fn METHOD ARGS)" nil nil)
1166 (make-obsolete 'eieio-defmethod 'cl-defmethod '"24.1")
1168 (autoload 'eieio-defgeneric "eieio-compat" "\
1169 Obsolete work part of an old version of the `defgeneric' macro.
1171 \(fn METHOD DOC-STRING)" nil nil)
1173 (make-obsolete 'eieio-defgeneric 'cl-defgeneric '"24.1")
1175 (autoload 'eieio-defclass "eieio-compat" "\
1178 \(fn CNAME SUPERCLASSES SLOTS OPTIONS)" nil nil)
1180 (make-obsolete 'eieio-defclass 'eieio-defclass-internal '"25.1")
1182 ;;;***
1185 (provide 'eieio-core)
1187 ;;; eieio-core.el ends here