Update copyright year to 2015
[emacs.git] / lisp / emacs-lisp / eieio-core.el
blob68b376592f518a51a5a956bd0d44582f98bf1022
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)
36 (put 'eieio--defalias 'byte-hunk-handler
37 #'byte-compile-file-form-defalias) ;;(get 'defalias 'byte-hunk-handler)
38 (defun eieio--defalias (name body)
39 "Like `defalias', but with less side-effects.
40 More specifically, it has no side-effects at all when the new function
41 definition is the same (`eq') as the old one."
42 (unless (and (fboundp name)
43 (eq (symbol-function name) body))
44 (defalias name body)))
46 ;;;
47 ;; A few functions that are better in the official EIEIO src, but
48 ;; used from the core.
49 (declare-function slot-unbound "eieio")
50 (declare-function slot-missing "eieio")
51 (declare-function child-of-class-p "eieio")
54 ;;;
55 ;; Variable declarations.
57 (defvar eieio-hook nil
58 "This hook is executed, then cleared each time `defclass' is called.")
60 (defvar eieio-error-unsupported-class-tags nil
61 "Non-nil to throw an error if an encountered tag is unsupported.
62 This may prevent classes from CLOS applications from being used with EIEIO
63 since EIEIO does not support all CLOS tags.")
65 (defvar eieio-skip-typecheck nil
66 "If non-nil, skip all slot typechecking.
67 Set this to t permanently if a program is functioning well to get a
68 small speed increase. This variable is also used internally to handle
69 default setting for optimization purposes.")
71 (defvar eieio-optimize-primary-methods-flag t
72 "Non-nil means to optimize the method dispatch on primary methods.")
74 (defvar eieio-initializing-object nil
75 "Set to non-nil while initializing an object.")
77 (defconst eieio-unbound
78 (if (and (boundp 'eieio-unbound) (symbolp eieio-unbound))
79 eieio-unbound
80 (make-symbol "unbound"))
81 "Uninterned symbol representing an unbound slot in an object.")
83 ;; This is a bootstrap for eieio-default-superclass so it has a value
84 ;; while it is being built itself.
85 (defvar eieio-default-superclass nil)
87 ;;;
88 ;; Class currently in scope.
90 ;; When invoking methods, the running method needs to know which class
91 ;; is currently in scope. Generally this is the class of the method
92 ;; being called, but 'call-next-method' needs to query this state,
93 ;; and change it to be then next super class up.
95 ;; Thus, the scoped class is a stack that needs to be managed.
97 (defvar eieio--scoped-class-stack nil
98 "A stack of the classes currently in scope during method invocation.")
100 (defun eieio--scoped-class ()
101 "Return the class currently in scope, or nil."
102 (car-safe eieio--scoped-class-stack))
104 (defmacro eieio--with-scoped-class (class &rest forms)
105 "Set CLASS as the currently scoped class while executing FORMS."
106 (declare (indent 1))
107 `(unwind-protect
108 (progn
109 (push ,class eieio--scoped-class-stack)
110 ,@forms)
111 (pop eieio--scoped-class-stack)))
114 ;; Field Accessors
116 (defmacro eieio--define-field-accessors (prefix fields)
117 (declare (indent 1))
118 (let ((index 0)
119 (defs '()))
120 (dolist (field fields)
121 (let ((doc (if (listp field)
122 (prog1 (cadr field) (setq field (car field))))))
123 (push `(defmacro ,(intern (format "eieio--%s-%s" prefix field)) (x)
124 ,@(if doc (list (format (if (string-match "\n" doc)
125 "Return %s" "Return %s of a %s.")
126 doc prefix)))
127 (list 'aref x ,index))
128 defs)
129 (setq index (1+ index))))
130 `(eval-and-compile
131 ,@(nreverse defs)
132 (defconst ,(intern (format "eieio--%s-num-slots" prefix)) ,index))))
134 (eieio--define-field-accessors class
135 (-unused-0 ;;FIXME: not sure, but at least there was no accessor!
136 (symbol "symbol (self-referencing)")
137 parent children
138 (symbol-obarray "obarray permitting fast access to variable position indexes")
139 ;; @todo
140 ;; the word "public" here is leftovers from the very first version.
141 ;; Get rid of it!
142 (public-a "class attribute index")
143 (public-d "class attribute defaults index")
144 (public-doc "class documentation strings for attributes")
145 (public-type "class type for a slot")
146 (public-custom "class custom type for a slot")
147 (public-custom-label "class custom group for a slot")
148 (public-custom-group "class custom group for a slot")
149 (public-printer "printer for a slot")
150 (protection "protection for a slot")
151 (initarg-tuples "initarg tuples list")
152 (class-allocation-a "class allocated attributes")
153 (class-allocation-doc "class allocated documentation")
154 (class-allocation-type "class allocated value type")
155 (class-allocation-custom "class allocated custom descriptor")
156 (class-allocation-custom-label "class allocated custom descriptor")
157 (class-allocation-custom-group "class allocated custom group")
158 (class-allocation-printer "class allocated printer for a slot")
159 (class-allocation-protection "class allocated protection list")
160 (class-allocation-values "class allocated value vector")
161 (default-object-cache "what a newly created object would look like.
162 This will speed up instantiation time as only a `copy-sequence' will
163 be needed, instead of looping over all the values and setting them
164 from the default.")
165 (options "storage location of tagged class options.
166 Stored outright without modifications or stripping.")))
168 (eieio--define-field-accessors object
169 (-unused-0 ;;FIXME: not sure, but at least there was no accessor!
170 (class "class struct defining OBJ")
171 name))
173 ;; FIXME: The constants below should have an `eieio-' prefix added!!
175 (defconst method-static 0 "Index into :static tag on a method.")
176 (defconst method-before 1 "Index into :before tag on a method.")
177 (defconst method-primary 2 "Index into :primary tag on a method.")
178 (defconst method-after 3 "Index into :after tag on a method.")
179 (defconst method-num-lists 4 "Number of indexes into methods vector in which groups of functions are kept.")
180 (defconst method-generic-before 4 "Index into generic :before tag on a method.")
181 (defconst method-generic-primary 5 "Index into generic :primary tag on a method.")
182 (defconst method-generic-after 6 "Index into generic :after tag on a method.")
183 (defconst method-num-slots 7 "Number of indexes into a method's vector.")
185 (defsubst eieio-specialized-key-to-generic-key (key)
186 "Convert a specialized KEY into a generic method key."
187 (cond ((eq key method-static) 0) ;; don't convert
188 ((< key method-num-lists) (+ key 3)) ;; The conversion
189 (t key) ;; already generic.. maybe.
193 ;;; Important macros used internally in eieio.
195 (defmacro eieio--check-type (type obj)
196 (unless (symbolp obj)
197 (error "eieio--check-type wants OBJ to be a variable"))
198 `(if (not ,(cond
199 ((eq 'or (car-safe type))
200 `(or ,@(mapcar (lambda (type) `(,type ,obj)) (cdr type))))
201 (t `(,type ,obj))))
202 (signal 'wrong-type-argument (list ',type ,obj))))
204 (defmacro class-v (class)
205 "Internal: Return the class vector from the CLASS symbol."
206 ;; No check: If eieio gets this far, it has probably been checked already.
207 `(get ,class 'eieio-class-definition))
209 (defsubst class-p (class)
210 "Return non-nil if CLASS is a valid class vector.
211 CLASS is a symbol."
212 ;; this new method is faster since it doesn't waste time checking lots of
213 ;; things.
214 (condition-case nil
215 (eq (aref (class-v class) 0) 'defclass)
216 (error nil)))
218 (defun eieio-class-name (class) "Return a Lisp like symbol name for CLASS."
219 (eieio--check-type class-p class)
220 ;; I think this is supposed to return a symbol, but to me CLASS is a symbol,
221 ;; and I wanted a string. Arg!
222 (format "#<class %s>" (symbol-name class)))
223 (define-obsolete-function-alias 'class-name #'eieio-class-name "24.4")
225 (defmacro eieio-class-parents-fast (class)
226 "Return parent classes to CLASS with no check."
227 `(eieio--class-parent (class-v ,class)))
229 (defmacro eieio-class-children-fast (class) "Return child classes to CLASS with no check."
230 `(eieio--class-children (class-v ,class)))
232 (defmacro same-class-fast-p (obj class)
233 "Return t if OBJ is of class-type CLASS with no error checking."
234 `(eq (eieio--object-class ,obj) ,class))
236 (defmacro class-constructor (class)
237 "Return the symbol representing the constructor of CLASS."
238 `(eieio--class-symbol (class-v ,class)))
240 (defsubst generic-p (method)
241 "Return non-nil if symbol METHOD is a generic function.
242 Only methods have the symbol `eieio-method-obarray' as a property
243 \(which contains a list of all bindings to that method type.)"
244 (and (fboundp method) (get method 'eieio-method-obarray)))
246 (defun generic-primary-only-p (method)
247 "Return t if symbol METHOD is a generic function with only primary methods.
248 Only methods have the symbol `eieio-method-obarray' as a property (which
249 contains a list of all bindings to that method type.)
250 Methods with only primary implementations are executed in an optimized way."
251 (and (generic-p method)
252 (let ((M (get method 'eieio-method-tree)))
253 (and (< 0 (length (aref M method-primary)))
254 (not (aref M method-static))
255 (not (aref M method-before))
256 (not (aref M method-after))
257 (not (aref M method-generic-before))
258 (not (aref M method-generic-primary))
259 (not (aref M method-generic-after))))
262 (defun generic-primary-only-one-p (method)
263 "Return t if symbol METHOD is a generic function with only primary methods.
264 Only methods have the symbol `eieio-method-obarray' as a property (which
265 contains a list of all bindings to that method type.)
266 Methods with only primary implementations are executed in an optimized way."
267 (and (generic-p method)
268 (let ((M (get method 'eieio-method-tree)))
269 (and (= 1 (length (aref M method-primary)))
270 (not (aref M method-static))
271 (not (aref M method-before))
272 (not (aref M method-after))
273 (not (aref M method-generic-before))
274 (not (aref M method-generic-primary))
275 (not (aref M method-generic-after))))
278 (defmacro class-option-assoc (list option)
279 "Return from LIST the found OPTION, or nil if it doesn't exist."
280 `(car-safe (cdr (memq ,option ,list))))
282 (defmacro class-option (class option)
283 "Return the value stored for CLASS' OPTION.
284 Return nil if that option doesn't exist."
285 `(class-option-assoc (eieio--class-options (class-v ,class)) ',option))
287 (defsubst eieio-object-p (obj)
288 "Return non-nil if OBJ is an EIEIO object."
289 (condition-case nil
290 (and (eq (aref obj 0) 'object)
291 (class-p (eieio--object-class obj)))
292 (error nil)))
293 (defalias 'object-p 'eieio-object-p)
295 (defsubst class-abstract-p (class)
296 "Return non-nil if CLASS is abstract.
297 Abstract classes cannot be instantiated."
298 (class-option class :abstract))
300 (defmacro class-method-invocation-order (class)
301 "Return the invocation order of CLASS.
302 Abstract classes cannot be instantiated."
303 `(or (class-option ,class :method-invocation-order)
304 :breadth-first))
309 ;; Class Creation
311 (defvar eieio-defclass-autoload-map (make-vector 7 nil)
312 "Symbol map of superclasses we find in autoloads.")
314 ;; We autoload this because it's used in `make-autoload'.
315 ;;;###autoload
316 (defun eieio-defclass-autoload (cname superclasses filename doc)
317 "Create autoload symbols for the EIEIO class CNAME.
318 SUPERCLASSES are the superclasses that CNAME inherits from.
319 DOC is the docstring for CNAME.
320 This function creates a mock-class for CNAME and adds it into
321 SUPERCLASSES as children.
322 It creates an autoload function for CNAME's constructor."
323 ;; Assume we've already debugged inputs.
325 (let* ((oldc (when (class-p cname) (class-v cname)))
326 (newc (make-vector eieio--class-num-slots nil))
328 (if oldc
329 nil ;; Do nothing if we already have this class.
331 ;; Create the class in NEWC, but don't fill anything else in.
332 (aset newc 0 'defclass)
333 (setf (eieio--class-symbol newc) cname)
335 (let ((clear-parent nil))
336 ;; No parents?
337 (when (not superclasses)
338 (setq superclasses '(eieio-default-superclass)
339 clear-parent t)
342 ;; Hook our new class into the existing structures so we can
343 ;; autoload it later.
344 (dolist (SC superclasses)
347 ;; TODO - If we create an autoload that is in the map, that
348 ;; map needs to be cleared!
351 ;; Does our parent exist?
352 (if (not (class-p SC))
354 ;; Create a symbol for this parent, and then store this
355 ;; parent on that symbol.
356 (let ((sym (intern (symbol-name SC) eieio-defclass-autoload-map)))
357 (if (not (boundp sym))
358 (set sym (list cname))
359 (add-to-list sym cname))
362 ;; We have a parent, save the child in there.
363 (when (not (member cname (eieio--class-children (class-v SC))))
364 (setf (eieio--class-children (class-v SC))
365 (cons cname (eieio--class-children (class-v SC))))))
367 ;; save parent in child
368 (setf (eieio--class-parent newc) (cons SC (eieio--class-parent newc)))
371 ;; turn this into a usable self-pointing symbol
372 (set cname cname)
374 ;; Store the new class vector definition into the symbol. We need to
375 ;; do this first so that we can call defmethod for the accessor.
376 ;; The vector will be updated by the following while loop and will not
377 ;; need to be stored a second time.
378 (put cname 'eieio-class-definition newc)
380 ;; Clear the parent
381 (if clear-parent (setf (eieio--class-parent newc) nil))
383 ;; Create an autoload on top of our constructor function.
384 (autoload cname filename doc nil nil)
385 (autoload (intern (concat (symbol-name cname) "-p")) filename "" nil nil)
386 (autoload (intern (concat (symbol-name cname) "-child-p")) filename "" nil nil)
387 (autoload (intern (concat (symbol-name cname) "-list-p")) filename "" nil nil)
389 ))))
391 (defsubst eieio-class-un-autoload (cname)
392 "If class CNAME is in an autoload state, load its file."
393 (when (eq (car-safe (symbol-function cname)) 'autoload)
394 (load-library (car (cdr (symbol-function cname))))))
396 (cl-deftype list-of (elem-type)
397 `(and list
398 (satisfies (lambda (list)
399 (cl-every (lambda (elem) (cl-typep elem ',elem-type))
400 list)))))
402 (defun eieio-defclass (cname superclasses slots options-and-doc)
403 ;; FIXME: Most of this should be moved to the `defclass' macro.
404 "Define CNAME as a new subclass of SUPERCLASSES.
405 SLOTS are the slots residing in that class definition, and options or
406 documentation OPTIONS-AND-DOC is the toplevel documentation for this class.
407 See `defclass' for more information."
408 ;; Run our eieio-hook each time, and clear it when we are done.
409 ;; This way people can add hooks safely if they want to modify eieio
410 ;; or add definitions when eieio is loaded or something like that.
411 (run-hooks 'eieio-hook)
412 (setq eieio-hook nil)
414 (eieio--check-type listp superclasses)
416 (let* ((pname superclasses)
417 (newc (make-vector eieio--class-num-slots nil))
418 (oldc (when (class-p cname) (class-v cname)))
419 (groups nil) ;; list of groups id'd from slots
420 (options nil)
421 (clearparent nil))
423 (aset newc 0 'defclass)
424 (setf (eieio--class-symbol newc) cname)
426 ;; If this class already existed, and we are updating its structure,
427 ;; make sure we keep the old child list. This can cause bugs, but
428 ;; if no new slots are created, it also saves time, and prevents
429 ;; method table breakage, particularly when the users is only
430 ;; byte compiling an EIEIO file.
431 (if oldc
432 (setf (eieio--class-children newc) (eieio--class-children oldc))
433 ;; If the old class did not exist, but did exist in the autoload map, then adopt those children.
434 ;; This is like the above, but deals with autoloads nicely.
435 (let ((sym (intern-soft (symbol-name cname) eieio-defclass-autoload-map)))
436 (when sym
437 (condition-case nil
438 (setf (eieio--class-children newc) (symbol-value sym))
439 (error nil))
440 (unintern (symbol-name cname) eieio-defclass-autoload-map)
444 (cond ((and (stringp (car options-and-doc))
445 (/= 1 (% (length options-and-doc) 2)))
446 (error "Too many arguments to `defclass'"))
447 ((and (symbolp (car options-and-doc))
448 (/= 0 (% (length options-and-doc) 2)))
449 (error "Too many arguments to `defclass'"))
452 (setq options
453 (if (stringp (car options-and-doc))
454 (cons :documentation options-and-doc)
455 options-and-doc))
457 (if pname
458 (progn
459 (while pname
460 (if (and (car pname) (symbolp (car pname)))
461 (if (not (class-p (car pname)))
462 ;; bad class
463 (error "Given parent class %s is not a class" (car pname))
464 ;; good parent class...
465 ;; save new child in parent
466 (when (not (member cname (eieio--class-children (class-v (car pname)))))
467 (setf (eieio--class-children (class-v (car pname)))
468 (cons cname (eieio--class-children (class-v (car pname))))))
469 ;; Get custom groups, and store them into our local copy.
470 (mapc (lambda (g) (cl-pushnew g groups :test #'equal))
471 (class-option (car pname) :custom-groups))
472 ;; save parent in child
473 (setf (eieio--class-parent newc) (cons (car pname) (eieio--class-parent newc))))
474 (error "Invalid parent class %s" pname))
475 (setq pname (cdr pname)))
476 ;; Reverse the list of our parents so that they are prioritized in
477 ;; the same order as specified in the code.
478 (setf (eieio--class-parent newc) (nreverse (eieio--class-parent newc))) )
479 ;; If there is nothing to loop over, then inherit from the
480 ;; default superclass.
481 (unless (eq cname 'eieio-default-superclass)
482 ;; adopt the default parent here, but clear it later...
483 (setq clearparent t)
484 ;; save new child in parent
485 (if (not (member cname (eieio--class-children (class-v 'eieio-default-superclass))))
486 (setf (eieio--class-children (class-v 'eieio-default-superclass))
487 (cons cname (eieio--class-children (class-v 'eieio-default-superclass)))))
488 ;; save parent in child
489 (setf (eieio--class-parent newc) (list eieio-default-superclass))))
491 ;; turn this into a usable self-pointing symbol
492 (set cname cname)
494 ;; These two tests must be created right away so we can have self-
495 ;; referencing classes. ei, a class whose slot can contain only
496 ;; pointers to itself.
498 ;; Create the test function
499 (let ((csym (intern (concat (symbol-name cname) "-p"))))
500 (fset csym
501 (list 'lambda (list 'obj)
502 (format "Test OBJ to see if it an object of type %s" cname)
503 (list 'and '(eieio-object-p obj)
504 (list 'same-class-p 'obj cname)))))
506 ;; Make sure the method invocation order is a valid value.
507 (let ((io (class-option-assoc options :method-invocation-order)))
508 (when (and io (not (member io '(:depth-first :breadth-first :c3))))
509 (error "Method invocation order %s is not allowed" io)
512 ;; Create a handy child test too
513 (let ((csym (intern (concat (symbol-name cname) "-child-p"))))
514 (fset csym
515 `(lambda (obj)
516 ,(format
517 "Test OBJ to see if it an object is a child of type %s"
518 cname)
519 (and (eieio-object-p obj)
520 (object-of-class-p obj ,cname))))
522 ;; Create a handy list of the class test too
523 (let ((csym (intern (concat (symbol-name cname) "-list-p"))))
524 (fset csym
525 `(lambda (obj)
526 ,(format
527 "Test OBJ to see if it a list of objects which are a child of type %s"
528 cname)
529 (when (listp obj)
530 (let ((ans t)) ;; nil is valid
531 ;; Loop over all the elements of the input list, test
532 ;; each to make sure it is a child of the desired object class.
533 (while (and obj ans)
534 (setq ans (and (eieio-object-p (car obj))
535 (object-of-class-p (car obj) ,cname)))
536 (setq obj (cdr obj)))
537 ans)))))
539 ;; When using typep, (typep OBJ 'myclass) returns t for objects which
540 ;; are subclasses of myclass. For our predicates, however, it is
541 ;; important for EIEIO to be backwards compatible, where
542 ;; myobject-p, and myobject-child-p are different.
543 ;; "cl" uses this technique to specify symbols with specific typep
544 ;; test, so we can let typep have the CLOS documented behavior
545 ;; while keeping our above predicate clean.
547 ;; FIXME: It would be cleaner to use `cl-deftype' here.
548 (put cname 'cl-deftype-handler
549 (list 'lambda () `(list 'satisfies (quote ,csym)))))
551 ;; Before adding new slots, let's add all the methods and classes
552 ;; in from the parent class.
553 (eieio-copy-parents-into-subclass newc superclasses)
555 ;; Store the new class vector definition into the symbol. We need to
556 ;; do this first so that we can call defmethod for the accessor.
557 ;; The vector will be updated by the following while loop and will not
558 ;; need to be stored a second time.
559 (put cname 'eieio-class-definition newc)
561 ;; Query each slot in the declaration list and mangle into the
562 ;; class structure I have defined.
563 (while slots
564 (let* ((slot1 (car slots))
565 (name (car slot1))
566 (slot (cdr slot1))
567 (acces (plist-get slot ':accessor))
568 (init (or (plist-get slot ':initform)
569 (if (member ':initform slot) nil
570 eieio-unbound)))
571 (initarg (plist-get slot ':initarg))
572 (docstr (plist-get slot ':documentation))
573 (prot (plist-get slot ':protection))
574 (reader (plist-get slot ':reader))
575 (writer (plist-get slot ':writer))
576 (alloc (plist-get slot ':allocation))
577 (type (plist-get slot ':type))
578 (custom (plist-get slot ':custom))
579 (label (plist-get slot ':label))
580 (customg (plist-get slot ':group))
581 (printer (plist-get slot ':printer))
583 (skip-nil (class-option-assoc options :allow-nil-initform))
586 (if eieio-error-unsupported-class-tags
587 (let ((tmp slot))
588 (while tmp
589 (if (not (member (car tmp) '(:accessor
590 :initform
591 :initarg
592 :documentation
593 :protection
594 :reader
595 :writer
596 :allocation
597 :type
598 :custom
599 :label
600 :group
601 :printer
602 :allow-nil-initform
603 :custom-groups)))
604 (signal 'invalid-slot-type (list (car tmp))))
605 (setq tmp (cdr (cdr tmp))))))
607 ;; Clean up the meaning of protection.
608 (cond ((or (eq prot 'public) (eq prot :public)) (setq prot nil))
609 ((or (eq prot 'protected) (eq prot :protected)) (setq prot 'protected))
610 ((or (eq prot 'private) (eq prot :private)) (setq prot 'private))
611 ((eq prot nil) nil)
612 (t (signal 'invalid-slot-type (list ':protection prot))))
614 ;; Make sure the :allocation parameter has a valid value.
615 (if (not (or (not alloc) (eq alloc :class) (eq alloc :instance)))
616 (signal 'invalid-slot-type (list ':allocation alloc)))
618 ;; The default type specifier is supposed to be t, meaning anything.
619 (if (not type) (setq type t))
621 ;; Label is nil, or a string
622 (if (not (or (null label) (stringp label)))
623 (signal 'invalid-slot-type (list ':label label)))
625 ;; Is there an initarg, but allocation of class?
626 (if (and initarg (eq alloc :class))
627 (message "Class allocated slots do not need :initarg"))
629 ;; intern the symbol so we can use it blankly
630 (if initarg (set initarg initarg))
632 ;; The customgroup should be a list of symbols
633 (cond ((null customg)
634 (setq customg '(default)))
635 ((not (listp customg))
636 (setq customg (list customg))))
637 ;; The customgroup better be a symbol, or list of symbols.
638 (mapc (lambda (cg)
639 (if (not (symbolp cg))
640 (signal 'invalid-slot-type (list ':group cg))))
641 customg)
643 ;; First up, add this slot into our new class.
644 (eieio-add-new-slot newc name init docstr type custom label customg printer
645 prot initarg alloc 'defaultoverride skip-nil)
647 ;; We need to id the group, and store them in a group list attribute.
648 (mapc (lambda (cg) (cl-pushnew cg groups :test 'equal)) customg)
650 ;; Anyone can have an accessor function. This creates a function
651 ;; of the specified name, and also performs a `defsetf' if applicable
652 ;; so that users can `setf' the space returned by this function.
653 (if acces
654 (progn
655 (eieio--defmethod
656 acces (if (eq alloc :class) :static :primary) cname
657 `(lambda (this)
658 ,(format
659 "Retrieves the slot `%s' from an object of class `%s'"
660 name cname)
661 (if (slot-boundp this ',name)
662 (eieio-oref this ',name)
663 ;; Else - Some error? nil?
664 nil)))
666 ;; FIXME: We should move more of eieio-defclass into the
667 ;; defclass macro so we don't have to use `eval' and require
668 ;; `gv' at run-time.
669 (eval `(gv-define-setter ,acces (eieio--store eieio--object)
670 (list 'eieio-oset eieio--object '',name
671 eieio--store)))))
673 ;; If a writer is defined, then create a generic method of that
674 ;; name whose purpose is to set the value of the slot.
675 (if writer
676 (eieio--defmethod
677 writer nil cname
678 `(lambda (this value)
679 ,(format "Set the slot `%s' of an object of class `%s'"
680 name cname)
681 (setf (slot-value this ',name) value))))
682 ;; If a reader is defined, then create a generic method
683 ;; of that name whose purpose is to access this slot value.
684 (if reader
685 (eieio--defmethod
686 reader nil cname
687 `(lambda (this)
688 ,(format "Access the slot `%s' from object of class `%s'"
689 name cname)
690 (slot-value this ',name))))
692 (setq slots (cdr slots)))
694 ;; Now that everything has been loaded up, all our lists are backwards!
695 ;; Fix that up now.
696 (setf (eieio--class-public-a newc) (nreverse (eieio--class-public-a newc)))
697 (setf (eieio--class-public-d newc) (nreverse (eieio--class-public-d newc)))
698 (setf (eieio--class-public-doc newc) (nreverse (eieio--class-public-doc newc)))
699 (setf (eieio--class-public-type newc)
700 (apply #'vector (nreverse (eieio--class-public-type newc))))
701 (setf (eieio--class-public-custom newc) (nreverse (eieio--class-public-custom newc)))
702 (setf (eieio--class-public-custom-label newc) (nreverse (eieio--class-public-custom-label newc)))
703 (setf (eieio--class-public-custom-group newc) (nreverse (eieio--class-public-custom-group newc)))
704 (setf (eieio--class-public-printer newc) (nreverse (eieio--class-public-printer newc)))
705 (setf (eieio--class-protection newc) (nreverse (eieio--class-protection newc)))
706 (setf (eieio--class-initarg-tuples newc) (nreverse (eieio--class-initarg-tuples newc)))
708 ;; The storage for class-class-allocation-type needs to be turned into
709 ;; a vector now.
710 (setf (eieio--class-class-allocation-type newc)
711 (apply #'vector (eieio--class-class-allocation-type newc)))
713 ;; Also, take class allocated values, and vectorize them for speed.
714 (setf (eieio--class-class-allocation-values newc)
715 (apply #'vector (eieio--class-class-allocation-values newc)))
717 ;; Attach slot symbols into an obarray, and store the index of
718 ;; this slot as the variable slot in this new symbol. We need to
719 ;; know about primes, because obarrays are best set in vectors of
720 ;; prime number length, and we also need to make our vector small
721 ;; to save space, and also optimal for the number of items we have.
722 (let* ((cnt 0)
723 (pubsyms (eieio--class-public-a newc))
724 (prots (eieio--class-protection newc))
725 (l (length pubsyms))
726 (vl (let ((primes '( 3 5 7 11 13 17 19 23 29 31 37 41 43 47
727 53 59 61 67 71 73 79 83 89 97 101 )))
728 (while (and primes (< (car primes) l))
729 (setq primes (cdr primes)))
730 (car primes)))
731 (oa (make-vector vl 0))
732 (newsym))
733 (while pubsyms
734 (setq newsym (intern (symbol-name (car pubsyms)) oa))
735 (set newsym cnt)
736 (setq cnt (1+ cnt))
737 (if (car prots) (put newsym 'protection (car prots)))
738 (setq pubsyms (cdr pubsyms)
739 prots (cdr prots)))
740 (setf (eieio--class-symbol-obarray newc) oa)
743 ;; Create the constructor function
744 (if (class-option-assoc options :abstract)
745 ;; Abstract classes cannot be instantiated. Say so.
746 (let ((abs (class-option-assoc options :abstract)))
747 (if (not (stringp abs))
748 (setq abs (format "Class %s is abstract" cname)))
749 (fset cname
750 `(lambda (&rest stuff)
751 ,(format "You cannot create a new object of type %s" cname)
752 (error ,abs))))
754 ;; Non-abstract classes need a constructor.
755 (fset cname
756 `(lambda (newname &rest slots)
757 ,(format "Create a new object with name NAME of class type %s" cname)
758 (apply #'constructor ,cname newname slots)))
761 ;; Set up a specialized doc string.
762 ;; Use stored value since it is calculated in a non-trivial way
763 (put cname 'variable-documentation
764 (class-option-assoc options :documentation))
766 ;; Save the file location where this class is defined.
767 (let ((fname (if load-in-progress
768 load-file-name
769 buffer-file-name)))
770 (when fname
771 (when (string-match "\\.elc\\'" fname)
772 (setq fname (substring fname 0 (1- (length fname)))))
773 (put cname 'class-location fname)))
775 ;; We have a list of custom groups. Store them into the options.
776 (let ((g (class-option-assoc options :custom-groups)))
777 (mapc (lambda (cg) (cl-pushnew cg g :test 'equal)) groups)
778 (if (memq :custom-groups options)
779 (setcar (cdr (memq :custom-groups options)) g)
780 (setq options (cons :custom-groups (cons g options)))))
782 ;; Set up the options we have collected.
783 (setf (eieio--class-options newc) options)
785 ;; if this is a superclass, clear out parent (which was set to the
786 ;; default superclass eieio-default-superclass)
787 (if clearparent (setf (eieio--class-parent newc) nil))
789 ;; Create the cached default object.
790 (let ((cache (make-vector (+ (length (eieio--class-public-a newc)) 3)
791 nil)))
792 (aset cache 0 'object)
793 (setf (eieio--object-class cache) cname)
794 (setf (eieio--object-name cache) 'default-cache-object)
795 (let ((eieio-skip-typecheck t))
796 ;; All type-checking has been done to our satisfaction
797 ;; before this call. Don't waste our time in this call..
798 (eieio-set-defaults cache t))
799 (setf (eieio--class-default-object-cache newc) cache))
801 ;; Return our new class object
802 ;; newc
803 cname
806 (defsubst eieio-eval-default-p (val)
807 "Whether the default value VAL should be evaluated for use."
808 (and (consp val) (symbolp (car val)) (fboundp (car val))))
810 (defun eieio-perform-slot-validation-for-default (slot spec value skipnil)
811 "For SLOT, signal if SPEC does not match VALUE.
812 If SKIPNIL is non-nil, then if VALUE is nil return t instead."
813 (if (and (not (eieio-eval-default-p value))
814 (not eieio-skip-typecheck)
815 (not (and skipnil (null value)))
816 (not (eieio-perform-slot-validation spec value)))
817 (signal 'invalid-slot-type (list slot spec value))))
819 (defun eieio-add-new-slot (newc a d doc type cust label custg print prot init alloc
820 &optional defaultoverride skipnil)
821 "Add into NEWC attribute A.
822 If A already exists in NEWC, then do nothing. If it doesn't exist,
823 then also add in D (default), DOC, TYPE, CUST, LABEL, CUSTG, PRINT, PROT, and INIT arg.
824 Argument ALLOC specifies if the slot is allocated per instance, or per class.
825 If optional DEFAULTOVERRIDE is non-nil, then if A exists in NEWC,
826 we must override its value for a default.
827 Optional argument SKIPNIL indicates if type checking should be skipped
828 if default value is nil."
829 ;; Make sure we duplicate those items that are sequences.
830 (condition-case nil
831 (if (sequencep d) (setq d (copy-sequence d)))
832 ;; This copy can fail on a cons cell with a non-cons in the cdr. Let's skip it if it doesn't work.
833 (error nil))
834 (if (sequencep type) (setq type (copy-sequence type)))
835 (if (sequencep cust) (setq cust (copy-sequence cust)))
836 (if (sequencep custg) (setq custg (copy-sequence custg)))
838 ;; To prevent override information w/out specification of storage,
839 ;; we need to do this little hack.
840 (if (member a (eieio--class-class-allocation-a newc)) (setq alloc ':class))
842 (if (or (not alloc) (and (symbolp alloc) (eq alloc ':instance)))
843 ;; In this case, we modify the INSTANCE version of a given slot.
845 (progn
847 ;; Only add this element if it is so-far unique
848 (if (not (member a (eieio--class-public-a newc)))
849 (progn
850 (eieio-perform-slot-validation-for-default a type d skipnil)
851 (setf (eieio--class-public-a newc) (cons a (eieio--class-public-a newc)))
852 (setf (eieio--class-public-d newc) (cons d (eieio--class-public-d newc)))
853 (setf (eieio--class-public-doc newc) (cons doc (eieio--class-public-doc newc)))
854 (setf (eieio--class-public-type newc) (cons type (eieio--class-public-type newc)))
855 (setf (eieio--class-public-custom newc) (cons cust (eieio--class-public-custom newc)))
856 (setf (eieio--class-public-custom-label newc) (cons label (eieio--class-public-custom-label newc)))
857 (setf (eieio--class-public-custom-group newc) (cons custg (eieio--class-public-custom-group newc)))
858 (setf (eieio--class-public-printer newc) (cons print (eieio--class-public-printer newc)))
859 (setf (eieio--class-protection newc) (cons prot (eieio--class-protection newc)))
860 (setf (eieio--class-initarg-tuples newc) (cons (cons init a) (eieio--class-initarg-tuples newc)))
862 ;; When defaultoverride is true, we are usually adding new local
863 ;; attributes which must override the default value of any slot
864 ;; passed in by one of the parent classes.
865 (when defaultoverride
866 ;; There is a match, and we must override the old value.
867 (let* ((ca (eieio--class-public-a newc))
868 (np (member a ca))
869 (num (- (length ca) (length np)))
870 (dp (if np (nthcdr num (eieio--class-public-d newc))
871 nil))
872 (tp (if np (nth num (eieio--class-public-type newc))))
874 (if (not np)
875 (error "EIEIO internal error overriding default value for %s"
877 ;; If type is passed in, is it the same?
878 (if (not (eq type t))
879 (if (not (equal type tp))
880 (error
881 "Child slot type `%s' does not match inherited type `%s' for `%s'"
882 type tp a)))
883 ;; If we have a repeat, only update the initarg...
884 (unless (eq d eieio-unbound)
885 (eieio-perform-slot-validation-for-default a tp d skipnil)
886 (setcar dp d))
887 ;; If we have a new initarg, check for it.
888 (when init
889 (let* ((inits (eieio--class-initarg-tuples newc))
890 (inita (rassq a inits)))
891 ;; Replace the CAR of the associate INITA.
892 ;;(message "Initarg: %S replace %s" inita init)
893 (setcar inita init)
896 ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
897 ;; checked and SHOULD match the superclass
898 ;; protection. Otherwise an error is thrown. However
899 ;; I wonder if a more flexible schedule might be
900 ;; implemented.
902 ;; EML - We used to have (if prot... here,
903 ;; but a prot of 'nil means public.
905 (let ((super-prot (nth num (eieio--class-protection newc)))
907 (if (not (eq prot super-prot))
908 (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
909 prot super-prot a)))
910 ;; End original PLN
912 ;; PLN Tue Jun 26 11:57:06 2007 :
913 ;; Do a non redundant combination of ancient custom
914 ;; groups and new ones.
915 (when custg
916 (let* ((groups
917 (nthcdr num (eieio--class-public-custom-group newc)))
918 (list1 (car groups))
919 (list2 (if (listp custg) custg (list custg))))
920 (if (< (length list1) (length list2))
921 (setq list1 (prog1 list2 (setq list2 list1))))
922 (dolist (elt list2)
923 (unless (memq elt list1)
924 (push elt list1)))
925 (setcar groups list1)))
926 ;; End PLN
928 ;; PLN Mon Jun 25 22:44:34 2007 : If a new cust is
929 ;; set, simply replaces the old one.
930 (when cust
931 ;; (message "Custom type redefined to %s" cust)
932 (setcar (nthcdr num (eieio--class-public-custom newc)) cust))
934 ;; If a new label is specified, it simply replaces
935 ;; the old one.
936 (when label
937 ;; (message "Custom label redefined to %s" label)
938 (setcar (nthcdr num (eieio--class-public-custom-label newc)) label))
939 ;; End PLN
941 ;; PLN Sat Jun 30 17:24:42 2007 : when a new
942 ;; doc is specified, simply replaces the old one.
943 (when doc
944 ;;(message "Documentation redefined to %s" doc)
945 (setcar (nthcdr num (eieio--class-public-doc newc))
946 doc))
947 ;; End PLN
949 ;; If a new printer is specified, it simply replaces
950 ;; the old one.
951 (when print
952 ;; (message "printer redefined to %s" print)
953 (setcar (nthcdr num (eieio--class-public-printer newc)) print))
958 ;; CLASS ALLOCATED SLOTS
959 (let ((value (eieio-default-eval-maybe d)))
960 (if (not (member a (eieio--class-class-allocation-a newc)))
961 (progn
962 (eieio-perform-slot-validation-for-default a type value skipnil)
963 ;; Here we have found a :class version of a slot. This
964 ;; requires a very different approach.
965 (setf (eieio--class-class-allocation-a newc) (cons a (eieio--class-class-allocation-a newc)))
966 (setf (eieio--class-class-allocation-doc newc) (cons doc (eieio--class-class-allocation-doc newc)))
967 (setf (eieio--class-class-allocation-type newc) (cons type (eieio--class-class-allocation-type newc)))
968 (setf (eieio--class-class-allocation-custom newc) (cons cust (eieio--class-class-allocation-custom newc)))
969 (setf (eieio--class-class-allocation-custom-label newc) (cons label (eieio--class-class-allocation-custom-label newc)))
970 (setf (eieio--class-class-allocation-custom-group newc) (cons custg (eieio--class-class-allocation-custom-group newc)))
971 (setf (eieio--class-class-allocation-protection newc) (cons prot (eieio--class-class-allocation-protection newc)))
972 ;; Default value is stored in the 'values section, since new objects
973 ;; can't initialize from this element.
974 (setf (eieio--class-class-allocation-values newc) (cons value (eieio--class-class-allocation-values newc))))
975 (when defaultoverride
976 ;; There is a match, and we must override the old value.
977 (let* ((ca (eieio--class-class-allocation-a newc))
978 (np (member a ca))
979 (num (- (length ca) (length np)))
980 (dp (if np
981 (nthcdr num
982 (eieio--class-class-allocation-values newc))
983 nil))
984 (tp (if np (nth num (eieio--class-class-allocation-type newc))
985 nil)))
986 (if (not np)
987 (error "EIEIO internal error overriding default value for %s"
989 ;; If type is passed in, is it the same?
990 (if (not (eq type t))
991 (if (not (equal type tp))
992 (error
993 "Child slot type `%s' does not match inherited type `%s' for `%s'"
994 type tp a)))
995 ;; EML - Note: the only reason to override a class bound slot
996 ;; is to change the default, so allow unbound in.
998 ;; If we have a repeat, only update the value...
999 (eieio-perform-slot-validation-for-default a tp value skipnil)
1000 (setcar dp value))
1002 ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
1003 ;; checked and SHOULD match the superclass
1004 ;; protection. Otherwise an error is thrown. However
1005 ;; I wonder if a more flexible schedule might be
1006 ;; implemented.
1007 (let ((super-prot
1008 (car (nthcdr num (eieio--class-class-allocation-protection newc)))))
1009 (if (not (eq prot super-prot))
1010 (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
1011 prot super-prot a)))
1012 ;; Do a non redundant combination of ancient custom groups
1013 ;; and new ones.
1014 (when custg
1015 (let* ((groups
1016 (nthcdr num (eieio--class-class-allocation-custom-group newc)))
1017 (list1 (car groups))
1018 (list2 (if (listp custg) custg (list custg))))
1019 (if (< (length list1) (length list2))
1020 (setq list1 (prog1 list2 (setq list2 list1))))
1021 (dolist (elt list2)
1022 (unless (memq elt list1)
1023 (push elt list1)))
1024 (setcar groups list1)))
1026 ;; PLN Sat Jun 30 17:24:42 2007 : when a new
1027 ;; doc is specified, simply replaces the old one.
1028 (when doc
1029 ;;(message "Documentation redefined to %s" doc)
1030 (setcar (nthcdr num (eieio--class-class-allocation-doc newc))
1031 doc))
1032 ;; End PLN
1034 ;; If a new printer is specified, it simply replaces
1035 ;; the old one.
1036 (when print
1037 ;; (message "printer redefined to %s" print)
1038 (setcar (nthcdr num (eieio--class-class-allocation-printer newc)) print))
1044 (defun eieio-copy-parents-into-subclass (newc _parents)
1045 "Copy into NEWC the slots of PARENTS.
1046 Follow the rules of not overwriting early parents when applying to
1047 the new child class."
1048 (let ((ps (eieio--class-parent newc))
1049 (sn (class-option-assoc (eieio--class-options newc)
1050 ':allow-nil-initform)))
1051 (while ps
1052 ;; First, duplicate all the slots of the parent.
1053 (let ((pcv (class-v (car ps))))
1054 (let ((pa (eieio--class-public-a pcv))
1055 (pd (eieio--class-public-d pcv))
1056 (pdoc (eieio--class-public-doc pcv))
1057 (ptype (eieio--class-public-type pcv))
1058 (pcust (eieio--class-public-custom pcv))
1059 (plabel (eieio--class-public-custom-label pcv))
1060 (pcustg (eieio--class-public-custom-group pcv))
1061 (printer (eieio--class-public-printer pcv))
1062 (pprot (eieio--class-protection pcv))
1063 (pinit (eieio--class-initarg-tuples pcv))
1064 (i 0))
1065 (while pa
1066 (eieio-add-new-slot newc
1067 (car pa) (car pd) (car pdoc) (aref ptype i)
1068 (car pcust) (car plabel) (car pcustg)
1069 (car printer)
1070 (car pprot) (car-safe (car pinit)) nil nil sn)
1071 ;; Increment each value.
1072 (setq pa (cdr pa)
1073 pd (cdr pd)
1074 pdoc (cdr pdoc)
1075 i (1+ i)
1076 pcust (cdr pcust)
1077 plabel (cdr plabel)
1078 pcustg (cdr pcustg)
1079 printer (cdr printer)
1080 pprot (cdr pprot)
1081 pinit (cdr pinit))
1082 )) ;; while/let
1083 ;; Now duplicate all the class alloc slots.
1084 (let ((pa (eieio--class-class-allocation-a pcv))
1085 (pdoc (eieio--class-class-allocation-doc pcv))
1086 (ptype (eieio--class-class-allocation-type pcv))
1087 (pcust (eieio--class-class-allocation-custom pcv))
1088 (plabel (eieio--class-class-allocation-custom-label pcv))
1089 (pcustg (eieio--class-class-allocation-custom-group pcv))
1090 (printer (eieio--class-class-allocation-printer pcv))
1091 (pprot (eieio--class-class-allocation-protection pcv))
1092 (pval (eieio--class-class-allocation-values pcv))
1093 (i 0))
1094 (while pa
1095 (eieio-add-new-slot newc
1096 (car pa) (aref pval i) (car pdoc) (aref ptype i)
1097 (car pcust) (car plabel) (car pcustg)
1098 (car printer)
1099 (car pprot) nil ':class sn)
1100 ;; Increment each value.
1101 (setq pa (cdr pa)
1102 pdoc (cdr pdoc)
1103 pcust (cdr pcust)
1104 plabel (cdr plabel)
1105 pcustg (cdr pcustg)
1106 printer (cdr printer)
1107 pprot (cdr pprot)
1108 i (1+ i))
1109 ))) ;; while/let
1110 ;; Loop over each parent class
1111 (setq ps (cdr ps)))
1115 ;;; CLOS methods and generics
1118 (defun eieio--defgeneric-init-form (method doc-string)
1119 "Form to use for the initial definition of a generic."
1120 (cond
1121 ((or (not (fboundp method))
1122 (eq 'autoload (car-safe (symbol-function method))))
1123 ;; Make sure the method tables are installed.
1124 (eieiomt-install method)
1125 ;; Construct the actual body of this function.
1126 (eieio-defgeneric-form method doc-string))
1127 ((generic-p method) (symbol-function method)) ;Leave it as-is.
1128 (t (error "You cannot create a generic/method over an existing symbol: %s"
1129 method))))
1131 (defun eieio-defgeneric-form (method doc-string)
1132 "The lambda form that would be used as the function defined on METHOD.
1133 All methods should call the same EIEIO function for dispatch.
1134 DOC-STRING is the documentation attached to METHOD."
1135 `(lambda (&rest local-args)
1136 ,doc-string
1137 (eieio-generic-call (quote ,method) local-args)))
1139 (defsubst eieio-defgeneric-reset-generic-form (method)
1140 "Setup METHOD to call the generic form."
1141 (let ((doc-string (documentation method)))
1142 (fset method (eieio-defgeneric-form method doc-string))))
1144 (defun eieio-defgeneric-form-primary-only (method doc-string)
1145 "The lambda form that would be used as the function defined on METHOD.
1146 All methods should call the same EIEIO function for dispatch.
1147 DOC-STRING is the documentation attached to METHOD."
1148 `(lambda (&rest local-args)
1149 ,doc-string
1150 (eieio-generic-call-primary-only (quote ,method) local-args)))
1152 (defsubst eieio-defgeneric-reset-generic-form-primary-only (method)
1153 "Setup METHOD to call the generic form."
1154 (let ((doc-string (documentation method)))
1155 (fset method (eieio-defgeneric-form-primary-only method doc-string))))
1157 (declare-function no-applicable-method "eieio" (object method &rest args))
1159 (defun eieio-defgeneric-form-primary-only-one (method doc-string
1160 class
1161 impl
1163 "The lambda form that would be used as the function defined on METHOD.
1164 All methods should call the same EIEIO function for dispatch.
1165 DOC-STRING is the documentation attached to METHOD.
1166 CLASS is the class symbol needed for private method access.
1167 IMPL is the symbol holding the method implementation."
1168 ;; NOTE: I tried out byte compiling this little fcn. Turns out it
1169 ;; is faster to execute this for not byte-compiled. ie, install this,
1170 ;; then measure calls going through here. I wonder why.
1171 (require 'bytecomp)
1172 (let ((byte-compile-warnings nil))
1173 (byte-compile
1174 `(lambda (&rest local-args)
1175 ,doc-string
1176 ;; This is a cool cheat. Usually we need to look up in the
1177 ;; method table to find out if there is a method or not. We can
1178 ;; instead make that determination at load time when there is
1179 ;; only one method. If the first arg is not a child of the class
1180 ;; of that one implementation, then clearly, there is no method def.
1181 (if (not (eieio-object-p (car local-args)))
1182 ;; Not an object. Just signal.
1183 (signal 'no-method-definition
1184 (list ',method local-args))
1186 ;; We do have an object. Make sure it is the right type.
1187 (if ,(if (eq class eieio-default-superclass)
1188 nil ; default superclass means just an obj. Already asked.
1189 `(not (child-of-class-p (eieio--object-class (car local-args))
1190 ',class)))
1192 ;; If not the right kind of object, call no applicable
1193 (apply #'no-applicable-method (car local-args)
1194 ',method local-args)
1196 ;; It is ok, do the call.
1197 ;; Fill in inter-call variables then evaluate the method.
1198 (let ((eieio-generic-call-next-method-list nil)
1199 (eieio-generic-call-key method-primary)
1200 (eieio-generic-call-methodname ',method)
1201 (eieio-generic-call-arglst local-args)
1203 (eieio--with-scoped-class ',class
1204 ,(if (< emacs-major-version 24)
1205 `(apply ,(list 'quote impl) local-args)
1206 `(apply #',impl local-args)))
1207 ;(,impl local-args)
1208 )))))))
1210 (defsubst eieio-defgeneric-reset-generic-form-primary-only-one (method)
1211 "Setup METHOD to call the generic form."
1212 (let* ((doc-string (documentation method))
1213 (M (get method 'eieio-method-tree))
1214 (entry (car (aref M method-primary)))
1216 (fset method (eieio-defgeneric-form-primary-only-one
1217 method doc-string
1218 (car entry)
1219 (cdr entry)
1220 ))))
1222 (defun eieio-unbind-method-implementations (method)
1223 "Make the generic method METHOD have no implementations.
1224 It will leave the original generic function in place,
1225 but remove reference to all implementations of METHOD."
1226 (put method 'eieio-method-tree nil)
1227 (put method 'eieio-method-obarray nil))
1229 (defun eieio--defmethod (method kind argclass code)
1230 "Work part of the `defmethod' macro defining METHOD with ARGS."
1231 (let ((key
1232 ;; Find optional keys.
1233 (cond ((memq kind '(:BEFORE :before)) method-before)
1234 ((memq kind '(:AFTER :after)) method-after)
1235 ((memq kind '(:STATIC :static)) method-static)
1236 ((memq kind '(:PRIMARY :primary nil)) method-primary)
1237 ;; Primary key.
1238 ;; (t method-primary)
1239 (t (error "Unknown method kind %S" kind)))))
1240 ;; Make sure there is a generic (when called from defclass).
1241 (eieio--defalias
1242 method (eieio--defgeneric-init-form
1243 method (or (documentation code)
1244 (format "Generically created method `%s'." method))))
1245 ;; Create symbol for property to bind to. If the first arg is of
1246 ;; the form (varname vartype) and `vartype' is a class, then
1247 ;; that class will be the type symbol. If not, then it will fall
1248 ;; under the type `primary' which is a non-specific calling of the
1249 ;; function.
1250 (if argclass
1251 (if (not (class-p argclass))
1252 (error "Unknown class type %s in method parameters"
1253 argclass))
1254 ;; Generics are higher.
1255 (setq key (eieio-specialized-key-to-generic-key key)))
1256 ;; Put this lambda into the symbol so we can find it.
1257 (eieiomt-add method code key argclass)
1260 (when eieio-optimize-primary-methods-flag
1261 ;; Optimizing step:
1263 ;; If this method, after this setup, only has primary methods, then
1264 ;; we can setup the generic that way.
1265 (if (generic-primary-only-p method)
1266 ;; If there is only one primary method, then we can go one more
1267 ;; optimization step.
1268 (if (generic-primary-only-one-p method)
1269 (eieio-defgeneric-reset-generic-form-primary-only-one method)
1270 (eieio-defgeneric-reset-generic-form-primary-only method))
1271 (eieio-defgeneric-reset-generic-form method)))
1273 method)
1275 ;;; Slot type validation
1277 ;; This is a hideous hack for replacing `typep' from cl-macs, to avoid
1278 ;; requiring the CL library at run-time. It can be eliminated if/when
1279 ;; `typep' is merged into Emacs core.
1281 (defun eieio-perform-slot-validation (spec value)
1282 "Return non-nil if SPEC does not match VALUE."
1283 (or (eq spec t) ; t always passes
1284 (eq value eieio-unbound) ; unbound always passes
1285 (cl-typep value spec)))
1287 (defun eieio-validate-slot-value (class slot-idx value slot)
1288 "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
1289 Checks the :type specifier.
1290 SLOT is the slot that is being checked, and is only used when throwing
1291 an error."
1292 (if eieio-skip-typecheck
1294 ;; Trim off object IDX junk added in for the object index.
1295 (setq slot-idx (- slot-idx 3))
1296 (let ((st (aref (eieio--class-public-type (class-v class)) slot-idx)))
1297 (if (not (eieio-perform-slot-validation st value))
1298 (signal 'invalid-slot-type (list class slot st value))))))
1300 (defun eieio-validate-class-slot-value (class slot-idx value slot)
1301 "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
1302 Checks the :type specifier.
1303 SLOT is the slot that is being checked, and is only used when throwing
1304 an error."
1305 (if eieio-skip-typecheck
1307 (let ((st (aref (eieio--class-class-allocation-type (class-v class))
1308 slot-idx)))
1309 (if (not (eieio-perform-slot-validation st value))
1310 (signal 'invalid-slot-type (list class slot st value))))))
1312 (defun eieio-barf-if-slot-unbound (value instance slotname fn)
1313 "Throw a signal if VALUE is a representation of an UNBOUND slot.
1314 INSTANCE is the object being referenced. SLOTNAME is the offending
1315 slot. If the slot is ok, return VALUE.
1316 Argument FN is the function calling this verifier."
1317 (if (and (eq value eieio-unbound) (not eieio-skip-typecheck))
1318 (slot-unbound instance (eieio--object-class instance) slotname fn)
1319 value))
1322 ;;; Get/Set slots in an object.
1324 (defun eieio-oref (obj slot)
1325 "Return the value in OBJ at SLOT in the object vector."
1326 (eieio--check-type (or eieio-object-p class-p) obj)
1327 (eieio--check-type symbolp slot)
1328 (if (class-p obj) (eieio-class-un-autoload obj))
1329 (let* ((class (if (class-p obj) obj (eieio--object-class obj)))
1330 (c (eieio-slot-name-index class obj slot)))
1331 (if (not c)
1332 ;; It might be missing because it is a :class allocated slot.
1333 ;; Let's check that info out.
1334 (if (setq c (eieio-class-slot-name-index class slot))
1335 ;; Oref that slot.
1336 (aref (eieio--class-class-allocation-values (class-v class)) c)
1337 ;; The slot-missing method is a cool way of allowing an object author
1338 ;; to intercept missing slot definitions. Since it is also the LAST
1339 ;; thing called in this fn, its return value would be retrieved.
1340 (slot-missing obj slot 'oref)
1341 ;;(signal 'invalid-slot-name (list (eieio-object-name obj) slot))
1343 (eieio--check-type eieio-object-p obj)
1344 (eieio-barf-if-slot-unbound (aref obj c) obj slot 'oref))))
1347 (defun eieio-oref-default (obj slot)
1348 "Do the work for the macro `oref-default' with similar parameters.
1349 Fills in OBJ's SLOT with its default value."
1350 (eieio--check-type (or eieio-object-p class-p) obj)
1351 (eieio--check-type symbolp slot)
1352 (let* ((cl (if (eieio-object-p obj) (eieio--object-class obj) obj))
1353 (c (eieio-slot-name-index cl obj slot)))
1354 (if (not c)
1355 ;; It might be missing because it is a :class allocated slot.
1356 ;; Let's check that info out.
1357 (if (setq c
1358 (eieio-class-slot-name-index cl slot))
1359 ;; Oref that slot.
1360 (aref (eieio--class-class-allocation-values (class-v cl))
1362 (slot-missing obj slot 'oref-default)
1363 ;;(signal 'invalid-slot-name (list (class-name cl) slot))
1365 (eieio-barf-if-slot-unbound
1366 (let ((val (nth (- c 3) (eieio--class-public-d (class-v cl)))))
1367 (eieio-default-eval-maybe val))
1368 obj cl 'oref-default))))
1370 (defun eieio-default-eval-maybe (val)
1371 "Check VAL, and return what `oref-default' would provide."
1372 (cond
1373 ;; Is it a function call? If so, evaluate it.
1374 ((eieio-eval-default-p val)
1375 (eval val))
1376 ;;;; check for quoted things, and unquote them
1377 ;;((and (consp val) (eq (car val) 'quote))
1378 ;; (car (cdr val)))
1379 ;; return it verbatim
1380 (t val)))
1382 (defun eieio-oset (obj slot value)
1383 "Do the work for the macro `oset'.
1384 Fills in OBJ's SLOT with VALUE."
1385 (eieio--check-type eieio-object-p obj)
1386 (eieio--check-type symbolp slot)
1387 (let ((c (eieio-slot-name-index (eieio--object-class obj) obj slot)))
1388 (if (not c)
1389 ;; It might be missing because it is a :class allocated slot.
1390 ;; Let's check that info out.
1391 (if (setq c
1392 (eieio-class-slot-name-index (eieio--object-class obj) slot))
1393 ;; Oset that slot.
1394 (progn
1395 (eieio-validate-class-slot-value (eieio--object-class obj) c value slot)
1396 (aset (eieio--class-class-allocation-values (class-v (eieio--object-class obj)))
1397 c value))
1398 ;; See oref for comment on `slot-missing'
1399 (slot-missing obj slot 'oset value)
1400 ;;(signal 'invalid-slot-name (list (eieio-object-name obj) slot))
1402 (eieio-validate-slot-value (eieio--object-class obj) c value slot)
1403 (aset obj c value))))
1405 (defun eieio-oset-default (class slot value)
1406 "Do the work for the macro `oset-default'.
1407 Fills in the default value in CLASS' in SLOT with VALUE."
1408 (eieio--check-type class-p class)
1409 (eieio--check-type symbolp slot)
1410 (eieio--with-scoped-class class
1411 (let* ((c (eieio-slot-name-index class nil slot)))
1412 (if (not c)
1413 ;; It might be missing because it is a :class allocated slot.
1414 ;; Let's check that info out.
1415 (if (setq c (eieio-class-slot-name-index class slot))
1416 (progn
1417 ;; Oref that slot.
1418 (eieio-validate-class-slot-value class c value slot)
1419 (aset (eieio--class-class-allocation-values (class-v class)) c
1420 value))
1421 (signal 'invalid-slot-name (list (eieio-class-name class) slot)))
1422 (eieio-validate-slot-value class c value slot)
1423 ;; Set this into the storage for defaults.
1424 (setcar (nthcdr (- c 3) (eieio--class-public-d (class-v class)))
1425 value)
1426 ;; Take the value, and put it into our cache object.
1427 (eieio-oset (eieio--class-default-object-cache (class-v class))
1428 slot value)
1429 ))))
1432 ;;; EIEIO internal search functions
1434 (defun eieio-slot-originating-class-p (start-class slot)
1435 "Return non-nil if START-CLASS is the first class to define SLOT.
1436 This is for testing if the class currently in scope is the class that defines SLOT
1437 so that we can protect private slots."
1438 (let ((par (eieio-class-parents-fast start-class))
1439 (ret t))
1440 (if (not par)
1442 (while (and par ret)
1443 (if (intern-soft (symbol-name slot)
1444 (eieio--class-symbol-obarray (class-v (car par))))
1445 (setq ret nil))
1446 (setq par (cdr par)))
1447 ret)))
1449 (defun eieio-slot-name-index (class obj slot)
1450 "In CLASS for OBJ find the index of the named SLOT.
1451 The slot is a symbol which is installed in CLASS by the `defclass'
1452 call. OBJ can be nil, but if it is an object, and the slot in question
1453 is protected, access will be allowed if OBJ is a child of the currently
1454 scoped class.
1455 If SLOT is the value created with :initarg instead,
1456 reverse-lookup that name, and recurse with the associated slot value."
1457 ;; Removed checks to outside this call
1458 (let* ((fsym (intern-soft (symbol-name slot)
1459 (eieio--class-symbol-obarray (class-v class))))
1460 (fsi (if (symbolp fsym) (symbol-value fsym) nil)))
1461 (if (integerp fsi)
1462 (cond
1463 ((not (get fsym 'protection))
1464 (+ 3 fsi))
1465 ((and (eq (get fsym 'protection) 'protected)
1466 (eieio--scoped-class)
1467 (or (child-of-class-p class (eieio--scoped-class))
1468 (and (eieio-object-p obj)
1469 (child-of-class-p class (eieio--object-class obj)))))
1470 (+ 3 fsi))
1471 ((and (eq (get fsym 'protection) 'private)
1472 (or (and (eieio--scoped-class)
1473 (eieio-slot-originating-class-p (eieio--scoped-class) slot))
1474 eieio-initializing-object))
1475 (+ 3 fsi))
1476 (t nil))
1477 (let ((fn (eieio-initarg-to-attribute class slot)))
1478 (if fn (eieio-slot-name-index class obj fn) nil)))))
1480 (defun eieio-class-slot-name-index (class slot)
1481 "In CLASS find the index of the named SLOT.
1482 The slot is a symbol which is installed in CLASS by the `defclass'
1483 call. If SLOT is the value created with :initarg instead,
1484 reverse-lookup that name, and recurse with the associated slot value."
1485 ;; This will happen less often, and with fewer slots. Do this the
1486 ;; storage cheap way.
1487 (let* ((a (eieio--class-class-allocation-a (class-v class)))
1488 (l1 (length a))
1489 (af (memq slot a))
1490 (l2 (length af)))
1491 ;; Slot # is length of the total list, minus the remaining list of
1492 ;; the found slot.
1493 (if af (- l1 l2))))
1496 ;; Way to assign slots based on a list. Used for constructors, or
1497 ;; even resetting an object at run-time
1499 (defun eieio-set-defaults (obj &optional set-all)
1500 "Take object OBJ, and reset all slots to their defaults.
1501 If SET-ALL is non-nil, then when a default is nil, that value is
1502 reset. If SET-ALL is nil, the slots are only reset if the default is
1503 not nil."
1504 (eieio--with-scoped-class (eieio--object-class obj)
1505 (let ((eieio-initializing-object t)
1506 (pub (eieio--class-public-a (class-v (eieio--object-class obj)))))
1507 (while pub
1508 (let ((df (eieio-oref-default obj (car pub))))
1509 (if (or df set-all)
1510 (eieio-oset obj (car pub) df)))
1511 (setq pub (cdr pub))))))
1513 (defun eieio-initarg-to-attribute (class initarg)
1514 "For CLASS, convert INITARG to the actual attribute name.
1515 If there is no translation, pass it in directly (so we can cheat if
1516 need be... May remove that later...)"
1517 (let ((tuple (assoc initarg (eieio--class-initarg-tuples (class-v class)))))
1518 (if tuple
1519 (cdr tuple)
1520 nil)))
1522 (defun eieio-attribute-to-initarg (class attribute)
1523 "In CLASS, convert the ATTRIBUTE into the corresponding init argument tag.
1524 This is usually a symbol that starts with `:'."
1525 (let ((tuple (rassoc attribute (eieio--class-initarg-tuples (class-v class)))))
1526 (if tuple
1527 (car tuple)
1528 nil)))
1531 ;; Method Invocation order: C3
1532 (defun eieio-c3-candidate (class remaining-inputs)
1533 "Return CLASS if it can go in the result now, otherwise nil"
1534 ;; Ensure CLASS is not in any position but the first in any of the
1535 ;; element lists of REMAINING-INPUTS.
1536 (and (not (let ((found nil))
1537 (while (and remaining-inputs (not found))
1538 (setq found (member class (cdr (car remaining-inputs)))
1539 remaining-inputs (cdr remaining-inputs)))
1540 found))
1541 class))
1543 (defun eieio-c3-merge-lists (reversed-partial-result remaining-inputs)
1544 "Merge REVERSED-PARTIAL-RESULT REMAINING-INPUTS in a consistent order, if possible.
1545 If a consistent order does not exist, signal an error."
1546 (if (let ((tail remaining-inputs)
1547 (found nil))
1548 (while (and tail (not found))
1549 (setq found (car tail) tail (cdr tail)))
1550 (not found))
1551 ;; If all remaining inputs are empty lists, we are done.
1552 (nreverse reversed-partial-result)
1553 ;; Otherwise, we try to find the next element of the result. This
1554 ;; is achieved by considering the first element of each
1555 ;; (non-empty) input list and accepting a candidate if it is
1556 ;; consistent with the rests of the input lists.
1557 (let* ((found nil)
1558 (tail remaining-inputs)
1559 (next (progn
1560 (while (and tail (not found))
1561 (setq found (and (car tail)
1562 (eieio-c3-candidate (caar tail)
1563 remaining-inputs))
1564 tail (cdr tail)))
1565 found)))
1566 (if next
1567 ;; The graph is consistent so far, add NEXT to result and
1568 ;; merge input lists, dropping NEXT from their heads where
1569 ;; applicable.
1570 (eieio-c3-merge-lists
1571 (cons next reversed-partial-result)
1572 (mapcar (lambda (l) (if (eq (cl-first l) next) (cl-rest l) l))
1573 remaining-inputs))
1574 ;; The graph is inconsistent, give up
1575 (signal 'inconsistent-class-hierarchy (list remaining-inputs))))))
1577 (defun eieio-class-precedence-c3 (class)
1578 "Return all parents of CLASS in c3 order."
1579 (let ((parents (eieio-class-parents-fast class)))
1580 (eieio-c3-merge-lists
1581 (list class)
1582 (append
1584 (mapcar
1585 (lambda (x)
1586 (eieio-class-precedence-c3 x))
1587 parents)
1588 '((eieio-default-superclass)))
1589 (list parents))))
1592 ;; Method Invocation Order: Depth First
1594 (defun eieio-class-precedence-dfs (class)
1595 "Return all parents of CLASS in depth-first order."
1596 (let* ((parents (eieio-class-parents-fast class))
1597 (classes (copy-sequence
1598 (apply #'append
1599 (list class)
1601 (mapcar
1602 (lambda (parent)
1603 (cons parent
1604 (eieio-class-precedence-dfs parent)))
1605 parents)
1606 '((eieio-default-superclass))))))
1607 (tail classes))
1608 ;; Remove duplicates.
1609 (while tail
1610 (setcdr tail (delq (car tail) (cdr tail)))
1611 (setq tail (cdr tail)))
1612 classes))
1615 ;; Method Invocation Order: Breadth First
1616 (defun eieio-class-precedence-bfs (class)
1617 "Return all parents of CLASS in breadth-first order."
1618 (let ((result)
1619 (queue (or (eieio-class-parents-fast class)
1620 '(eieio-default-superclass))))
1621 (while queue
1622 (let ((head (pop queue)))
1623 (unless (member head result)
1624 (push head result)
1625 (unless (eq head 'eieio-default-superclass)
1626 (setq queue (append queue (or (eieio-class-parents-fast head)
1627 '(eieio-default-superclass))))))))
1628 (cons class (nreverse result)))
1632 ;; Method Invocation Order
1634 (defun eieio-class-precedence-list (class)
1635 "Return (transitively closed) list of parents of CLASS.
1636 The order, in which the parents are returned depends on the
1637 method invocation orders of the involved classes."
1638 (if (or (null class) (eq class 'eieio-default-superclass))
1640 (cl-case (class-method-invocation-order class)
1641 (:depth-first
1642 (eieio-class-precedence-dfs class))
1643 (:breadth-first
1644 (eieio-class-precedence-bfs class))
1645 (:c3
1646 (eieio-class-precedence-c3 class))))
1648 (define-obsolete-function-alias
1649 'class-precedence-list 'eieio-class-precedence-list "24.4")
1652 ;;; CLOS generics internal function handling
1654 (defvar eieio-generic-call-methodname nil
1655 "When using `call-next-method', provides a context on how to do it.")
1656 (defvar eieio-generic-call-arglst nil
1657 "When using `call-next-method', provides a context for parameters.")
1658 (defvar eieio-generic-call-key nil
1659 "When using `call-next-method', provides a context for the current key.
1660 Keys are a number representing :before, :primary, and :after methods.")
1661 (defvar eieio-generic-call-next-method-list nil
1662 "When executing a PRIMARY or STATIC method, track the 'next-method'.
1663 During executions, the list is first generated, then as each next method
1664 is called, the next method is popped off the stack.")
1666 (define-obsolete-variable-alias 'eieio-pre-method-execution-hooks
1667 'eieio-pre-method-execution-functions "24.3")
1668 (defvar eieio-pre-method-execution-functions nil
1669 "Abnormal hook run just before an EIEIO method is executed.
1670 The hook function must accept one argument, the list of forms
1671 about to be executed.")
1673 (defun eieio-generic-call (method args)
1674 "Call METHOD with ARGS.
1675 ARGS provides the context on which implementation to use.
1676 This should only be called from a generic function."
1677 ;; We must expand our arguments first as they are always
1678 ;; passed in as quoted symbols
1679 (let ((newargs nil) (mclass nil) (lambdas nil) (tlambdas nil) (keys nil)
1680 (eieio-generic-call-methodname method)
1681 (eieio-generic-call-arglst args)
1682 (firstarg nil)
1683 (primarymethodlist nil))
1684 ;; get a copy
1685 (setq newargs args
1686 firstarg (car newargs))
1687 ;; Is the class passed in autoloaded?
1688 ;; Since class names are also constructors, they can be autoloaded
1689 ;; via the autoload command. Check for this, and load them in.
1690 ;; It is ok if it doesn't turn out to be a class. Probably want that
1691 ;; function loaded anyway.
1692 (if (and (symbolp firstarg)
1693 (fboundp firstarg)
1694 (listp (symbol-function firstarg))
1695 (eq 'autoload (car (symbol-function firstarg))))
1696 (load (nth 1 (symbol-function firstarg))))
1697 ;; Determine the class to use.
1698 (cond ((eieio-object-p firstarg)
1699 (setq mclass (eieio--object-class firstarg)))
1700 ((class-p firstarg)
1701 (setq mclass firstarg))
1703 ;; Make sure the class is a valid class
1704 ;; mclass can be nil (meaning a generic for should be used.
1705 ;; mclass cannot have a value that is not a class, however.
1706 (when (and (not (null mclass)) (not (class-p mclass)))
1707 (error "Cannot dispatch method %S on class %S"
1708 method mclass)
1710 ;; Now create a list in reverse order of all the calls we have
1711 ;; make in order to successfully do this right. Rules:
1712 ;; 1) Only call generics if scoped-class is not defined
1713 ;; This prevents multiple calls in the case of recursion
1714 ;; 2) Only call static if this is a static method.
1715 ;; 3) Only call specifics if the definition allows for them.
1716 ;; 4) Call in order based on :before, :primary, and :after
1717 (when (eieio-object-p firstarg)
1718 ;; Non-static calls do all this stuff.
1720 ;; :after methods
1721 (setq tlambdas
1722 (if mclass
1723 (eieiomt-method-list method method-after mclass)
1724 (list (eieio-generic-form method method-after nil)))
1725 ;;(or (and mclass (eieio-generic-form method method-after mclass))
1726 ;; (eieio-generic-form method method-after nil))
1728 (setq lambdas (append tlambdas lambdas)
1729 keys (append (make-list (length tlambdas) method-after) keys))
1731 ;; :primary methods
1732 (setq tlambdas
1733 (or (and mclass (eieio-generic-form method method-primary mclass))
1734 (eieio-generic-form method method-primary nil)))
1735 (when tlambdas
1736 (setq lambdas (cons tlambdas lambdas)
1737 keys (cons method-primary keys)
1738 primarymethodlist
1739 (eieiomt-method-list method method-primary mclass)))
1741 ;; :before methods
1742 (setq tlambdas
1743 (if mclass
1744 (eieiomt-method-list method method-before mclass)
1745 (list (eieio-generic-form method method-before nil)))
1746 ;;(or (and mclass (eieio-generic-form method method-before mclass))
1747 ;; (eieio-generic-form method method-before nil))
1749 (setq lambdas (append tlambdas lambdas)
1750 keys (append (make-list (length tlambdas) method-before) keys))
1753 (if mclass
1754 ;; For the case of a class,
1755 ;; if there were no methods found, then there could be :static methods.
1756 (when (not lambdas)
1757 (setq tlambdas
1758 (eieio-generic-form method method-static mclass))
1759 (setq lambdas (cons tlambdas lambdas)
1760 keys (cons method-static keys)
1761 primarymethodlist ;; Re-use even with bad name here
1762 (eieiomt-method-list method method-static mclass)))
1763 ;; For the case of no class (ie - mclass == nil) then there may
1764 ;; be a primary method.
1765 (setq tlambdas
1766 (eieio-generic-form method method-primary nil))
1767 (when tlambdas
1768 (setq lambdas (cons tlambdas lambdas)
1769 keys (cons method-primary keys)
1770 primarymethodlist
1771 (eieiomt-method-list method method-primary nil)))
1774 (run-hook-with-args 'eieio-pre-method-execution-functions
1775 primarymethodlist)
1777 ;; Now loop through all occurrences forms which we must execute
1778 ;; (which are happily sorted now) and execute them all!
1779 (let ((rval nil) (lastval nil) (found nil))
1780 (while lambdas
1781 (if (car lambdas)
1782 (eieio--with-scoped-class (cdr (car lambdas))
1783 (let* ((eieio-generic-call-key (car keys))
1784 (has-return-val
1785 (or (= eieio-generic-call-key method-primary)
1786 (= eieio-generic-call-key method-static)))
1787 (eieio-generic-call-next-method-list
1788 ;; Use the cdr, as the first element is the fcn
1789 ;; we are calling right now.
1790 (when has-return-val (cdr primarymethodlist)))
1792 (setq found t)
1793 ;;(setq rval (apply (car (car lambdas)) newargs))
1794 (setq lastval (apply (car (car lambdas)) newargs))
1795 (when has-return-val
1796 (setq rval lastval))
1798 (setq lambdas (cdr lambdas)
1799 keys (cdr keys)))
1800 (if (not found)
1801 (if (eieio-object-p (car args))
1802 (setq rval (apply #'no-applicable-method (car args) method args))
1803 (signal
1804 'no-method-definition
1805 (list method args))))
1806 rval)))
1808 (defun eieio-generic-call-primary-only (method args)
1809 "Call METHOD with ARGS for methods with only :PRIMARY implementations.
1810 ARGS provides the context on which implementation to use.
1811 This should only be called from a generic function.
1813 This method is like `eieio-generic-call', but only
1814 implementations in the :PRIMARY slot are queried. After many
1815 years of use, it appears that over 90% of methods in use
1816 have :PRIMARY implementations only. We can therefore optimize
1817 for this common case to improve performance."
1818 ;; We must expand our arguments first as they are always
1819 ;; passed in as quoted symbols
1820 (let ((newargs nil) (mclass nil) (lambdas nil)
1821 (eieio-generic-call-methodname method)
1822 (eieio-generic-call-arglst args)
1823 (firstarg nil)
1824 (primarymethodlist nil)
1826 ;; get a copy
1827 (setq newargs args
1828 firstarg (car newargs))
1830 ;; Determine the class to use.
1831 (cond ((eieio-object-p firstarg)
1832 (setq mclass (eieio--object-class firstarg)))
1833 ((not firstarg)
1834 (error "Method %s called on nil" method))
1835 ((not (eieio-object-p firstarg))
1836 (error "Primary-only method %s called on something not an object" method))
1838 (error "EIEIO Error: Improperly classified method %s as primary only"
1839 method)
1841 ;; Make sure the class is a valid class
1842 ;; mclass can be nil (meaning a generic for should be used.
1843 ;; mclass cannot have a value that is not a class, however.
1844 (when (null mclass)
1845 (error "Cannot dispatch method %S on class %S" method mclass)
1848 ;; :primary methods
1849 (setq lambdas (eieio-generic-form method method-primary mclass))
1850 (setq primarymethodlist ;; Re-use even with bad name here
1851 (eieiomt-method-list method method-primary mclass))
1853 ;; Now loop through all occurrences forms which we must execute
1854 ;; (which are happily sorted now) and execute them all!
1855 (eieio--with-scoped-class (cdr lambdas)
1856 (let* ((rval nil) (lastval nil)
1857 (eieio-generic-call-key method-primary)
1858 ;; Use the cdr, as the first element is the fcn
1859 ;; we are calling right now.
1860 (eieio-generic-call-next-method-list (cdr primarymethodlist))
1863 (if (or (not lambdas) (not (car lambdas)))
1865 ;; No methods found for this impl...
1866 (if (eieio-object-p (car args))
1867 (setq rval (apply #'no-applicable-method
1868 (car args) method args))
1869 (signal
1870 'no-method-definition
1871 (list method args)))
1873 ;; Do the regular implementation here.
1875 (run-hook-with-args 'eieio-pre-method-execution-functions
1876 lambdas)
1878 (setq lastval (apply (car lambdas) newargs))
1879 (setq rval lastval))
1881 rval))))
1883 (defun eieiomt-method-list (method key class)
1884 "Return an alist list of methods lambdas.
1885 METHOD is the method name.
1886 KEY represents either :before, or :after methods.
1887 CLASS is the starting class to search from in the method tree.
1888 If CLASS is nil, then an empty list of methods should be returned."
1889 ;; Note: eieiomt - the MT means MethodTree. See more comments below
1890 ;; for the rest of the eieiomt methods.
1892 ;; Collect lambda expressions stored for the class and its parent
1893 ;; classes.
1894 (let (lambdas)
1895 (dolist (ancestor (eieio-class-precedence-list class))
1896 ;; Lookup the form to use for the PRIMARY object for the next level
1897 (let ((tmpl (eieio-generic-form method key ancestor)))
1898 (when (and tmpl
1899 (or (not lambdas)
1900 ;; This prevents duplicates coming out of the
1901 ;; class method optimizer. Perhaps we should
1902 ;; just not optimize before/afters?
1903 (not (member tmpl lambdas))))
1904 (push tmpl lambdas))))
1906 ;; Return collected lambda. For :after methods, return in current
1907 ;; order (most general class last); Otherwise, reverse order.
1908 (if (eq key method-after)
1909 lambdas
1910 (nreverse lambdas))))
1914 ;; eieio-method-tree : eieiomt-
1916 ;; Stored as eieio-method-tree in property list of a generic method
1918 ;; (eieio-method-tree . [BEFORE PRIMARY AFTER
1919 ;; genericBEFORE genericPRIMARY genericAFTER])
1920 ;; and
1921 ;; (eieio-method-obarray . [BEFORE PRIMARY AFTER
1922 ;; genericBEFORE genericPRIMARY genericAFTER])
1923 ;; where the association is a vector.
1924 ;; (aref 0 -- all static methods.
1925 ;; (aref 1 -- all methods classified as :before
1926 ;; (aref 2 -- all methods classified as :primary
1927 ;; (aref 3 -- all methods classified as :after
1928 ;; (aref 4 -- a generic classified as :before
1929 ;; (aref 5 -- a generic classified as :primary
1930 ;; (aref 6 -- a generic classified as :after
1932 (defvar eieiomt-optimizing-obarray nil
1933 "While mapping atoms, this contain the obarray being optimized.")
1935 (defun eieiomt-install (method-name)
1936 "Install the method tree, and obarray onto METHOD-NAME.
1937 Do not do the work if they already exist."
1938 (let ((emtv (get method-name 'eieio-method-tree))
1939 (emto (get method-name 'eieio-method-obarray)))
1940 (if (or (not emtv) (not emto))
1941 (progn
1942 (setq emtv (put method-name 'eieio-method-tree
1943 (make-vector method-num-slots nil))
1944 emto (put method-name 'eieio-method-obarray
1945 (make-vector method-num-slots nil)))
1946 (aset emto 0 (make-vector 11 0))
1947 (aset emto 1 (make-vector 11 0))
1948 (aset emto 2 (make-vector 41 0))
1949 (aset emto 3 (make-vector 11 0))
1950 ))))
1952 (defun eieiomt-add (method-name method key class)
1953 "Add to METHOD-NAME the forms METHOD in a call position KEY for CLASS.
1954 METHOD-NAME is the name created by a call to `defgeneric'.
1955 METHOD are the forms for a given implementation.
1956 KEY is an integer (see comment in eieio.el near this function) which
1957 is associated with the :static :before :primary and :after tags.
1958 It also indicates if CLASS is defined or not.
1959 CLASS is the class this method is associated with."
1960 (if (or (> key method-num-slots) (< key 0))
1961 (error "eieiomt-add: method key error!"))
1962 (let ((emtv (get method-name 'eieio-method-tree))
1963 (emto (get method-name 'eieio-method-obarray)))
1964 ;; Make sure the method tables are available.
1965 (if (or (not emtv) (not emto))
1966 (error "Programmer error: eieiomt-add"))
1967 ;; only add new cells on if it doesn't already exist!
1968 (if (assq class (aref emtv key))
1969 (setcdr (assq class (aref emtv key)) method)
1970 (aset emtv key (cons (cons class method) (aref emtv key))))
1971 ;; Add function definition into newly created symbol, and store
1972 ;; said symbol in the correct obarray, otherwise use the
1973 ;; other array to keep this stuff
1974 (if (< key method-num-lists)
1975 (let ((nsym (intern (symbol-name class) (aref emto key))))
1976 (fset nsym method)))
1977 ;; Save the defmethod file location in a symbol property.
1978 (let ((fname (if load-in-progress
1979 load-file-name
1980 buffer-file-name))
1981 loc)
1982 (when fname
1983 (when (string-match "\\.elc$" fname)
1984 (setq fname (substring fname 0 (1- (length fname)))))
1985 (setq loc (get method-name 'method-locations))
1986 (cl-pushnew (list class fname) loc :test 'equal)
1987 (put method-name 'method-locations loc)))
1988 ;; Now optimize the entire obarray
1989 (if (< key method-num-lists)
1990 (let ((eieiomt-optimizing-obarray (aref emto key)))
1991 ;; @todo - Is this overkill? Should we just clear the symbol?
1992 (mapatoms 'eieiomt-sym-optimize eieiomt-optimizing-obarray)))
1995 (defun eieiomt-next (class)
1996 "Return the next parent class for CLASS.
1997 If CLASS is a superclass, return variable `eieio-default-superclass'.
1998 If CLASS is variable `eieio-default-superclass' then return nil.
1999 This is different from function `class-parent' as class parent returns
2000 nil for superclasses. This function performs no type checking!"
2001 ;; No type-checking because all calls are made from functions which
2002 ;; are safe and do checking for us.
2003 (or (eieio-class-parents-fast class)
2004 (if (eq class 'eieio-default-superclass)
2006 '(eieio-default-superclass))))
2008 (defun eieiomt-sym-optimize (s)
2009 "Find the next class above S which has a function body for the optimizer."
2010 ;; Set the value to nil in case there is no nearest cell.
2011 (set s nil)
2012 ;; Find the nearest cell that has a function body. If we find one,
2013 ;; we replace the nil from above.
2014 (let ((external-symbol (intern-soft (symbol-name s))))
2015 (catch 'done
2016 (dolist (ancestor
2017 (cl-rest (eieio-class-precedence-list external-symbol)))
2018 (let ((ov (intern-soft (symbol-name ancestor)
2019 eieiomt-optimizing-obarray)))
2020 (when (fboundp ov)
2021 (set s ov) ;; store ov as our next symbol
2022 (throw 'done ancestor)))))))
2024 (defun eieio-generic-form (method key class)
2025 "Return the lambda form belonging to METHOD using KEY based upon CLASS.
2026 If CLASS is not a class then use `generic' instead. If class has
2027 no form, but has a parent class, then trace to that parent class.
2028 The first time a form is requested from a symbol, an optimized path
2029 is memorized for faster future use."
2030 (let ((emto (aref (get method 'eieio-method-obarray)
2031 (if class key (eieio-specialized-key-to-generic-key key)))))
2032 (if (class-p class)
2033 ;; 1) find our symbol
2034 (let ((cs (intern-soft (symbol-name class) emto)))
2035 (if (not cs)
2036 ;; 2) If there isn't one, then make one.
2037 ;; This can be slow since it only occurs once
2038 (progn
2039 (setq cs (intern (symbol-name class) emto))
2040 ;; 2.1) Cache its nearest neighbor with a quick optimize
2041 ;; which should only occur once for this call ever
2042 (let ((eieiomt-optimizing-obarray emto))
2043 (eieiomt-sym-optimize cs))))
2044 ;; 3) If it's bound return this one.
2045 (if (fboundp cs)
2046 (cons cs (eieio--class-symbol (class-v class)))
2047 ;; 4) If it's not bound then this variable knows something
2048 (if (symbol-value cs)
2049 (progn
2050 ;; 4.1) This symbol holds the next class in its value
2051 (setq class (symbol-value cs)
2052 cs (intern-soft (symbol-name class) emto))
2053 ;; 4.2) The optimizer should always have chosen a
2054 ;; function-symbol
2055 ;;(if (fboundp cs)
2056 (cons cs (eieio--class-symbol (class-v (intern (symbol-name class)))))
2057 ;;(error "EIEIO optimizer: erratic data loss!"))
2059 ;; There never will be a funcall...
2060 nil)))
2061 ;; for a generic call, what is a list, is the function body we want.
2062 (let ((emtl (aref (get method 'eieio-method-tree)
2063 (if class key (eieio-specialized-key-to-generic-key key)))))
2064 (if emtl
2065 ;; The car of EMTL is supposed to be a class, which in this
2066 ;; case is nil, so skip it.
2067 (cons (cdr (car emtl)) nil)
2068 nil)))))
2071 ;;; Here are some special types of errors
2073 (define-error 'no-method-definition "No method definition")
2074 (define-error 'no-next-method "No next method")
2075 (define-error 'invalid-slot-name "Invalid slot name")
2076 (define-error 'invalid-slot-type "Invalid slot type")
2077 (define-error 'unbound-slot "Unbound slot")
2078 (define-error 'inconsistent-class-hierarchy "Inconsistent class hierarchy")
2080 ;;; Obsolete backward compatibility functions.
2081 ;; Needed to run byte-code compiled with the EIEIO of Emacs-23.
2083 (defun eieio-defmethod (method args)
2084 "Obsolete work part of an old version of the `defmethod' macro."
2085 (let ((key nil) (body nil) (firstarg nil) (argfix nil) (argclass nil) loopa)
2086 ;; find optional keys
2087 (setq key
2088 (cond ((memq (car args) '(:BEFORE :before))
2089 (setq args (cdr args))
2090 method-before)
2091 ((memq (car args) '(:AFTER :after))
2092 (setq args (cdr args))
2093 method-after)
2094 ((memq (car args) '(:STATIC :static))
2095 (setq args (cdr args))
2096 method-static)
2097 ((memq (car args) '(:PRIMARY :primary))
2098 (setq args (cdr args))
2099 method-primary)
2100 ;; Primary key.
2101 (t method-primary)))
2102 ;; Get body, and fix contents of args to be the arguments of the fn.
2103 (setq body (cdr args)
2104 args (car args))
2105 (setq loopa args)
2106 ;; Create a fixed version of the arguments.
2107 (while loopa
2108 (setq argfix (cons (if (listp (car loopa)) (car (car loopa)) (car loopa))
2109 argfix))
2110 (setq loopa (cdr loopa)))
2111 ;; Make sure there is a generic.
2112 (eieio-defgeneric
2113 method
2114 (if (stringp (car body))
2115 (car body) (format "Generically created method `%s'." method)))
2116 ;; create symbol for property to bind to. If the first arg is of
2117 ;; the form (varname vartype) and `vartype' is a class, then
2118 ;; that class will be the type symbol. If not, then it will fall
2119 ;; under the type `primary' which is a non-specific calling of the
2120 ;; function.
2121 (setq firstarg (car args))
2122 (if (listp firstarg)
2123 (progn
2124 (setq argclass (nth 1 firstarg))
2125 (if (not (class-p argclass))
2126 (error "Unknown class type %s in method parameters"
2127 (nth 1 firstarg))))
2128 ;; Generics are higher.
2129 (setq key (eieio-specialized-key-to-generic-key key)))
2130 ;; Put this lambda into the symbol so we can find it.
2131 (if (byte-code-function-p (car-safe body))
2132 (eieiomt-add method (car-safe body) key argclass)
2133 (eieiomt-add method (append (list 'lambda (reverse argfix)) body)
2134 key argclass))
2137 (when eieio-optimize-primary-methods-flag
2138 ;; Optimizing step:
2140 ;; If this method, after this setup, only has primary methods, then
2141 ;; we can setup the generic that way.
2142 (if (generic-primary-only-p method)
2143 ;; If there is only one primary method, then we can go one more
2144 ;; optimization step.
2145 (if (generic-primary-only-one-p method)
2146 (eieio-defgeneric-reset-generic-form-primary-only-one method)
2147 (eieio-defgeneric-reset-generic-form-primary-only method))
2148 (eieio-defgeneric-reset-generic-form method)))
2150 method)
2151 (make-obsolete 'eieio-defmethod 'eieio--defmethod "24.1")
2153 (defun eieio-defgeneric (method doc-string)
2154 "Obsolete work part of an old version of the `defgeneric' macro."
2155 (if (and (fboundp method) (not (generic-p method))
2156 (or (byte-code-function-p (symbol-function method))
2157 (not (eq 'autoload (car (symbol-function method)))))
2159 (error "You cannot create a generic/method over an existing symbol: %s"
2160 method))
2161 ;; Don't do this over and over.
2162 (unless (fboundp 'method)
2163 ;; This defun tells emacs where the first definition of this
2164 ;; method is defined.
2165 `(defun ,method nil)
2166 ;; Make sure the method tables are installed.
2167 (eieiomt-install method)
2168 ;; Apply the actual body of this function.
2169 (fset method (eieio-defgeneric-form method doc-string))
2170 ;; Return the method
2171 'method))
2172 (make-obsolete 'eieio-defgeneric nil "24.1")
2174 (provide 'eieio-core)
2176 ;;; eieio-core.el ends here