* lisp/calendar/diary-lib.el (diary-remind): Fix bug#30455.
[emacs.git] / lisp / emacs-lisp / eieio-core.el
blobe5ea33c00324690d1532e8412fb6ae30df0ec83a
1 ;;; eieio-core.el --- Core implementation for eieio -*- lexical-binding:t -*-
3 ;; Copyright (C) 1995-1996, 1998-2018 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 <https://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 'eieio-loaddefs nil t)
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 (eval-when-compile (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. NOTE: Using the default
107 ;; `safety' value does NOT give the default
108 ;; `byte-compile-delete-errors' value. Therefore limit this (and
109 ;; the above `cl-declaim') to compile time so that we don't affect
110 ;; code which only loads this library.
111 (eval-when-compile (cl-declaim (optimize (safety 1)))))
114 (eval-and-compile
115 (defconst eieio--object-num-slots 1))
117 (defsubst eieio--object-class-tag (obj)
118 (aref obj 0))
120 (defsubst eieio--object-class (obj)
121 (eieio--object-class-tag obj))
124 ;;; Important macros used internally in eieio.
126 (require 'cl-macs) ;For cl--find-class.
128 (defsubst eieio--class-object (class)
129 "Return the class object."
130 (if (symbolp class)
131 ;; Keep the symbol if class-v is nil, for better error messages.
132 (or (cl--find-class class) class)
133 class))
135 (defun class-p (x)
136 "Return non-nil if X is a valid class vector.
137 X can also be is a symbol."
138 (eieio--class-p (if (symbolp x) (cl--find-class x) x)))
140 (defun eieio--class-print-name (class)
141 "Return a printed representation of CLASS."
142 (format "#<class %s>" (eieio-class-name class)))
144 (defun eieio-class-name (class)
145 "Return a Lisp like symbol name for CLASS."
146 (setq class (eieio--class-object class))
147 (cl-check-type class eieio--class)
148 (eieio--class-name class))
149 (define-obsolete-function-alias 'class-name #'eieio-class-name "24.4")
151 (defalias 'eieio--class-constructor #'identity
152 "Return the symbol representing the constructor of CLASS.")
154 (defmacro eieio--class-option-assoc (list option)
155 "Return from LIST the found OPTION, or nil if it doesn't exist."
156 `(car-safe (cdr (memq ,option ,list))))
158 (defsubst eieio--class-option (class option)
159 "Return the value stored for CLASS' OPTION.
160 Return nil if that option doesn't exist."
161 (eieio--class-option-assoc (eieio--class-options class) option))
163 (defun eieio-object-p (obj)
164 "Return non-nil if OBJ is an EIEIO object."
165 (and (recordp obj)
166 (eieio--class-p (eieio--object-class-tag obj))))
168 (define-obsolete-function-alias 'object-p 'eieio-object-p "25.1")
170 (defun class-abstract-p (class)
171 "Return non-nil if CLASS is abstract.
172 Abstract classes cannot be instantiated."
173 (eieio--class-option (cl--find-class class) :abstract))
175 (defsubst eieio--class-method-invocation-order (class)
176 "Return the invocation order of CLASS.
177 Abstract classes cannot be instantiated."
178 (or (eieio--class-option class :method-invocation-order)
179 :breadth-first))
184 ;; Class Creation
186 (defvar eieio-defclass-autoload-map (make-hash-table)
187 "Symbol map of superclasses we find in autoloads.")
189 ;; We autoload this because it's used in `make-autoload'.
190 ;;;###autoload
191 (defun eieio-defclass-autoload (cname _superclasses filename doc)
192 "Create autoload symbols for the EIEIO class CNAME.
193 SUPERCLASSES are the superclasses that CNAME inherits from.
194 DOC is the docstring for CNAME.
195 This function creates a mock-class for CNAME and adds it into
196 SUPERCLASSES as children.
197 It creates an autoload function for CNAME's constructor."
198 ;; Assume we've already debugged inputs.
200 ;; We used to store the list of superclasses in the `parent' slot (as a list
201 ;; of class names). But now this slot holds a list of class objects, and
202 ;; those parents may not exist yet, so the corresponding class objects may
203 ;; simply not exist yet. So instead we just don't store the list of parents
204 ;; here in eieio-defclass-autoload at all, since it seems that they're just
205 ;; not needed before the class is actually loaded.
206 (let* ((oldc (cl--find-class cname))
207 (newc (eieio--class-make cname)))
208 (if (eieio--class-p oldc)
209 nil ;; Do nothing if we already have this class.
211 ;; turn this into a usable self-pointing symbol
212 (when eieio-backward-compatibility
213 (set cname cname)
214 (make-obsolete-variable cname (format "use \\='%s instead" cname)
215 "25.1"))
217 ;; Store the new class vector definition into the symbol. We need to
218 ;; do this first so that we can call defmethod for the accessor.
219 ;; The vector will be updated by the following while loop and will not
220 ;; need to be stored a second time.
221 (setf (cl--find-class cname) newc)
223 ;; Create an autoload on top of our constructor function.
224 (autoload cname filename doc nil nil)
225 (autoload (intern (format "%s-p" cname)) filename "" nil nil)
226 (when eieio-backward-compatibility
227 (autoload (intern (format "%s-child-p" cname)) filename "" nil nil)
228 (autoload (intern (format "%s-list-p" cname)) filename "" nil nil)))))
230 (defsubst eieio-class-un-autoload (cname)
231 "If class CNAME is in an autoload state, load its file."
232 (autoload-do-load (symbol-function cname))) ; cname
234 (cl-deftype list-of (elem-type)
235 `(and list
236 (satisfies (lambda (list)
237 (cl-every (lambda (elem) (cl-typep elem ',elem-type))
238 list)))))
241 (defun eieio-make-class-predicate (class)
242 (lambda (obj)
243 (:documentation
244 (format "Return non-nil if OBJ is an object of type `%S'.\n\n(fn OBJ)"
245 class))
246 (and (eieio-object-p obj)
247 (same-class-p obj class))))
249 (defun eieio-make-child-predicate (class)
250 (lambda (obj)
251 (:documentation
252 (format "Return non-nil if OBJ is an object of type `%S' or a subclass.
253 \n(fn OBJ)" class))
254 (and (eieio-object-p obj)
255 (object-of-class-p obj class))))
257 (defvar eieio--known-slot-names nil)
259 (defun eieio-defclass-internal (cname superclasses slots options)
260 "Define CNAME as a new subclass of SUPERCLASSES.
261 SLOTS are the slots residing in that class definition, and OPTIONS
262 holds the class options.
263 See `defclass' for more information."
264 ;; Run our eieio-hook each time, and clear it when we are done.
265 ;; This way people can add hooks safely if they want to modify eieio
266 ;; or add definitions when eieio is loaded or something like that.
267 (run-hooks 'eieio-hook)
268 (setq eieio-hook nil)
270 (let* ((oldc (let ((c (cl--find-class cname))) (if (eieio--class-p c) c)))
271 (newc (or oldc
272 ;; Reuse `oldc' instead of creating a new one, so that
273 ;; existing references stay valid. E.g. when
274 ;; reloading the file that does the `defclass', we don't
275 ;; want to create a new class object.
276 (eieio--class-make cname)))
277 (groups nil) ;; list of groups id'd from slots
278 (clearparent nil))
280 ;; If this class already existed, and we are updating its structure,
281 ;; make sure we keep the old child list. This can cause bugs, but
282 ;; if no new slots are created, it also saves time, and prevents
283 ;; method table breakage, particularly when the users is only
284 ;; byte compiling an EIEIO file.
285 (if oldc
286 (progn
287 (cl-assert (eq newc oldc))
288 ;; Reset the fields.
289 (setf (eieio--class-parents newc) nil)
290 (setf (eieio--class-slots newc) nil)
291 (setf (eieio--class-initarg-tuples newc) nil)
292 (setf (eieio--class-class-slots newc) nil))
293 ;; If the old class did not exist, but did exist in the autoload map,
294 ;; then adopt those children. This is like the above, but deals with
295 ;; autoloads nicely.
296 (let ((children (gethash cname eieio-defclass-autoload-map)))
297 (when children
298 (setf (eieio--class-children newc) children)
299 (remhash cname eieio-defclass-autoload-map))))
301 (if superclasses
302 (progn
303 (dolist (p superclasses)
304 (if (not (and p (symbolp p)))
305 (error "Invalid parent class %S" p)
306 (let ((c (cl--find-class p)))
307 (if (not (eieio--class-p c))
308 ;; bad class
309 (error "Given parent class %S is not a class" p)
310 ;; good parent class...
311 ;; save new child in parent
312 (cl-pushnew cname (eieio--class-children c))
313 ;; Get custom groups, and store them into our local copy.
314 (mapc (lambda (g) (cl-pushnew g groups :test #'equal))
315 (eieio--class-option c :custom-groups))
316 ;; Save parent in child.
317 (push c (eieio--class-parents newc))))))
318 ;; Reverse the list of our parents so that they are prioritized in
319 ;; the same order as specified in the code.
320 (cl-callf nreverse (eieio--class-parents newc)))
321 ;; If there is nothing to loop over, then inherit from the
322 ;; default superclass.
323 (unless (eq cname 'eieio-default-superclass)
324 ;; adopt the default parent here, but clear it later...
325 (setq clearparent t)
326 ;; save new child in parent
327 (cl-pushnew cname (eieio--class-children eieio-default-superclass))
328 ;; save parent in child
329 (setf (eieio--class-parents newc) (list eieio-default-superclass))))
331 ;; turn this into a usable self-pointing symbol; FIXME: Why?
332 (when eieio-backward-compatibility
333 (set cname cname)
334 (make-obsolete-variable cname (format "use \\='%s instead" cname)
335 "25.1"))
337 ;; Create a handy list of the class test too
338 (when eieio-backward-compatibility
339 (let ((csym (intern (concat (symbol-name cname) "-list-p"))))
340 (defalias csym
341 `(lambda (obj)
342 ,(format
343 "Test OBJ to see if it a list of objects which are a child of type %s"
344 cname)
345 (when (listp obj)
346 (let ((ans t)) ;; nil is valid
347 ;; Loop over all the elements of the input list, test
348 ;; each to make sure it is a child of the desired object class.
349 (while (and obj ans)
350 (setq ans (and (eieio-object-p (car obj))
351 (object-of-class-p (car obj) ,cname)))
352 (setq obj (cdr obj)))
353 ans))))
354 (make-obsolete csym (format
355 "use (cl-typep ... \\='(list-of %s)) instead"
356 cname)
357 "25.1")))
359 ;; Before adding new slots, let's add all the methods and classes
360 ;; in from the parent class.
361 (eieio-copy-parents-into-subclass newc)
363 ;; Store the new class vector definition into the symbol. We need to
364 ;; do this first so that we can call defmethod for the accessor.
365 ;; The vector will be updated by the following while loop and will not
366 ;; need to be stored a second time.
367 (setf (cl--find-class cname) newc)
369 ;; Query each slot in the declaration list and mangle into the
370 ;; class structure I have defined.
371 (pcase-dolist (`(,name . ,slot) slots)
372 (let* ((init (or (plist-get slot :initform)
373 (if (member :initform slot) nil
374 eieio-unbound)))
375 (initarg (plist-get slot :initarg))
376 (docstr (plist-get slot :documentation))
377 (prot (plist-get slot :protection))
378 (alloc (plist-get slot :allocation))
379 (type (plist-get slot :type))
380 (custom (plist-get slot :custom))
381 (label (plist-get slot :label))
382 (customg (plist-get slot :group))
383 (printer (plist-get slot :printer))
385 (skip-nil (eieio--class-option-assoc options :allow-nil-initform))
388 ;; Clean up the meaning of protection.
389 (setq prot
390 (pcase prot
391 ((or 'nil 'public ':public) nil)
392 ((or 'protected ':protected) 'protected)
393 ((or 'private ':private) 'private)
394 (_ (signal 'invalid-slot-type (list :protection prot)))))
396 ;; The default type specifier is supposed to be t, meaning anything.
397 (if (not type) (setq type t))
399 ;; intern the symbol so we can use it blankly
400 (if eieio-backward-compatibility
401 (and initarg (not (keywordp initarg))
402 (progn
403 (set initarg initarg)
404 (make-obsolete-variable
405 initarg (format "use \\='%s instead" initarg) "25.1"))))
407 ;; The customgroup should be a list of symbols.
408 (cond ((and (null customg) custom)
409 (setq customg '(default)))
410 ((not (listp customg))
411 (setq customg (list customg))))
412 ;; The customgroup better be a list of symbols.
413 (dolist (cg customg)
414 (unless (symbolp cg)
415 (signal 'invalid-slot-type (list :group cg))))
417 ;; First up, add this slot into our new class.
418 (eieio--add-new-slot
419 newc (cl--make-slot-descriptor
420 name init type
421 `(,@(if docstr `((:documentation . ,docstr)))
422 ,@(if custom `((:custom . ,custom)))
423 ,@(if label `((:label . ,label)))
424 ,@(if customg `((:group . ,customg)))
425 ,@(if printer `((:printer . ,printer)))
426 ,@(if prot `((:protection . ,prot)))))
427 initarg alloc 'defaultoverride skip-nil)
429 ;; We need to id the group, and store them in a group list attribute.
430 (dolist (cg customg)
431 (cl-pushnew cg groups :test #'equal))
434 ;; Now that everything has been loaded up, all our lists are backwards!
435 ;; Fix that up now and then them into vectors.
436 (cl-callf (lambda (slots) (apply #'vector (nreverse slots)))
437 (eieio--class-slots newc))
438 (cl-callf nreverse (eieio--class-initarg-tuples newc))
440 ;; The storage for class-class-allocation-type needs to be turned into
441 ;; a vector now.
442 (cl-callf (lambda (slots) (apply #'vector slots))
443 (eieio--class-class-slots newc))
445 ;; Also, setup the class allocated values.
446 (let* ((slots (eieio--class-class-slots newc))
447 (n (length slots))
448 (v (make-vector n nil)))
449 (dotimes (i n)
450 (setf (aref v i) (eieio-default-eval-maybe
451 (cl--slot-descriptor-initform (aref slots i)))))
452 (setf (eieio--class-class-allocation-values newc) v))
454 ;; Attach slot symbols into a hash table, and store the index of
455 ;; this slot as the value this table.
456 (let* ((slots (eieio--class-slots newc))
457 ;; (cslots (eieio--class-class-slots newc))
458 (oa (make-hash-table :test #'eq)))
459 ;; (dotimes (cnt (length cslots))
460 ;; (setf (gethash (cl--slot-descriptor-name (aref cslots cnt)) oa) (- -1 cnt)))
461 (dotimes (cnt (length slots))
462 (setf (gethash (cl--slot-descriptor-name (aref slots cnt)) oa) cnt))
463 (setf (eieio--class-index-table newc) oa))
465 ;; Set up a specialized doc string.
466 ;; Use stored value since it is calculated in a non-trivial way
467 (let ((docstring (eieio--class-option-assoc options :documentation)))
468 (setf (eieio--class-docstring newc) docstring)
469 (when eieio-backward-compatibility
470 (put cname 'variable-documentation docstring)))
472 ;; Save the file location where this class is defined.
473 (add-to-list 'current-load-list `(define-type . ,cname))
475 ;; We have a list of custom groups. Store them into the options.
476 (let ((g (eieio--class-option-assoc options :custom-groups)))
477 (mapc (lambda (cg) (cl-pushnew cg g :test 'equal)) groups)
478 (if (memq :custom-groups options)
479 (setcar (cdr (memq :custom-groups options)) g)
480 (setq options (cons :custom-groups (cons g options)))))
482 ;; Set up the options we have collected.
483 (setf (eieio--class-options newc) options)
485 ;; if this is a superclass, clear out parent (which was set to the
486 ;; default superclass eieio-default-superclass)
487 (if clearparent (setf (eieio--class-parents newc) nil))
489 ;; Create the cached default object.
490 (let ((cache (make-record newc
491 (+ (length (eieio--class-slots newc))
492 (eval-when-compile eieio--object-num-slots)
494 nil)))
495 (let ((eieio-skip-typecheck t))
496 ;; All type-checking has been done to our satisfaction
497 ;; before this call. Don't waste our time in this call..
498 (eieio-set-defaults cache t))
499 (setf (eieio--class-default-object-cache newc) cache))
501 ;; Return our new class object
502 ;; newc
503 cname
506 (defsubst eieio-eval-default-p (val)
507 "Whether the default value VAL should be evaluated for use."
508 (and (consp val) (symbolp (car val)) (fboundp (car val))))
510 (defun eieio--perform-slot-validation-for-default (slot skipnil)
511 "For SLOT, signal if its type does not match its default value.
512 If SKIPNIL is non-nil, then if default value is nil return t instead."
513 (let ((value (cl--slot-descriptor-initform slot))
514 (spec (cl--slot-descriptor-type slot)))
515 (if (not (or (eieio-eval-default-p value) ;FIXME: Why?
516 eieio-skip-typecheck
517 (and skipnil (null value))
518 (eieio--perform-slot-validation spec value)))
519 (signal 'invalid-slot-type (list (cl--slot-descriptor-name slot) spec value)))))
521 (defun eieio--slot-override (old new skipnil)
522 (cl-assert (eq (cl--slot-descriptor-name old) (cl--slot-descriptor-name new)))
523 ;; There is a match, and we must override the old value.
524 (let* ((a (cl--slot-descriptor-name old))
525 (tp (cl--slot-descriptor-type old))
526 (d (cl--slot-descriptor-initform new))
527 (type (cl--slot-descriptor-type new))
528 (oprops (cl--slot-descriptor-props old))
529 (nprops (cl--slot-descriptor-props new))
530 (custg (alist-get :group nprops)))
531 ;; If type is passed in, is it the same?
532 (if (not (eq type t))
533 (if (not (equal type tp))
534 (error
535 "Child slot type `%s' does not match inherited type `%s' for `%s'"
536 type tp a))
537 (setf (cl--slot-descriptor-type new) tp))
538 ;; If we have a repeat, only update the initarg...
539 (unless (eq d eieio-unbound)
540 (eieio--perform-slot-validation-for-default new skipnil)
541 (setf (cl--slot-descriptor-initform old) d))
543 ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
544 ;; checked and SHOULD match the superclass
545 ;; protection. Otherwise an error is thrown. However
546 ;; I wonder if a more flexible schedule might be
547 ;; implemented.
549 ;; EML - We used to have (if prot... here,
550 ;; but a prot of 'nil means public.
552 (let ((super-prot (alist-get :protection oprops))
553 (prot (alist-get :protection nprops)))
554 (if (not (eq prot super-prot))
555 (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
556 prot super-prot a)))
557 ;; End original PLN
559 ;; PLN Tue Jun 26 11:57:06 2007 :
560 ;; Do a non redundant combination of ancient custom
561 ;; groups and new ones.
562 (when custg
563 (let* ((list1 (alist-get :group oprops)))
564 (dolist (elt custg)
565 (unless (memq elt list1)
566 (push elt list1)))
567 (setf (alist-get :group (cl--slot-descriptor-props old)) list1)))
568 ;; End PLN
570 ;; PLN Mon Jun 25 22:44:34 2007 : If a new cust is
571 ;; set, simply replaces the old one.
572 (dolist (prop '(:custom :label :documentation :printer))
573 (when (alist-get prop (cl--slot-descriptor-props new))
574 (setf (alist-get prop (cl--slot-descriptor-props old))
575 (alist-get prop (cl--slot-descriptor-props new))))
577 ) ))
579 (defun eieio--add-new-slot (newc slot init alloc
580 &optional defaultoverride skipnil)
581 "Add into NEWC attribute SLOT.
582 If a slot of that name already exists in NEWC, then do nothing. If it doesn't exist,
583 INIT is the initarg, if any.
584 Argument ALLOC specifies if the slot is allocated per instance, or per class.
585 If optional DEFAULTOVERRIDE is non-nil, then if A exists in NEWC,
586 we must override its value for a default.
587 Optional argument SKIPNIL indicates if type checking should be skipped
588 if default value is nil."
589 ;; Make sure we duplicate those items that are sequences.
590 (let* ((a (cl--slot-descriptor-name slot))
591 (d (cl--slot-descriptor-initform slot))
592 (old (car (cl-member a (eieio--class-slots newc)
593 :key #'cl--slot-descriptor-name)))
594 (cold (car (cl-member a (eieio--class-class-slots newc)
595 :key #'cl--slot-descriptor-name))))
596 (cl-pushnew a eieio--known-slot-names)
597 (condition-case nil
598 (if (sequencep d) (setq d (copy-sequence d)))
599 ;; This copy can fail on a cons cell with a non-cons in the cdr. Let's
600 ;; skip it if it doesn't work.
601 (error nil))
602 ;; (if (sequencep type) (setq type (copy-sequence type)))
603 ;; (if (sequencep cust) (setq cust (copy-sequence cust)))
604 ;; (if (sequencep custg) (setq custg (copy-sequence custg)))
606 ;; To prevent override information w/out specification of storage,
607 ;; we need to do this little hack.
608 (if cold (setq alloc :class))
610 (if (memq alloc '(nil :instance))
611 ;; In this case, we modify the INSTANCE version of a given slot.
612 (progn
613 ;; Only add this element if it is so-far unique
614 (if (not old)
615 (progn
616 (eieio--perform-slot-validation-for-default slot skipnil)
617 (push slot (eieio--class-slots newc))
619 ;; When defaultoverride is true, we are usually adding new local
620 ;; attributes which must override the default value of any slot
621 ;; passed in by one of the parent classes.
622 (when defaultoverride
623 (eieio--slot-override old slot skipnil)))
624 (when init
625 (cl-pushnew (cons init a) (eieio--class-initarg-tuples newc)
626 :test #'equal)))
628 ;; CLASS ALLOCATED SLOTS
629 (if (not cold)
630 (progn
631 (eieio--perform-slot-validation-for-default slot skipnil)
632 ;; Here we have found a :class version of a slot. This
633 ;; requires a very different approach.
634 (push slot (eieio--class-class-slots newc)))
635 (when defaultoverride
636 ;; There is a match, and we must override the old value.
637 (eieio--slot-override cold slot skipnil))))))
639 (defun eieio-copy-parents-into-subclass (newc)
640 "Copy into NEWC the slots of PARENTS.
641 Follow the rules of not overwriting early parents when applying to
642 the new child class."
643 (let ((sn (eieio--class-option-assoc (eieio--class-options newc)
644 :allow-nil-initform)))
645 (dolist (pcv (eieio--class-parents newc))
646 ;; First, duplicate all the slots of the parent.
647 (let ((pslots (eieio--class-slots pcv))
648 (pinit (eieio--class-initarg-tuples pcv)))
649 (dotimes (i (length pslots))
650 (let* ((sd (cl--copy-slot-descriptor (aref pslots i)))
651 (init (car (rassq (cl--slot-descriptor-name sd) pinit))))
652 (eieio--add-new-slot newc sd init nil nil sn))
653 )) ;; while/let
654 ;; Now duplicate all the class alloc slots.
655 (let ((pcslots (eieio--class-class-slots pcv)))
656 (dotimes (i (length pcslots))
657 (eieio--add-new-slot newc (cl--copy-slot-descriptor
658 (aref pcslots i))
659 nil :class sn)
660 )))))
663 ;;; Slot type validation
665 ;; This is a hideous hack for replacing `typep' from cl-macs, to avoid
666 ;; requiring the CL library at run-time. It can be eliminated if/when
667 ;; `typep' is merged into Emacs core.
669 (defun eieio--perform-slot-validation (spec value)
670 "Return non-nil if SPEC does not match VALUE."
671 (or (eq spec t) ; t always passes
672 (eq value eieio-unbound) ; unbound always passes
673 (cl-typep value spec)))
675 (defun eieio--validate-slot-value (class slot-idx value slot)
676 "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
677 Checks the :type specifier.
678 SLOT is the slot that is being checked, and is only used when throwing
679 an error."
680 (if eieio-skip-typecheck
682 ;; Trim off object IDX junk added in for the object index.
683 (setq slot-idx (- slot-idx (eval-when-compile eieio--object-num-slots)))
684 (let ((st (cl--slot-descriptor-type (aref (eieio--class-slots class)
685 slot-idx))))
686 (if (not (eieio--perform-slot-validation st value))
687 (signal 'invalid-slot-type
688 (list (eieio--class-name class) slot st value))))))
690 (defun eieio--validate-class-slot-value (class slot-idx value slot)
691 "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
692 Checks the :type specifier.
693 SLOT is the slot that is being checked, and is only used when throwing
694 an error."
695 (if eieio-skip-typecheck
697 (let ((st (cl--slot-descriptor-type (aref (eieio--class-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-barf-if-slot-unbound (value instance slotname fn)
704 "Throw a signal if VALUE is a representation of an UNBOUND slot.
705 INSTANCE is the object being referenced. SLOTNAME is the offending
706 slot. If the slot is ok, return VALUE.
707 Argument FN is the function calling this verifier."
708 (if (and (eq value eieio-unbound) (not eieio-skip-typecheck))
709 (slot-unbound instance (eieio--object-class instance) slotname fn)
710 value))
713 ;;; Get/Set slots in an object.
715 (defun eieio-oref (obj slot)
716 "Return the value in OBJ at SLOT in the object vector."
717 (declare (compiler-macro
718 (lambda (exp)
719 (ignore obj)
720 (pcase slot
721 ((and (or `',name (and name (pred keywordp)))
722 (guard (not (memq name eieio--known-slot-names))))
723 (macroexp--warn-and-return
724 (format-message "Unknown slot `%S'" name) exp 'compile-only))
725 (_ exp)))))
726 (cl-check-type slot symbol)
727 (cl-check-type obj (or eieio-object class))
728 (let* ((class (cond ((symbolp obj)
729 (error "eieio-oref called on a class: %s" obj)
730 (let ((c (cl--find-class obj)))
731 (if (eieio--class-p c) (eieio-class-un-autoload obj))
733 (t (eieio--object-class obj))))
734 (c (eieio--slot-name-index class slot)))
735 (if (not c)
736 ;; It might be missing because it is a :class allocated slot.
737 ;; Let's check that info out.
738 (if (setq c (eieio--class-slot-name-index class slot))
739 ;; Oref that slot.
740 (aref (eieio--class-class-allocation-values class) c)
741 ;; The slot-missing method is a cool way of allowing an object author
742 ;; to intercept missing slot definitions. Since it is also the LAST
743 ;; thing called in this fn, its return value would be retrieved.
744 (slot-missing obj slot 'oref))
745 (cl-check-type obj eieio-object)
746 (eieio-barf-if-slot-unbound (aref obj c) obj slot 'oref))))
749 (defun eieio-oref-default (obj slot)
750 "Do the work for the macro `oref-default' with similar parameters.
751 Fills in OBJ's SLOT with its default value."
752 (cl-check-type obj (or eieio-object class))
753 (cl-check-type slot symbol)
754 (let* ((cl (cond ((symbolp obj) (cl--find-class obj))
755 ((eieio-object-p obj) (eieio--object-class obj))
756 (t obj)))
757 (c (eieio--slot-name-index cl slot)))
758 (if (not c)
759 ;; It might be missing because it is a :class allocated slot.
760 ;; Let's check that info out.
761 (if (setq c
762 (eieio--class-slot-name-index cl slot))
763 ;; Oref that slot.
764 (aref (eieio--class-class-allocation-values cl)
766 (slot-missing obj slot 'oref-default))
767 (eieio-barf-if-slot-unbound
768 (let ((val (cl--slot-descriptor-initform
769 (aref (eieio--class-slots cl)
770 (- c (eval-when-compile eieio--object-num-slots))))))
771 (eieio-default-eval-maybe val))
772 obj (eieio--class-name cl) 'oref-default))))
774 (defun eieio-default-eval-maybe (val)
775 "Check VAL, and return what `oref-default' would provide."
776 ;; FIXME: What the hell is this supposed to do? Shouldn't it evaluate
777 ;; variables as well? Why not just always call `eval'?
778 (cond
779 ;; Is it a function call? If so, evaluate it.
780 ((eieio-eval-default-p val)
781 (eval val))
782 ;;;; check for quoted things, and unquote them
783 ;;((and (consp val) (eq (car val) 'quote))
784 ;; (car (cdr val)))
785 ;; return it verbatim
786 (t val)))
788 (defun eieio-oset (obj slot value)
789 "Do the work for the macro `oset'.
790 Fills in OBJ's SLOT with VALUE."
791 (cl-check-type obj eieio-object)
792 (cl-check-type slot symbol)
793 (let* ((class (eieio--object-class obj))
794 (c (eieio--slot-name-index class slot)))
795 (if (not c)
796 ;; It might be missing because it is a :class allocated slot.
797 ;; Let's check that info out.
798 (if (setq c
799 (eieio--class-slot-name-index class slot))
800 ;; Oset that slot.
801 (progn
802 (eieio--validate-class-slot-value class c value slot)
803 (aset (eieio--class-class-allocation-values class)
804 c value))
805 ;; See oref for comment on `slot-missing'
806 (slot-missing obj slot 'oset value))
807 (eieio--validate-slot-value class c value slot)
808 (aset obj c value))))
810 (defun eieio-oset-default (class slot value)
811 "Do the work for the macro `oset-default'.
812 Fills in the default value in CLASS' in SLOT with VALUE."
813 (setq class (eieio--class-object class))
814 (cl-check-type class eieio--class)
815 (cl-check-type slot symbol)
816 (let* ((c (eieio--slot-name-index class slot)))
817 (if (not c)
818 ;; It might be missing because it is a :class allocated slot.
819 ;; Let's check that info out.
820 (if (setq c (eieio--class-slot-name-index class slot))
821 (progn
822 ;; Oref that slot.
823 (eieio--validate-class-slot-value class c value slot)
824 (aset (eieio--class-class-allocation-values class) c
825 value))
826 (signal 'invalid-slot-name (list (eieio--class-name class) slot)))
827 ;; `oset-default' on an instance-allocated slot is allowed by EIEIO but
828 ;; not by CLOS and is mildly inconsistent with the :initform thingy, so
829 ;; it'd be nice to get of it. This said, it is/was used at one place by
830 ;; gnus/registry.el, so it might be used elsewhere as well, so let's
831 ;; keep it for now.
832 ;; FIXME: Generate a compile-time warning for it!
833 ;; (error "Can't `oset-default' an instance-allocated slot: %S of %S"
834 ;; slot class)
835 (eieio--validate-slot-value class c value slot)
836 ;; Set this into the storage for defaults.
837 (if (eieio-eval-default-p value)
838 (error "Can't set default to a sexp that gets evaluated again"))
839 (setf (cl--slot-descriptor-initform
840 ;; FIXME: Apparently we set it both in `slots' and in
841 ;; `object-cache', which seems redundant.
842 (aref (eieio--class-slots class)
843 (- c (eval-when-compile eieio--object-num-slots))))
844 value)
845 ;; Take the value, and put it into our cache object.
846 (eieio-oset (eieio--class-default-object-cache class)
847 slot value)
851 ;;; EIEIO internal search functions
853 (defun eieio--slot-name-index (class slot)
854 "In CLASS find the index of the named SLOT.
855 The slot is a symbol which is installed in CLASS by the `defclass' call.
856 If SLOT is the value created with :initarg instead,
857 reverse-lookup that name, and recurse with the associated slot value."
858 ;; Removed checks to outside this call
859 (let* ((fsi (gethash slot (eieio--class-index-table class))))
860 (if (integerp fsi)
861 (+ (eval-when-compile eieio--object-num-slots) fsi)
862 (let ((fn (eieio--initarg-to-attribute class slot)))
863 (if fn
864 ;; Accessing a slot via its :initarg is accepted by EIEIO
865 ;; (but not CLOS) but is a bad idea (for one: it's slower).
866 ;; FIXME: We should emit a compile-time warning when this happens!
867 (eieio--slot-name-index class fn)
868 nil)))))
870 (defun eieio--class-slot-name-index (class slot)
871 "In CLASS find the index of the named SLOT.
872 The slot is a symbol which is installed in CLASS by the `defclass'
873 call. If SLOT is the value created with :initarg instead,
874 reverse-lookup that name, and recurse with the associated slot value."
875 ;; This will happen less often, and with fewer slots. Do this the
876 ;; storage cheap way.
877 (let ((index nil)
878 (slots (eieio--class-class-slots class)))
879 (dotimes (i (length slots))
880 (if (eq slot (cl--slot-descriptor-name (aref slots i)))
881 (setq index i)))
882 index))
885 ;; Way to assign slots based on a list. Used for constructors, or
886 ;; even resetting an object at run-time
888 (defun eieio-set-defaults (obj &optional set-all)
889 "Take object OBJ, and reset all slots to their defaults.
890 If SET-ALL is non-nil, then when a default is nil, that value is
891 reset. If SET-ALL is nil, the slots are only reset if the default is
892 not nil."
893 (let ((slots (eieio--class-slots (eieio--object-class obj))))
894 (dotimes (i (length slots))
895 (let* ((name (cl--slot-descriptor-name (aref slots i)))
896 (df (eieio-oref-default obj name)))
897 (if (or df set-all)
898 (eieio-oset obj name df))))))
900 (defun eieio--initarg-to-attribute (class initarg)
901 "For CLASS, convert INITARG to the actual attribute name.
902 If there is no translation, pass it in directly (so we can cheat if
903 need be... May remove that later...)"
904 (let ((tuple (assoc initarg (eieio--class-initarg-tuples class))))
905 (if tuple
906 (cdr tuple)
907 nil)))
910 ;; Method Invocation order: C3
911 (defun eieio--c3-candidate (class remaining-inputs)
912 "Return CLASS if it can go in the result now, otherwise nil."
913 ;; Ensure CLASS is not in any position but the first in any of the
914 ;; element lists of REMAINING-INPUTS.
915 (and (not (let ((found nil))
916 (while (and remaining-inputs (not found))
917 (setq found (member class (cdr (car remaining-inputs)))
918 remaining-inputs (cdr remaining-inputs)))
919 found))
920 class))
922 (defun eieio--c3-merge-lists (reversed-partial-result remaining-inputs)
923 "Merge REVERSED-PARTIAL-RESULT REMAINING-INPUTS in a consistent order, if possible.
924 If a consistent order does not exist, signal an error."
925 (setq remaining-inputs (delq nil remaining-inputs))
926 (if (null remaining-inputs)
927 ;; If all remaining inputs are empty lists, we are done.
928 (nreverse reversed-partial-result)
929 ;; Otherwise, we try to find the next element of the result. This
930 ;; is achieved by considering the first element of each
931 ;; (non-empty) input list and accepting a candidate if it is
932 ;; consistent with the rests of the input lists.
933 (let* ((found nil)
934 (tail remaining-inputs)
935 (next (progn
936 (while (and tail (not found))
937 (setq found (eieio--c3-candidate (caar tail)
938 remaining-inputs)
939 tail (cdr tail)))
940 found)))
941 (if next
942 ;; The graph is consistent so far, add NEXT to result and
943 ;; merge input lists, dropping NEXT from their heads where
944 ;; applicable.
945 (eieio--c3-merge-lists
946 (cons next reversed-partial-result)
947 (mapcar (lambda (l) (if (eq (cl-first l) next) (cl-rest l) l))
948 remaining-inputs))
949 ;; The graph is inconsistent, give up
950 (signal 'inconsistent-class-hierarchy (list remaining-inputs))))))
952 (defsubst eieio--class/struct-parents (class)
953 (or (eieio--class-parents class)
954 `(,eieio-default-superclass)))
956 (defun eieio--class-precedence-c3 (class)
957 "Return all parents of CLASS in c3 order."
958 (let ((parents (eieio--class-parents class)))
959 (eieio--c3-merge-lists
960 (list class)
961 (append
963 (mapcar #'eieio--class-precedence-c3 parents)
964 `((,eieio-default-superclass)))
965 (list parents))))
968 ;; Method Invocation Order: Depth First
970 (defun eieio--class-precedence-dfs (class)
971 "Return all parents of CLASS in depth-first order."
972 (let* ((parents (eieio--class-parents class))
973 (classes (copy-sequence
974 (apply #'append
975 (list class)
977 (mapcar
978 (lambda (parent)
979 (cons parent
980 (eieio--class-precedence-dfs parent)))
981 parents)
982 `((,eieio-default-superclass))))))
983 (tail classes))
984 ;; Remove duplicates.
985 (while tail
986 (setcdr tail (delq (car tail) (cdr tail)))
987 (setq tail (cdr tail)))
988 classes))
991 ;; Method Invocation Order: Breadth First
992 (defun eieio--class-precedence-bfs (class)
993 "Return all parents of CLASS in breadth-first order."
994 (let* ((result)
995 (queue (eieio--class/struct-parents class)))
996 (while queue
997 (let ((head (pop queue)))
998 (unless (member head result)
999 (push head result)
1000 (unless (eq head eieio-default-superclass)
1001 (setq queue (append queue (eieio--class/struct-parents head)))))))
1002 (cons class (nreverse result)))
1006 ;; Method Invocation Order
1008 (defun eieio--class-precedence-list (class)
1009 "Return (transitively closed) list of parents of CLASS.
1010 The order, in which the parents are returned depends on the
1011 method invocation orders of the involved classes."
1012 (if (or (null class) (eq class eieio-default-superclass))
1014 (unless (eieio--class-default-object-cache class)
1015 (eieio-class-un-autoload (eieio--class-name class)))
1016 (cl-case (eieio--class-method-invocation-order class)
1017 (:depth-first
1018 (eieio--class-precedence-dfs class))
1019 (:breadth-first
1020 (eieio--class-precedence-bfs class))
1021 (:c3
1022 (eieio--class-precedence-c3 class))))
1024 (define-obsolete-function-alias
1025 'class-precedence-list 'eieio--class-precedence-list "24.4")
1028 ;;; Here are some special types of errors
1030 (define-error 'invalid-slot-name "Invalid slot name")
1031 (define-error 'invalid-slot-type "Invalid slot type")
1032 (define-error 'unbound-slot "Unbound slot")
1033 (define-error 'inconsistent-class-hierarchy "Inconsistent class hierarchy")
1035 ;;; Hooking into cl-generic.
1037 (require 'cl-generic)
1039 ;;;; General support to dispatch based on the type of the argument.
1041 (cl-generic-define-generalizer eieio--generic-generalizer
1042 ;; Use the exact same tagcode as for cl-struct, so that methods
1043 ;; that dispatch on both kinds of objects get to share this
1044 ;; part of the dispatch code.
1045 50 #'cl--generic-struct-tag
1046 (lambda (tag &rest _)
1047 (let ((class (cl--find-class tag)))
1048 (and (eieio--class-p class)
1049 (mapcar #'eieio--class-name
1050 (eieio--class-precedence-list class))))))
1052 (cl-defmethod cl-generic-generalizers :extra "class" (specializer)
1053 "Support for dispatch on types defined by EIEIO's `defclass'."
1054 ;; CLHS says:
1055 ;; A class must be defined before it can be used as a parameter
1056 ;; specializer in a defmethod form.
1057 ;; So we can ignore types that are not known to denote classes.
1059 (and (eieio--class-p (eieio--class-object specializer))
1060 (list eieio--generic-generalizer))
1061 (cl-call-next-method)))
1063 ;;;; Dispatch for arguments which are classes.
1065 ;; Since EIEIO does not support metaclasses, users can't easily use the
1066 ;; "dispatch on argument type" for class arguments. That's why EIEIO's
1067 ;; `defmethod' added the :static qualifier. For cl-generic, such a qualifier
1068 ;; would not make much sense (e.g. to which argument should it apply?).
1069 ;; Instead, we add a new "subclass" specializer.
1071 (defun eieio--generic-subclass-specializers (tag &rest _)
1072 (when (eieio--class-p tag)
1073 (mapcar (lambda (class)
1074 `(subclass ,(eieio--class-name class)))
1075 (eieio--class-precedence-list tag))))
1077 (cl-generic-define-generalizer eieio--generic-subclass-generalizer
1078 60 (lambda (name &rest _) `(and (symbolp ,name) (cl--find-class ,name)))
1079 #'eieio--generic-subclass-specializers)
1081 (cl-defmethod cl-generic-generalizers ((_specializer (head subclass)))
1082 "Support for (subclass CLASS) specializers.
1083 These match if the argument is the name of a subclass of CLASS."
1084 (list eieio--generic-subclass-generalizer))
1086 (provide 'eieio-core)
1088 ;;; eieio-core.el ends here