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