Resynchronize with emacs bzr trunk eieio.
[gnus] / lisp / gnus-fallback-lib / eieio / eieio.el
1 ;;; eieio.el --- Enhanced Implementation of Emacs Interpreted Objects
2 ;;;              or maybe Eric's Implementation of Emacs Intrepreted Objects
3
4 ;; Copyright (C) 1995-1996, 1998-2011  Free Software Foundation, Inc.
5
6 ;; Author: Eric M. Ludlam <zappo@gnu.org>
7 ;; Version: 1.3
8 ;; Keywords: OO, lisp
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26 ;;
27 ;; EIEIO is a series of Lisp routines which implements a subset of
28 ;; CLOS, the Common Lisp Object System.  In addition, EIEIO also adds
29 ;; a few new features which help it integrate more strongly with the
30 ;; Emacs running environment.
31 ;;
32 ;; See eieio.texi for complete documentation on using this package.
33 ;;
34 ;; Note: the implementation of the c3 algorithm is based on:
35 ;;   Kim Barrett et al.: A Monotonic Superclass Linearization for Dylan
36 ;;   Retrieved from:
37 ;;   http://192.220.96.201/dylan/linearization-oopsla96.html
38
39 ;; There is funny stuff going on with typep and deftype.  This
40 ;; is the only way I seem to be able to make this stuff load properly.
41
42 ;; @TODO - fix :initform to be a form, not a quoted value
43 ;; @TODO - Prefix non-clos functions with `eieio-'.
44
45 ;;; Code:
46
47 (eval-when-compile
48   (require 'cl))
49
50 (defvar eieio-version "1.3"
51   "Current version of EIEIO.")
52
53 (defun eieio-version ()
54   "Display the current version of EIEIO."
55   (interactive)
56   (message eieio-version))
57
58 (eval-and-compile
59 ;; About the above.  EIEIO must process its own code when it compiles
60 ;; itself, thus, by eval-and-compiling outselves, we solve the problem.
61
62 ;; Compatibility
63 (if (fboundp 'compiled-function-arglist)
64
65     ;; XEmacs can only access a compiled functions arglist like this:
66     (defalias 'eieio-compiled-function-arglist 'compiled-function-arglist)
67
68   ;; Emacs doesn't have this function, but since FUNC is a vector, we can just
69   ;; grab the appropriate element.
70   (defun eieio-compiled-function-arglist (func)
71     "Return the argument list for the compiled function FUNC."
72     (aref func 0))
73
74   )
75
76 \f
77 ;;;
78 ;; Variable declarations.
79 ;;
80
81 (defvar eieio-hook nil
82   "*This hook is executed, then cleared each time `defclass' is called.")
83
84 (defvar eieio-error-unsupported-class-tags nil
85   "Non-nil to throw an error if an encountered tag is unsupported.
86 This may prevent classes from CLOS applications from being used with EIEIO
87 since EIEIO does not support all CLOS tags.")
88
89 (defvar eieio-skip-typecheck nil
90   "*If non-nil, skip all slot typechecking.
91 Set this to t permanently if a program is functioning well to get a
92 small speed increase.  This variable is also used internally to handle
93 default setting for optimization purposes.")
94
95 (defvar eieio-optimize-primary-methods-flag t
96   "Non-nil means to optimize the method dispatch on primary methods.")
97
98 ;; State Variables
99 ;; FIXME: These two constants below should have an `eieio-' prefix added!!
100 (defvar this nil
101   "Inside a method, this variable is the object in question.
102 DO NOT SET THIS YOURSELF unless you are trying to simulate friendly slots.
103
104 Note: Embedded methods are no longer supported.  The variable THIS is
105 still set for CLOS methods for the sake of routines like
106 `call-next-method'.")
107
108 (defvar scoped-class nil
109   "This is set to a class when a method is running.
110 This is so we know we are allowed to check private parts or how to
111 execute a `call-next-method'.  DO NOT SET THIS YOURSELF!")
112
113 (defvar eieio-initializing-object  nil
114   "Set to non-nil while initializing an object.")
115
116 (defconst eieio-unbound
117   (if (and (boundp 'eieio-unbound) (symbolp eieio-unbound))
118       eieio-unbound
119     (make-symbol "unbound"))
120   "Uninterned symbol representing an unbound slot in an object.")
121
122 ;; This is a bootstrap for eieio-default-superclass so it has a value
123 ;; while it is being built itself.
124 (defvar eieio-default-superclass nil)
125
126 ;; FIXME: The constants below should have an `eieio-' prefix added!!
127 (defconst class-symbol 1 "Class's symbol (self-referencing.).")
128 (defconst class-parent 2 "Class parent slot.")
129 (defconst class-children 3 "Class children class slot.")
130 (defconst class-symbol-obarray 4 "Obarray permitting fast access to variable position indexes.")
131 ;; @todo
132 ;; the word "public" here is leftovers from the very first version.
133 ;; Get rid of it!
134 (defconst class-public-a 5 "Class attribute index.")
135 (defconst class-public-d 6 "Class attribute defaults index.")
136 (defconst class-public-doc 7 "Class documentation strings for attributes.")
137 (defconst class-public-type 8 "Class type for a slot.")
138 (defconst class-public-custom 9 "Class custom type for a slot.")
139 (defconst class-public-custom-label 10 "Class custom group for a slot.")
140 (defconst class-public-custom-group 11 "Class custom group for a slot.")
141 (defconst class-public-printer 12 "Printer for a slot.")
142 (defconst class-protection 13 "Class protection for a slot.")
143 (defconst class-initarg-tuples 14 "Class initarg tuples list.")
144 (defconst class-class-allocation-a 15 "Class allocated attributes.")
145 (defconst class-class-allocation-doc 16 "Class allocated documentation.")
146 (defconst class-class-allocation-type 17 "Class allocated value type.")
147 (defconst class-class-allocation-custom 18 "Class allocated custom descriptor.")
148 (defconst class-class-allocation-custom-label 19 "Class allocated custom descriptor.")
149 (defconst class-class-allocation-custom-group 20 "Class allocated custom group.")
150 (defconst class-class-allocation-printer 21 "Class allocated printer for a slot.")
151 (defconst class-class-allocation-protection 22 "Class allocated protection list.")
152 (defconst class-class-allocation-values 23 "Class allocated value vector.")
153 (defconst class-default-object-cache 24
154   "Cache index of what a newly created object would look like.
155 This will speed up instantiation time as only a `copy-sequence' will
156 be needed, instead of looping over all the values and setting them
157 from the default.")
158 (defconst class-options 25
159   "Storage location of tagged class options.
160 Stored outright without modifications or stripping.")
161
162 (defconst class-num-slots 26
163   "Number of slots in the class definition object.")
164
165 (defconst object-class 1 "Index in an object vector where the class is stored.")
166 (defconst object-name 2 "Index in an object where the name is stored.")
167
168 (defconst method-static 0 "Index into :static tag on a method.")
169 (defconst method-before 1 "Index into :before tag on a method.")
170 (defconst method-primary 2 "Index into :primary tag on a method.")
171 (defconst method-after 3 "Index into :after tag on a method.")
172 (defconst method-num-lists 4 "Number of indexes into methods vector in which groups of functions are kept.")
173 (defconst method-generic-before 4 "Index into generic :before tag on a method.")
174 (defconst method-generic-primary 5 "Index into generic :primary tag on a method.")
175 (defconst method-generic-after 6 "Index into generic :after tag on a method.")
176 (defconst method-num-slots 7 "Number of indexes into a method's vector.")
177
178 (defsubst eieio-specialized-key-to-generic-key (key)
179   "Convert a specialized KEY into a generic method key."
180   (cond ((eq key method-static) 0) ;; don't convert
181         ((< key method-num-lists) (+ key 3)) ;; The conversion
182         (t key) ;; already generic.. maybe.
183         ))
184
185 \f
186 ;;; Important macros used in eieio.
187 ;;
188 (defmacro class-v (class)
189   "Internal: Return the class vector from the CLASS symbol."
190   ;; No check: If eieio gets this far, it's probably been checked already.
191   `(get ,class 'eieio-class-definition))
192
193 (defmacro class-p (class)
194   "Return t if CLASS is a valid class vector.
195 CLASS is a symbol."
196   ;; this new method is faster since it doesn't waste time checking lots of
197   ;; things.
198   `(condition-case nil
199        (eq (aref (class-v ,class) 0) 'defclass)
200      (error nil)))
201
202 (defmacro eieio-object-p (obj)
203   "Return non-nil if OBJ is an EIEIO object."
204   `(condition-case nil
205        (let ((tobj ,obj))
206          (and (eq (aref tobj 0) 'object)
207               (class-p (aref tobj object-class))))
208      (error nil)))
209 (defalias 'object-p 'eieio-object-p)
210
211 (defmacro class-constructor (class)
212   "Return the symbol representing the constructor of CLASS."
213   `(aref (class-v ,class) class-symbol))
214
215 (defmacro generic-p (method)
216   "Return t if symbol METHOD is a generic function.
217 Only methods have the symbol `eieio-method-obarray' as a property
218 \(which contains a list of all bindings to that method type.)"
219   `(and (fboundp ,method) (get ,method 'eieio-method-obarray)))
220
221 (defun generic-primary-only-p (method)
222   "Return t if symbol METHOD is a generic function with only primary methods.
223 Only methods have the symbol `eieio-method-obarray' as a property (which
224 contains a list of all bindings to that method type.)
225 Methods with only primary implementations are executed in an optimized way."
226   (and (generic-p method)
227        (let ((M (get method 'eieio-method-tree)))
228          (and (< 0 (length (aref M method-primary)))
229               (not (aref M method-static))
230               (not (aref M method-before))
231               (not (aref M method-after))
232               (not (aref M method-generic-before))
233               (not (aref M method-generic-primary))
234               (not (aref M method-generic-after))))
235        ))
236
237 (defun generic-primary-only-one-p (method)
238   "Return t if symbol METHOD is a generic function with only primary methods.
239 Only methods have the symbol `eieio-method-obarray' as a property (which
240 contains a list of all bindings to that method type.)
241 Methods with only primary implementations are executed in an optimized way."
242   (and (generic-p method)
243        (let ((M (get method 'eieio-method-tree)))
244          (and (= 1 (length (aref M method-primary)))
245               (not (aref M method-static))
246               (not (aref M method-before))
247               (not (aref M method-after))
248               (not (aref M method-generic-before))
249               (not (aref M method-generic-primary))
250               (not (aref M method-generic-after))))
251        ))
252
253 (defmacro class-option-assoc (list option)
254   "Return from LIST the found OPTION, or nil if it doesn't exist."
255   `(car-safe (cdr (memq ,option ,list))))
256
257 (defmacro class-option (class option)
258   "Return the value stored for CLASS' OPTION.
259 Return nil if that option doesn't exist."
260   `(class-option-assoc (aref (class-v ,class) class-options) ',option))
261
262 (defmacro class-abstract-p (class)
263   "Return non-nil if CLASS is abstract.
264 Abstract classes cannot be instantiated."
265   `(class-option ,class :abstract))
266
267 (defmacro class-method-invocation-order (class)
268   "Return the invocation order of CLASS.
269 Abstract classes cannot be instantiated."
270   `(or (class-option ,class :method-invocation-order)
271        :breadth-first))
272
273 \f
274 ;;; Defining a new class
275 ;;
276 (defmacro defclass (name superclass slots &rest options-and-doc)
277   "Define NAME as a new class derived from SUPERCLASS with SLOTS.
278 OPTIONS-AND-DOC is used as the class' options and base documentation.
279 SUPERCLASS is a list of superclasses to inherit from, with SLOTS
280 being the slots residing in that class definition.  NOTE: Currently
281 only one slot may exist in SUPERCLASS as multiple inheritance is not
282 yet supported.  Supported tags are:
283
284   :initform   - Initializing form.
285   :initarg    - Tag used during initialization.
286   :accessor   - Tag used to create a function to access this slot.
287   :allocation - Specify where the value is stored.
288                 Defaults to `:instance', but could also be `:class'.
289   :writer     - A function symbol which will `write' an object's slot.
290   :reader     - A function symbol which will `read' an object.
291   :type       - The type of data allowed in this slot (see `typep').
292   :documentation
293               - A string documenting use of this slot.
294
295 The following are extensions on CLOS:
296   :protection - Specify protection for this slot.
297                 Defaults to `:public'.  Also use `:protected', or `:private'.
298   :custom     - When customizing an object, the custom :type.  Public only.
299   :label      - A text string label used for a slot when customizing.
300   :group      - Name of a customization group this slot belongs in.
301   :printer    - A function to call to print the value of a slot.
302                 See `eieio-override-prin1' as an example.
303
304 A class can also have optional options.  These options happen in place
305 of documentation (including a :documentation tag), in addition to
306 documentation, or not at all.  Supported options are:
307
308   :documentation - The doc-string used for this class.
309
310 Options added to EIEIO:
311
312   :allow-nil-initform - Non-nil to skip typechecking of null initforms.
313   :custom-groups      - List of custom group names.  Organizes slots into
314                         reasonable groups for customizations.
315   :abstract           - Non-nil to prevent instances of this class.
316                         If a string, use as an error string if someone does
317                         try to make an instance.
318   :method-invocation-order
319                       - Control the method invocation order if there is
320                         multiple inheritance.  Valid values are:
321                          :breadth-first - The default.
322                          :depth-first
323
324 Options in CLOS not supported in EIEIO:
325
326   :metaclass - Class to use in place of `standard-class'
327   :default-initargs - Initargs to use when initializing new objects of
328                       this class.
329
330 Due to the way class options are set up, you can add any tags you wish,
331 and reference them using the function `class-option'."
332   ;; We must `eval-and-compile' this so that when we byte compile
333   ;; an eieio program, there is no need to load it ahead of time.
334   ;; It also provides lots of nice debugging errors at compile time.
335   `(eval-and-compile
336      (eieio-defclass ',name ',superclass ',slots ',options-and-doc)))
337
338 (defvar eieio-defclass-autoload-map (make-vector 7 nil)
339   "Symbol map of superclasses we find in autoloads.")
340
341 ;; We autoload this because it's used in `make-autoload'.
342 ;;;###autoload
343 (defun eieio-defclass-autoload (cname superclasses filename doc)
344   "Create autoload symbols for the EIEIO class CNAME.
345 SUPERCLASSES are the superclasses that CNAME inherits from.
346 DOC is the docstring for CNAME.
347 This function creates a mock-class for CNAME and adds it into
348 SUPERCLASSES as children.
349 It creates an autoload function for CNAME's constructor."
350   ;; Assume we've already debugged inputs.
351
352   (let* ((oldc (when (class-p cname) (class-v cname)))
353          (newc (make-vector class-num-slots nil))
354          )
355     (if oldc
356         nil ;; Do nothing if we already have this class.
357
358       ;; Create the class in NEWC, but don't fill anything else in.
359       (aset newc 0 'defclass)
360       (aset newc class-symbol cname)
361
362       (let ((clear-parent nil))
363         ;; No parents?
364         (when (not superclasses)
365           (setq superclasses '(eieio-default-superclass)
366                 clear-parent t)
367           )
368
369         ;; Hook our new class into the existing structures so we can
370         ;; autoload it later.
371         (dolist (SC superclasses)
372
373
374           ;; TODO - If we create an autoload that is in the map, that
375           ;;        map needs to be cleared!
376
377
378           ;; Does our parent exist?
379           (if (not (class-p SC))
380
381               ;; Create a symbol for this parent, and then store this
382               ;; parent on that symbol.
383               (let ((sym (intern (symbol-name SC) eieio-defclass-autoload-map)))
384                 (if (not (boundp sym))
385                     (set sym (list cname))
386                   (add-to-list sym cname))
387                 )
388
389             ;; We have a parent, save the child in there.
390             (when (not (member cname (aref (class-v SC) class-children)))
391               (aset (class-v SC) class-children
392                     (cons cname (aref (class-v SC) class-children)))))
393
394           ;; save parent in child
395           (aset newc class-parent (cons SC (aref newc class-parent)))
396           )
397
398         ;; turn this into a useable self-pointing symbol
399         (set cname cname)
400
401         ;; Store the new class vector definition into the symbol.  We need to
402         ;; do this first so that we can call defmethod for the accessor.
403         ;; The vector will be updated by the following while loop and will not
404         ;; need to be stored a second time.
405         (put cname 'eieio-class-definition newc)
406
407         ;; Clear the parent
408         (if clear-parent (aset newc class-parent nil))
409
410         ;; Create an autoload on top of our constructor function.
411         (autoload cname filename doc nil nil)
412         (autoload (intern (concat (symbol-name cname) "-p")) filename "" nil nil)
413         (autoload (intern (concat (symbol-name cname) "-child-p")) filename "" nil nil)
414
415         ))))
416
417 (defsubst eieio-class-un-autoload (cname)
418   "If class CNAME is in an autoload state, load its file."
419   (when (eq (car-safe (symbol-function cname)) 'autoload)
420     (load-library (car (cdr (symbol-function cname))))))
421
422 (defun eieio-defclass (cname superclasses slots options-and-doc)
423   "Define CNAME as a new subclass of SUPERCLASSES.
424 SLOTS are the slots residing in that class definition, and options or
425 documentation OPTIONS-AND-DOC is the toplevel documentation for this class.
426 See `defclass' for more information."
427   ;; Run our eieio-hook each time, and clear it when we are done.
428   ;; This way people can add hooks safely if they want to modify eieio
429   ;; or add definitions when eieio is loaded or something like that.
430   (run-hooks 'eieio-hook)
431   (setq eieio-hook nil)
432
433   (if (not (symbolp cname)) (signal 'wrong-type-argument '(symbolp cname)))
434   (if (not (listp superclasses)) (signal 'wrong-type-argument '(listp superclasses)))
435
436   (let* ((pname (if superclasses superclasses nil))
437          (newc (make-vector class-num-slots nil))
438          (oldc (when (class-p cname) (class-v cname)))
439          (groups nil) ;; list of groups id'd from slots
440          (options nil)
441          (clearparent nil))
442
443     (aset newc 0 'defclass)
444     (aset newc class-symbol cname)
445
446     ;; If this class already existed, and we are updating its structure,
447     ;; make sure we keep the old child list.  This can cause bugs, but
448     ;; if no new slots are created, it also saves time, and prevents
449     ;; method table breakage, particularly when the users is only
450     ;; byte compiling an EIEIO file.
451     (if oldc
452         (aset newc class-children (aref oldc class-children))
453       ;; If the old class did not exist, but did exist in the autoload map, then adopt those children.
454       ;; This is like the above, but deals with autoloads nicely.
455       (let ((sym (intern-soft (symbol-name cname) eieio-defclass-autoload-map)))
456         (when sym
457           (condition-case nil
458               (aset newc class-children (symbol-value sym))
459             (error nil))
460           (unintern (symbol-name cname) eieio-defclass-autoload-map)
461           ))
462       )
463
464     (cond ((and (stringp (car options-and-doc))
465                 (/= 1 (% (length options-and-doc) 2)))
466            (error "Too many arguments to `defclass'"))
467           ((and (symbolp (car options-and-doc))
468                 (/= 0 (% (length options-and-doc) 2)))
469            (error "Too many arguments to `defclass'"))
470           )
471
472     (setq options
473           (if (stringp (car options-and-doc))
474               (cons :documentation options-and-doc)
475             options-and-doc))
476
477     (if pname
478         (progn
479           (while pname
480             (if (and (car pname) (symbolp (car pname)))
481                 (if (not (class-p (car pname)))
482                     ;; bad class
483                     (error "Given parent class %s is not a class" (car pname))
484                   ;; good parent class...
485                   ;; save new child in parent
486                   (when (not (member cname (aref (class-v (car pname)) class-children)))
487                     (aset (class-v (car pname)) class-children
488                           (cons cname (aref (class-v (car pname)) class-children))))
489                   ;; Get custom groups, and store them into our local copy.
490                   (mapc (lambda (g) (add-to-list 'groups g))
491                         (class-option (car pname) :custom-groups))
492                   ;; save parent in child
493                   (aset newc class-parent (cons (car pname) (aref newc class-parent))))
494               (error "Invalid parent class %s" pname))
495             (setq pname (cdr pname)))
496           ;; Reverse the list of our parents so that they are prioritized in
497           ;; the same order as specified in the code.
498           (aset newc class-parent (nreverse (aref newc class-parent))) )
499       ;; If there is nothing to loop over, then inherit from the
500       ;; default superclass.
501       (unless (eq cname 'eieio-default-superclass)
502         ;; adopt the default parent here, but clear it later...
503         (setq clearparent t)
504         ;; save new child in parent
505         (if (not (member cname (aref (class-v 'eieio-default-superclass) class-children)))
506             (aset (class-v 'eieio-default-superclass) class-children
507                   (cons cname (aref (class-v 'eieio-default-superclass) class-children))))
508         ;; save parent in child
509         (aset newc class-parent (list eieio-default-superclass))))
510
511     ;; turn this into a useable self-pointing symbol
512     (set cname cname)
513
514     ;; These two tests must be created right away so we can have self-
515     ;; referencing classes.  ei, a class whose slot can contain only
516     ;; pointers to itself.
517
518     ;; Create the test function
519     (let ((csym (intern (concat (symbol-name cname) "-p"))))
520       (fset csym
521             (list 'lambda (list 'obj)
522                   (format "Test OBJ to see if it an object of type %s" cname)
523                   (list 'and '(eieio-object-p obj)
524                         (list 'same-class-p 'obj cname)))))
525
526     ;; Make sure the method invocation order  is a valid value.
527     (let ((io (class-option-assoc options :method-invocation-order)))
528       (when (and io (not (member io '(:depth-first :breadth-first :c3))))
529         (error "Method invocation order %s is not allowed" io)
530         ))
531
532     ;; Create a handy child test too
533     (let ((csym (intern (concat (symbol-name cname) "-child-p"))))
534       (fset csym
535             `(lambda (obj)
536                ,(format
537                   "Test OBJ to see if it an object is a child of type %s"
538                   cname)
539                (and (eieio-object-p obj)
540                     (object-of-class-p obj ,cname))))
541
542       ;; When using typep, (typep OBJ 'myclass) returns t for objects which
543       ;; are subclasses of myclass.  For our predicates, however, it is
544       ;; important for EIEIO to be backwards compatible, where
545       ;; myobject-p, and myobject-child-p are different.
546       ;; "cl" uses this technique to specify symbols with specific typep
547       ;; test, so we can let typep have the CLOS documented behavior
548       ;; while keeping our above predicate clean.
549
550       ;; It would be cleaner to use `defsetf' here, but that requires cl
551       ;; at runtime.
552       (put cname 'cl-deftype-handler
553            (list 'lambda () `(list 'satisfies (quote ,csym)))))
554
555     ;; before adding new slots, lets add all the methods and classes
556     ;; in from the parent class
557     (eieio-copy-parents-into-subclass newc superclasses)
558
559     ;; Store the new class vector definition into the symbol.  We need to
560     ;; do this first so that we can call defmethod for the accessor.
561     ;; The vector will be updated by the following while loop and will not
562     ;; need to be stored a second time.
563     (put cname 'eieio-class-definition newc)
564
565     ;; Query each slot in the declaration list and mangle into the
566     ;; class structure I have defined.
567     (while slots
568       (let* ((slot1  (car slots))
569              (name    (car slot1))
570              (slot   (cdr slot1))
571              (acces   (plist-get slot ':accessor))
572              (init    (or (plist-get slot ':initform)
573                           (if (member ':initform slot) nil
574                             eieio-unbound)))
575              (initarg (plist-get slot ':initarg))
576              (docstr  (plist-get slot ':documentation))
577              (prot    (plist-get slot ':protection))
578              (reader  (plist-get slot ':reader))
579              (writer  (plist-get slot ':writer))
580              (alloc   (plist-get slot ':allocation))
581              (type    (plist-get slot ':type))
582              (custom  (plist-get slot ':custom))
583              (label   (plist-get slot ':label))
584              (customg (plist-get slot ':group))
585              (printer (plist-get slot ':printer))
586
587              (skip-nil (class-option-assoc options :allow-nil-initform))
588              )
589
590         (if eieio-error-unsupported-class-tags
591             (let ((tmp slot))
592               (while tmp
593                 (if (not (member (car tmp) '(:accessor
594                                              :initform
595                                              :initarg
596                                              :documentation
597                                              :protection
598                                              :reader
599                                              :writer
600                                              :allocation
601                                              :type
602                                              :custom
603                                              :label
604                                              :group
605                                              :printer
606                                              :allow-nil-initform
607                                              :custom-groups)))
608                     (signal 'invalid-slot-type (list (car tmp))))
609                 (setq tmp (cdr (cdr tmp))))))
610
611         ;; Clean up the meaning of protection.
612         (cond ((or (eq prot 'public) (eq prot :public)) (setq prot nil))
613               ((or (eq prot 'protected) (eq prot :protected)) (setq prot 'protected))
614               ((or (eq prot 'private) (eq prot :private)) (setq prot 'private))
615               ((eq prot nil) nil)
616               (t (signal 'invalid-slot-type (list ':protection prot))))
617
618         ;; Make sure the :allocation parameter has a valid value.
619         (if (not (or (not alloc) (eq alloc :class) (eq alloc :instance)))
620             (signal 'invalid-slot-type (list ':allocation alloc)))
621
622         ;; The default type specifier is supposed to be t, meaning anything.
623         (if (not type) (setq type t))
624
625         ;; Label is nil, or a string
626         (if (not (or (null label) (stringp label)))
627             (signal 'invalid-slot-type (list ':label label)))
628
629         ;; Is there an initarg, but allocation of class?
630         (if (and initarg (eq alloc :class))
631             (message "Class allocated slots do not need :initarg"))
632
633         ;; intern the symbol so we can use it blankly
634         (if initarg (set initarg initarg))
635
636         ;; The customgroup should be a list of symbols
637         (cond ((null customg)
638                (setq customg '(default)))
639               ((not (listp customg))
640                (setq customg (list customg))))
641         ;; The customgroup better be a symbol, or list of symbols.
642         (mapc (lambda (cg)
643                 (if (not (symbolp cg))
644                     (signal 'invalid-slot-type (list ':group cg))))
645                 customg)
646
647         ;; First up, add this slot into our new class.
648         (eieio-add-new-slot newc name init docstr type custom label customg printer
649                              prot initarg alloc 'defaultoverride skip-nil)
650
651         ;; We need to id the group, and store them in a group list attribute.
652         (mapc (lambda (cg) (add-to-list 'groups cg)) customg)
653
654         ;; anyone can have an accessor function.  This creates a function
655         ;; of the specified name, and also performs a `defsetf' if applicable
656         ;; so that users can `setf' the space returned by this function
657         (if acces
658             (progn
659               (eieio--defmethod
660                acces (if (eq alloc :class) :static :primary) cname
661                `(lambda (this)
662                   ,(format
663                        "Retrieves the slot `%s' from an object of class `%s'"
664                        name cname)
665                   (if (slot-boundp this ',name)
666                       (eieio-oref this ',name)
667                             ;; Else - Some error?  nil?
668                             nil)))
669
670               ;; Provide a setf method.  It would be cleaner to use
671               ;; defsetf, but that would require CL at runtime.
672               (put acces 'setf-method
673                    `(lambda (widget)
674                       (let* ((--widget-sym-- (make-symbol "--widget--"))
675                              (--store-sym-- (make-symbol "--store--")))
676                         (list
677                          (list --widget-sym--)
678                          (list widget)
679                          (list --store-sym--)
680                          (list 'eieio-oset --widget-sym-- '',name --store-sym--)
681                          (list 'getfoo --widget-sym--)))))))
682
683         ;; If a writer is defined, then create a generic method of that
684         ;; name whose purpose is to set the value of the slot.
685         (if writer
686             (eieio--defmethod
687              writer nil cname
688              `(lambda (this value)
689                 ,(format "Set the slot `%s' of an object of class `%s'"
690                               name cname)
691                 (setf (slot-value this ',name) value))))
692         ;; If a reader is defined, then create a generic method
693         ;; of that name whose purpose is to access this slot value.
694         (if reader
695             (eieio--defmethod
696              reader nil cname
697              `(lambda (this)
698                 ,(format "Access the slot `%s' from object of class `%s'"
699                               name cname)
700                 (slot-value this ',name))))
701         )
702       (setq slots (cdr slots)))
703
704     ;; Now that everything has been loaded up, all our lists are backwards!  Fix that up now.
705     (aset newc class-public-a (nreverse (aref newc class-public-a)))
706     (aset newc class-public-d (nreverse (aref newc class-public-d)))
707     (aset newc class-public-doc (nreverse (aref newc class-public-doc)))
708     (aset newc class-public-type
709           (apply 'vector (nreverse (aref newc class-public-type))))
710     (aset newc class-public-custom (nreverse (aref newc class-public-custom)))
711     (aset newc class-public-custom-label (nreverse (aref newc class-public-custom-label)))
712     (aset newc class-public-custom-group (nreverse (aref newc class-public-custom-group)))
713     (aset newc class-public-printer (nreverse (aref newc class-public-printer)))
714     (aset newc class-protection (nreverse (aref newc class-protection)))
715     (aset newc class-initarg-tuples (nreverse (aref newc class-initarg-tuples)))
716
717     ;; The storage for class-class-allocation-type needs to be turned into
718     ;; a vector now.
719     (aset newc class-class-allocation-type
720           (apply 'vector (aref newc class-class-allocation-type)))
721
722     ;; Also, take class allocated values, and vectorize them for speed.
723     (aset newc class-class-allocation-values
724           (apply 'vector (aref newc class-class-allocation-values)))
725
726     ;; Attach slot symbols into an obarray, and store the index of
727     ;; this slot as the variable slot in this new symbol.  We need to
728     ;; know about primes, because obarrays are best set in vectors of
729     ;; prime number length, and we also need to make our vector small
730     ;; to save space, and also optimal for the number of items we have.
731     (let* ((cnt 0)
732            (pubsyms (aref newc class-public-a))
733            (prots (aref newc class-protection))
734            (l (length pubsyms))
735            (vl (let ((primes '( 3 5 7 11 13 17 19 23 29 31 37 41 43 47
736                                   53 59 61 67 71 73 79 83 89 97 101 )))
737                  (while (and primes (< (car primes) l))
738                    (setq primes (cdr primes)))
739                  (car primes)))
740            (oa (make-vector vl 0))
741            (newsym))
742       (while pubsyms
743         (setq newsym (intern (symbol-name (car pubsyms)) oa))
744         (set newsym cnt)
745         (setq cnt (1+ cnt))
746         (if (car prots) (put newsym 'protection (car prots)))
747         (setq pubsyms (cdr pubsyms)
748               prots (cdr prots)))
749       (aset newc class-symbol-obarray oa)
750       )
751
752     ;; Create the constructor function
753     (if (class-option-assoc options :abstract)
754         ;; Abstract classes cannot be instantiated.  Say so.
755         (let ((abs (class-option-assoc options :abstract)))
756           (if (not (stringp abs))
757               (setq abs (format "Class %s is abstract" cname)))
758           (fset cname
759                 `(lambda (&rest stuff)
760                    ,(format "You cannot create a new object of type %s" cname)
761                    (error ,abs))))
762
763       ;; Non-abstract classes need a constructor.
764       (fset cname
765             `(lambda (newname &rest slots)
766                ,(format "Create a new object with name NAME of class type %s" cname)
767                (apply 'constructor ,cname newname slots)))
768       )
769
770     ;; Set up a specialized doc string.
771     ;; Use stored value since it is calculated in a non-trivial way
772     (put cname 'variable-documentation
773          (class-option-assoc options :documentation))
774
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) (add-to-list 'g cg)) groups)
778       (if (memq :custom-groups options)
779           (setcar (cdr (memq :custom-groups options)) g)
780         (setq options (cons :custom-groups (cons g options)))))
781
782     ;; Set up the options we have collected.
783     (aset newc class-options options)
784
785     ;; if this is a superclass, clear out parent (which was set to the
786     ;; default superclass eieio-default-superclass)
787     (if clearparent (aset newc class-parent nil))
788
789     ;; Create the cached default object.
790     (let ((cache (make-vector (+ (length (aref newc class-public-a))
791                                  3) nil)))
792       (aset cache 0 'object)
793       (aset cache object-class cname)
794       (aset cache object-name '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       (aset newc class-default-object-cache cache))
800
801     ;; Return our new class object
802     ;; newc
803     cname
804     ))
805
806 (defun eieio-perform-slot-validation-for-default (slot spec value skipnil)
807   "For SLOT, signal if SPEC does not match VALUE.
808 If SKIPNIL is non-nil, then if VALUE is nil return t instead."
809   (if (and (not (eieio-eval-default-p value))
810            (not eieio-skip-typecheck)
811            (not (and skipnil (null value)))
812            (not (eieio-perform-slot-validation spec value)))
813       (signal 'invalid-slot-type (list slot spec value))))
814
815 (defun eieio-add-new-slot (newc a d doc type cust label custg print prot init alloc
816                                  &optional defaultoverride skipnil)
817   "Add into NEWC attribute A.
818 If A already exists in NEWC, then do nothing.  If it doesn't exist,
819 then also add in D (default), DOC, TYPE, CUST, LABEL, CUSTG, PRINT, PROT, and INIT arg.
820 Argument ALLOC specifies if the slot is allocated per instance, or per class.
821 If optional DEFAULTOVERRIDE is non-nil, then if A exists in NEWC,
822 we must override its value for a default.
823 Optional argument SKIPNIL indicates if type checking should be skipped
824 if default value is nil."
825   ;; Make sure we duplicate those items that are sequences.
826   (condition-case nil
827       (if (sequencep d) (setq d (copy-sequence d)))
828     ;; This copy can fail on a cons cell with a non-cons in the cdr.  Lets skip it if it doesn't work.
829     (error nil))
830   (if (sequencep type) (setq type (copy-sequence type)))
831   (if (sequencep cust) (setq cust (copy-sequence cust)))
832   (if (sequencep custg) (setq custg (copy-sequence custg)))
833
834   ;; To prevent override information w/out specification of storage,
835   ;; we need to do this little hack.
836   (if (member a (aref newc class-class-allocation-a)) (setq alloc ':class))
837
838   (if (or (not alloc) (and (symbolp alloc) (eq alloc ':instance)))
839       ;; In this case, we modify the INSTANCE version of a given slot.
840
841       (progn
842
843         ;; Only add this element if it is so-far unique
844         (if (not (member a (aref newc class-public-a)))
845             (progn
846               (eieio-perform-slot-validation-for-default a type d skipnil)
847               (aset newc class-public-a (cons a (aref newc class-public-a)))
848               (aset newc class-public-d (cons d (aref newc class-public-d)))
849               (aset newc class-public-doc (cons doc (aref newc class-public-doc)))
850               (aset newc class-public-type (cons type (aref newc class-public-type)))
851               (aset newc class-public-custom (cons cust (aref newc class-public-custom)))
852               (aset newc class-public-custom-label (cons label (aref newc class-public-custom-label)))
853               (aset newc class-public-custom-group (cons custg (aref newc class-public-custom-group)))
854               (aset newc class-public-printer (cons print (aref newc class-public-printer)))
855               (aset newc class-protection (cons prot (aref newc class-protection)))
856               (aset newc class-initarg-tuples (cons (cons init a) (aref newc class-initarg-tuples)))
857               )
858           ;; When defaultoverride is true, we are usually adding new local
859           ;; attributes which must override the default value of any slot
860           ;; passed in by one of the parent classes.
861           (when defaultoverride
862             ;; There is a match, and we must override the old value.
863             (let* ((ca (aref newc class-public-a))
864                    (np (member a ca))
865                    (num (- (length ca) (length np)))
866                    (dp (if np (nthcdr num (aref newc class-public-d))
867                          nil))
868                    (tp (if np (nth num (aref newc class-public-type))))
869                    )
870               (if (not np)
871                   (error "EIEIO internal error overriding default value for %s"
872                          a)
873                 ;; If type is passed in, is it the same?
874                 (if (not (eq type t))
875                     (if (not (equal type tp))
876                         (error
877                          "Child slot type `%s' does not match inherited type `%s' for `%s'"
878                          type tp a)))
879                 ;; If we have a repeat, only update the initarg...
880                 (unless (eq d eieio-unbound)
881                   (eieio-perform-slot-validation-for-default a tp d skipnil)
882                   (setcar dp d))
883                 ;; If we have a new initarg, check for it.
884                 (when init
885                   (let* ((inits (aref newc class-initarg-tuples))
886                          (inita (rassq a inits)))
887                     ;; Replace the CAR of the associate INITA.
888                     ;;(message "Initarg: %S replace %s" inita init)
889                     (setcar inita init)
890                     ))
891
892                 ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
893                 ;; checked and SHOULD match the superclass
894                 ;; protection. Otherwise an error is thrown. However
895                 ;; I wonder if a more flexible schedule might be
896                 ;; implemented.
897                 ;;
898                 ;; EML - We used to have (if prot... here,
899                 ;;       but a prot of 'nil means public.
900                 ;;
901                 (let ((super-prot (nth num (aref newc class-protection)))
902                       )
903                   (if (not (eq prot super-prot))
904                       (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
905                              prot super-prot a)))
906                 ;; End original PLN
907
908                 ;; PLN Tue Jun 26 11:57:06 2007 :
909                 ;; Do a non redundant combination of ancient custom
910                 ;; groups and new ones.
911                 (when custg
912                   (let* ((groups
913                           (nthcdr num (aref newc class-public-custom-group)))
914                          (list1 (car groups))
915                          (list2 (if (listp custg) custg (list custg))))
916                     (if (< (length list1) (length list2))
917                         (setq list1 (prog1 list2 (setq list2 list1))))
918                     (dolist (elt list2)
919                       (unless (memq elt list1)
920                         (push elt list1)))
921                     (setcar groups list1)))
922                 ;;  End PLN
923
924                 ;;  PLN Mon Jun 25 22:44:34 2007 : If a new cust is
925                 ;;  set, simply replaces the old one.
926                 (when cust
927                   ;; (message "Custom type redefined to %s" cust)
928                   (setcar (nthcdr num (aref newc class-public-custom)) cust))
929
930                 ;; If a new label is specified, it simply replaces
931                 ;; the old one.
932                 (when label
933                   ;; (message "Custom label redefined to %s" label)
934                   (setcar (nthcdr num (aref newc class-public-custom-label)) label))
935                 ;;  End PLN
936
937                 ;; PLN Sat Jun 30 17:24:42 2007 : when a new
938                 ;; doc is specified, simply replaces the old one.
939                 (when doc
940                   ;;(message "Documentation redefined to %s" doc)
941                   (setcar (nthcdr num (aref newc class-public-doc))
942                           doc))
943                 ;; End PLN
944
945                 ;; If a new printer is specified, it simply replaces
946                 ;; the old one.
947                 (when print
948                   ;; (message "printer redefined to %s" print)
949                   (setcar (nthcdr num (aref newc class-public-printer)) print))
950
951                 )))
952           ))
953
954     ;; CLASS ALLOCATED SLOTS
955     (let ((value (eieio-default-eval-maybe d)))
956       (if (not (member a (aref newc class-class-allocation-a)))
957           (progn
958             (eieio-perform-slot-validation-for-default a type value skipnil)
959             ;; Here we have found a :class version of a slot.  This
960             ;; requires a very different aproach.
961             (aset newc class-class-allocation-a (cons a (aref newc class-class-allocation-a)))
962             (aset newc class-class-allocation-doc (cons doc (aref newc class-class-allocation-doc)))
963             (aset newc class-class-allocation-type (cons type (aref newc class-class-allocation-type)))
964             (aset newc class-class-allocation-custom (cons cust (aref newc class-class-allocation-custom)))
965             (aset newc class-class-allocation-custom-label (cons label (aref newc class-class-allocation-custom-label)))
966             (aset newc class-class-allocation-custom-group (cons custg (aref newc class-class-allocation-custom-group)))
967             (aset newc class-class-allocation-protection (cons prot (aref newc class-class-allocation-protection)))
968             ;; Default value is stored in the 'values section, since new objects
969             ;; can't initialize from this element.
970             (aset newc class-class-allocation-values (cons value (aref newc class-class-allocation-values))))
971         (when defaultoverride
972           ;; There is a match, and we must override the old value.
973           (let* ((ca (aref newc class-class-allocation-a))
974                  (np (member a ca))
975                  (num (- (length ca) (length np)))
976                  (dp (if np
977                          (nthcdr num
978                                  (aref newc class-class-allocation-values))
979                        nil))
980                  (tp (if np (nth num (aref newc class-class-allocation-type))
981                        nil)))
982             (if (not np)
983                 (error "EIEIO internal error overriding default value for %s"
984                        a)
985               ;; If type is passed in, is it the same?
986               (if (not (eq type t))
987                   (if (not (equal type tp))
988                       (error
989                        "Child slot type `%s' does not match inherited type `%s' for `%s'"
990                        type tp a)))
991               ;; EML - Note: the only reason to override a class bound slot
992               ;;       is to change the default, so allow unbound in.
993
994               ;; If we have a repeat, only update the vlaue...
995               (eieio-perform-slot-validation-for-default a tp value skipnil)
996               (setcar dp value))
997
998             ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
999             ;; checked and SHOULD match the superclass
1000             ;; protection. Otherwise an error is thrown. However
1001             ;; I wonder if a more flexible schedule might be
1002             ;; implemented.
1003             (let ((super-prot
1004                    (car (nthcdr num (aref newc class-class-allocation-protection)))))
1005               (if (not (eq prot super-prot))
1006                   (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
1007                          prot super-prot a)))
1008             ;; Do a non redundant combination of ancient custom groups
1009             ;; and new ones.
1010             (when custg
1011               (let* ((groups
1012                       (nthcdr num (aref newc class-class-allocation-custom-group)))
1013                      (list1 (car groups))
1014                      (list2 (if (listp custg) custg (list custg))))
1015                 (if (< (length list1) (length list2))
1016                     (setq list1 (prog1 list2 (setq list2 list1))))
1017                 (dolist (elt list2)
1018                   (unless (memq elt list1)
1019                     (push elt list1)))
1020                 (setcar groups list1)))
1021
1022             ;; PLN Sat Jun 30 17:24:42 2007 : when a new
1023             ;; doc is specified, simply replaces the old one.
1024             (when doc
1025               ;;(message "Documentation redefined to %s" doc)
1026               (setcar (nthcdr num (aref newc class-class-allocation-doc))
1027                       doc))
1028             ;; End PLN
1029
1030             ;; If a new printer is specified, it simply replaces
1031             ;; the old one.
1032             (when print
1033               ;; (message "printer redefined to %s" print)
1034               (setcar (nthcdr num (aref newc class-class-allocation-printer)) print))
1035
1036             ))
1037         ))
1038     ))
1039
1040 (defun eieio-copy-parents-into-subclass (newc parents)
1041   "Copy into NEWC the slots of PARENTS.
1042 Follow the rules of not overwriting early parents when applying to
1043 the new child class."
1044   (let ((ps (aref newc class-parent))
1045         (sn (class-option-assoc (aref newc class-options)
1046                                 ':allow-nil-initform)))
1047     (while ps
1048       ;; First, duplicate all the slots of the parent.
1049       (let ((pcv (class-v (car ps))))
1050         (let ((pa (aref pcv class-public-a))
1051               (pd (aref pcv class-public-d))
1052               (pdoc (aref pcv class-public-doc))
1053               (ptype (aref pcv class-public-type))
1054               (pcust (aref pcv class-public-custom))
1055               (plabel (aref pcv class-public-custom-label))
1056               (pcustg (aref pcv class-public-custom-group))
1057               (printer (aref pcv class-public-printer))
1058               (pprot (aref pcv class-protection))
1059               (pinit (aref pcv class-initarg-tuples))
1060               (i 0))
1061           (while pa
1062             (eieio-add-new-slot newc
1063                                  (car pa) (car pd) (car pdoc) (aref ptype i)
1064                                  (car pcust) (car plabel) (car pcustg)
1065                                  (car printer)
1066                                  (car pprot) (car-safe (car pinit)) nil nil sn)
1067             ;; Increment each value.
1068             (setq pa (cdr pa)
1069                   pd (cdr pd)
1070                   pdoc (cdr pdoc)
1071                   i (1+ i)
1072                   pcust (cdr pcust)
1073                   plabel (cdr plabel)
1074                   pcustg (cdr pcustg)
1075                   printer (cdr printer)
1076                   pprot (cdr pprot)
1077                   pinit (cdr pinit))
1078             )) ;; while/let
1079         ;; Now duplicate all the class alloc slots.
1080         (let ((pa (aref pcv class-class-allocation-a))
1081               (pdoc (aref pcv class-class-allocation-doc))
1082               (ptype (aref pcv class-class-allocation-type))
1083               (pcust (aref pcv class-class-allocation-custom))
1084               (plabel (aref pcv class-class-allocation-custom-label))
1085               (pcustg (aref pcv class-class-allocation-custom-group))
1086               (printer (aref pcv class-class-allocation-printer))
1087               (pprot (aref pcv class-class-allocation-protection))
1088               (pval (aref pcv class-class-allocation-values))
1089               (i 0))
1090           (while pa
1091             (eieio-add-new-slot newc
1092                                  (car pa) (aref pval i) (car pdoc) (aref ptype i)
1093                                  (car pcust) (car plabel) (car pcustg)
1094                                  (car printer)
1095                                  (car pprot) nil ':class sn)
1096             ;; Increment each value.
1097             (setq pa (cdr pa)
1098                   pdoc (cdr pdoc)
1099                   pcust (cdr pcust)
1100                   plabel (cdr plabel)
1101                   pcustg (cdr pcustg)
1102                   printer (cdr printer)
1103                   pprot (cdr pprot)
1104                   i (1+ i))
1105             ))) ;; while/let
1106       ;; Loop over each parent class
1107       (setq ps (cdr ps)))
1108     ))
1109
1110 ;;; CLOS style implementation of object creators.
1111 ;;
1112 (defun make-instance (class &rest initargs)
1113   "Make a new instance of CLASS based on INITARGS.
1114 CLASS is a class symbol.  For example:
1115
1116   (make-instance 'foo)
1117
1118   INITARGS is a property list with keywords based on the :initarg
1119 for each slot.  For example:
1120
1121   (make-instance 'foo :slot1 value1 :slotN valueN)
1122
1123 Compatibility note:
1124
1125 If the first element of INITARGS is a string, it is used as the
1126 name of the class.
1127
1128 In EIEIO, the class' constructor requires a name for use when printing.
1129 `make-instance' in CLOS doesn't use names the way Emacs does, so the
1130 class is used as the name slot instead when INITARGS doesn't start with
1131 a string."
1132   (if (and (car initargs) (stringp (car initargs)))
1133       (apply (class-constructor class) initargs)
1134     (apply  (class-constructor class)
1135             (cond ((symbolp class) (symbol-name class))
1136                   (t (format "%S" class)))
1137             initargs)))
1138
1139 \f
1140 ;;; CLOS methods and generics
1141 ;;
1142 (defmacro defgeneric (method args &optional doc-string)
1143   "Create a generic function METHOD.
1144 DOC-STRING is the base documentation for this class.  A generic
1145 function has no body, as its purpose is to decide which method body
1146 is appropriate to use.  Uses `defmethod' to create methods, and calls
1147 `defgeneric' for you.  With this implementation the ARGS are
1148 currently ignored.  You can use `defgeneric' to apply specialized
1149 top level documentation to a method."
1150   `(eieio-defgeneric (quote ,method) ,doc-string))
1151
1152 (defun eieio-defgeneric-form (method doc-string)
1153   "The lambda form that would be used as the function defined on METHOD.
1154 All methods should call the same EIEIO function for dispatch.
1155 DOC-STRING is the documentation attached to METHOD."
1156   `(lambda (&rest local-args)
1157      ,doc-string
1158      (eieio-generic-call (quote ,method) local-args)))
1159
1160 (defsubst eieio-defgeneric-reset-generic-form (method)
1161   "Setup METHOD to call the generic form."
1162   (let ((doc-string (documentation method)))
1163     (fset method (eieio-defgeneric-form method doc-string))))
1164
1165 (defun eieio-defgeneric-form-primary-only (method doc-string)
1166   "The lambda form that would be used as the function defined on METHOD.
1167 All methods should call the same EIEIO function for dispatch.
1168 DOC-STRING is the documentation attached to METHOD."
1169   `(lambda (&rest local-args)
1170      ,doc-string
1171      (eieio-generic-call-primary-only (quote ,method) local-args)))
1172
1173 (defsubst eieio-defgeneric-reset-generic-form-primary-only (method)
1174   "Setup METHOD to call the generic form."
1175   (let ((doc-string (documentation method)))
1176     (fset method (eieio-defgeneric-form-primary-only method doc-string))))
1177
1178 (defun eieio-defgeneric-form-primary-only-one (method doc-string
1179                                                       class
1180                                                       impl
1181                                                       )
1182   "The lambda form that would be used as the function defined on METHOD.
1183 All methods should call the same EIEIO function for dispatch.
1184 DOC-STRING is the documentation attached to METHOD.
1185 CLASS is the class symbol needed for private method access.
1186 IMPL is the symbol holding the method implementation."
1187   ;; NOTE: I tried out byte compiling this little fcn.  Turns out it
1188   ;; is faster to execute this for not byte-compiled.  ie, install this,
1189   ;; then measure calls going through here.  I wonder why.
1190   (require 'bytecomp)
1191   (let ((byte-compile-warnings nil))
1192     (byte-compile
1193      `(lambda (&rest local-args)
1194         ,doc-string
1195         ;; This is a cool cheat.  Usually we need to look up in the
1196         ;; method table to find out if there is a method or not.  We can
1197         ;; instead make that determination at load time when there is
1198         ;; only one method.  If the first arg is not a child of the class
1199         ;; of that one implementation, then clearly, there is no method def.
1200         (if (not (eieio-object-p (car local-args)))
1201             ;; Not an object.  Just signal.
1202             (signal 'no-method-definition
1203                     (list ,(list 'quote method) local-args))
1204
1205           ;; We do have an object.  Make sure it is the right type.
1206           (if ,(if (eq class eieio-default-superclass)
1207                    nil ; default superclass means just an obj.  Already asked.
1208                  `(not (child-of-class-p (aref (car local-args) object-class)
1209                                          ,(list 'quote class)))
1210                  )
1211
1212               ;; If not the right kind of object, call no applicable
1213               (apply 'no-applicable-method (car local-args)
1214                      ,(list 'quote method) local-args)
1215
1216             ;; It is ok, do the call.
1217             ;; Fill in inter-call variables then evaluate the method.
1218             (let ((scoped-class ,(list 'quote class))
1219                   (eieio-generic-call-next-method-list nil)
1220                   (eieio-generic-call-key method-primary)
1221                   (eieio-generic-call-methodname ,(list 'quote method))
1222                   (eieio-generic-call-arglst local-args)
1223                   )
1224               (apply ,(list 'quote impl) local-args)
1225               ;(,impl local-args)
1226               )))))))
1227
1228 (defsubst eieio-defgeneric-reset-generic-form-primary-only-one (method)
1229   "Setup METHOD to call the generic form."
1230   (let* ((doc-string (documentation method))
1231          (M (get method 'eieio-method-tree))
1232          (entry (car (aref M method-primary)))
1233          )
1234     (fset method (eieio-defgeneric-form-primary-only-one
1235                   method doc-string
1236                   (car entry)
1237                   (cdr entry)
1238                   ))))
1239
1240 (defun eieio-defgeneric (method doc-string)
1241   "Engine part to `defgeneric' macro defining METHOD with DOC-STRING."
1242   (if (and (fboundp method) (not (generic-p method))
1243            (or (byte-code-function-p (symbol-function method))
1244                (not (eq 'autoload (car (symbol-function method)))))
1245            )
1246       (error "You cannot create a generic/method over an existing symbol: %s"
1247              method))
1248   ;; Don't do this over and over.
1249   (unless (fboundp 'method)
1250     ;; This defun tells emacs where the first definition of this
1251     ;; method is defined.
1252     `(defun ,method nil)
1253     ;; Make sure the method tables are installed.
1254     (eieiomt-install method)
1255     ;; Apply the actual body of this function.
1256     (fset method (eieio-defgeneric-form method doc-string))
1257     ;; Return the method
1258     'method))
1259
1260 (defun eieio-unbind-method-implementations (method)
1261   "Make the generic method METHOD have no implementations.
1262 It will leave the original generic function in place,
1263 but remove reference to all implementations of METHOD."
1264   (put method 'eieio-method-tree nil)
1265   (put method 'eieio-method-obarray nil))
1266
1267 (defmacro defmethod (method &rest args)
1268   "Create a new METHOD through `defgeneric' with ARGS.
1269
1270 The optional second argument KEY is a specifier that
1271 modifies how the method is called, including:
1272    :before  - Method will be called before the :primary
1273    :primary - The default if not specified
1274    :after   - Method will be called after the :primary
1275    :static  - First arg could be an object or class
1276 The next argument is the ARGLIST.  The ARGLIST specifies the arguments
1277 to the method as with `defun'.  The first argument can have a type
1278 specifier, such as:
1279   ((VARNAME CLASS) ARG2 ...)
1280 where VARNAME is the name of the local variable for the method being
1281 created.  The CLASS is a class symbol for a class made with `defclass'.
1282 A DOCSTRING comes after the ARGLIST, and is optional.
1283 All the rest of the args are the BODY of the method.  A method will
1284 return the value of the last form in the BODY.
1285
1286 Summary:
1287
1288  (defmethod mymethod [:before | :primary | :after | :static]
1289                      ((typearg class-name) arg2 &optional opt &rest rest)
1290     \"doc-string\"
1291      body)"
1292   (let* ((key (if (keywordp (car args)) (pop args)))
1293          (params (car args))
1294          (arg1 (car params))
1295          (class (if (consp arg1) (nth 1 arg1))))
1296     `(eieio--defmethod ',method ',key ',class
1297                        (lambda ,(if (consp arg1)
1298                                (cons (car arg1) (cdr params))
1299                              params)
1300                          ,@(cdr args)))))
1301
1302 (defun eieio--defmethod (method kind argclass code)
1303   "Work part of the `defmethod' macro defining METHOD with ARGS."
1304   (let ((key
1305     ;; find optional keys
1306          (cond ((or (eq ':BEFORE kind)
1307                     (eq ':before kind))
1308                  method-before)
1309                ((or (eq ':AFTER kind)
1310                     (eq ':after kind))
1311                  method-after)
1312                ((or (eq ':PRIMARY kind)
1313                     (eq ':primary kind))
1314                  method-primary)
1315                ((or (eq ':STATIC kind)
1316                     (eq ':static kind))
1317                  method-static)
1318                 ;; Primary key
1319                (t method-primary))))
1320     ;; make sure there is a generic
1321     (eieio-defgeneric
1322      method
1323      (or (documentation code)
1324          (format "Generically created method `%s'." method)))
1325     ;; create symbol for property to bind to.  If the first arg is of
1326     ;; the form (varname vartype) and `vartype' is a class, then
1327     ;; that class will be the type symbol.  If not, then it will fall
1328     ;; under the type `primary' which is a non-specific calling of the
1329     ;; function.
1330     (if argclass
1331           (if (not (class-p argclass))
1332               (error "Unknown class type %s in method parameters"
1333                    argclass))
1334       (if (= key -1)
1335           (signal 'wrong-type-argument (list :static 'non-class-arg)))
1336       ;; generics are higher
1337       (setq key (eieio-specialized-key-to-generic-key key)))
1338     ;; Put this lambda into the symbol so we can find it
1339     (eieiomt-add method code key argclass)
1340     )
1341
1342   (when eieio-optimize-primary-methods-flag
1343     ;; Optimizing step:
1344     ;;
1345     ;; If this method, after this setup, only has primary methods, then
1346     ;; we can setup the generic that way.
1347     (if (generic-primary-only-p method)
1348         ;; If there is only one primary method, then we can go one more
1349         ;; optimization step.
1350         (if (generic-primary-only-one-p method)
1351             (eieio-defgeneric-reset-generic-form-primary-only-one method)
1352           (eieio-defgeneric-reset-generic-form-primary-only method))
1353       (eieio-defgeneric-reset-generic-form method)))
1354
1355   method)
1356
1357 ;;; Slot type validation
1358
1359 ;; This is a hideous hack for replacing `typep' from cl-macs, to avoid
1360 ;; requiring the CL library at run-time.  It can be eliminated if/when
1361 ;; `typep' is merged into Emacs core.
1362 (defun eieio--typep (val type)
1363   (if (symbolp type)
1364       (cond ((get type 'cl-deftype-handler)
1365              (eieio--typep val (funcall (get type 'cl-deftype-handler))))
1366             ((eq type t) t)
1367             ((eq type 'null)   (null val))
1368             ((eq type 'atom)   (atom val))
1369             ((eq type 'float)  (and (numberp val) (not (integerp val))))
1370             ((eq type 'real)   (numberp val))
1371             ((eq type 'fixnum) (integerp val))
1372             ((memq type '(character string-char)) (characterp val))
1373             (t
1374              (let* ((name (symbol-name type))
1375                     (namep (intern (concat name "p"))))
1376                (if (fboundp namep)
1377                    (funcall `(lambda () (,namep val)))
1378                  (funcall `(lambda ()
1379                              (,(intern (concat name "-p")) val)))))))
1380     (cond ((get (car type) 'cl-deftype-handler)
1381            (eieio--typep val (apply (get (car type) 'cl-deftype-handler)
1382                                     (cdr type))))
1383           ((memq (car type) '(integer float real number))
1384            (and (eieio--typep val (car type))
1385                 (or (memq (cadr type) '(* nil))
1386                     (if (consp (cadr type))
1387                         (> val (car (cadr type)))
1388                       (>= val (cadr type))))
1389                 (or (memq (caddr type) '(* nil))
1390                     (if (consp (car (cddr type)))
1391                         (< val (caar (cddr type)))
1392                       (<= val (car (cddr type)))))))
1393           ((memq (car type) '(and or not))
1394            (eval (cons (car type)
1395                        (mapcar (lambda (x)
1396                                  `(eieio--typep (quote ,val) (quote ,x)))
1397                                (cdr type)))))
1398           ((memq (car type) '(member member*))
1399            (memql val (cdr type)))
1400           ((eq (car type) 'satisfies)
1401            (funcall `(lambda () (,(cadr type) val))))
1402           (t (error "Bad type spec: %s" type)))))
1403
1404 (defun eieio-perform-slot-validation (spec value)
1405   "Return non-nil if SPEC does not match VALUE."
1406   (or (eq spec t)                       ; t always passes
1407       (eq value eieio-unbound)          ; unbound always passes
1408       (eieio--typep value spec)))
1409
1410 (defun eieio-validate-slot-value (class slot-idx value slot)
1411   "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
1412 Checks the :type specifier.
1413 SLOT is the slot that is being checked, and is only used when throwing
1414 an error."
1415   (if eieio-skip-typecheck
1416       nil
1417     ;; Trim off object IDX junk added in for the object index.
1418     (setq slot-idx (- slot-idx 3))
1419     (let ((st (aref (aref (class-v class) class-public-type) slot-idx)))
1420       (if (not (eieio-perform-slot-validation st value))
1421           (signal 'invalid-slot-type (list class slot st value))))))
1422
1423 (defun eieio-validate-class-slot-value (class slot-idx value slot)
1424   "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
1425 Checks the :type specifier.
1426 SLOT is the slot that is being checked, and is only used when throwing
1427 an error."
1428   (if eieio-skip-typecheck
1429       nil
1430     (let ((st (aref (aref (class-v class) class-class-allocation-type)
1431                     slot-idx)))
1432       (if (not (eieio-perform-slot-validation st value))
1433           (signal 'invalid-slot-type (list class slot st value))))))
1434
1435 (defun eieio-barf-if-slot-unbound (value instance slotname fn)
1436   "Throw a signal if VALUE is a representation of an UNBOUND slot.
1437 INSTANCE is the object being referenced.  SLOTNAME is the offending
1438 slot.  If the slot is ok, return VALUE.
1439 Argument FN is the function calling this verifier."
1440   (if (and (eq value eieio-unbound) (not eieio-skip-typecheck))
1441       (slot-unbound instance (object-class instance) slotname fn)
1442     value))
1443
1444 ;;; Get/Set slots in an object.
1445 ;;
1446 (defmacro oref (obj slot)
1447   "Retrieve the value stored in OBJ in the slot named by SLOT.
1448 Slot is the name of the slot when created by `defclass' or the label
1449 created by the :initarg tag."
1450   `(eieio-oref ,obj (quote ,slot)))
1451
1452 (defun eieio-oref (obj slot)
1453   "Return the value in OBJ at SLOT in the object vector."
1454   (if (not (or (eieio-object-p obj) (class-p obj)))
1455       (signal 'wrong-type-argument (list '(or eieio-object-p class-p) obj)))
1456   (if (not (symbolp slot))
1457       (signal 'wrong-type-argument (list 'symbolp slot)))
1458   (if (class-p obj) (eieio-class-un-autoload obj))
1459   (let* ((class (if (class-p obj) obj (aref obj object-class)))
1460          (c (eieio-slot-name-index class obj slot)))
1461     (if (not c)
1462         ;; It might be missing because it is a :class allocated slot.
1463         ;; Lets check that info out.
1464         (if (setq c (eieio-class-slot-name-index class slot))
1465             ;; Oref that slot.
1466             (aref (aref (class-v class) class-class-allocation-values) c)
1467           ;; The slot-missing method is a cool way of allowing an object author
1468           ;; to intercept missing slot definitions.  Since it is also the LAST
1469           ;; thing called in this fn, its return value would be retrieved.
1470           (slot-missing obj slot 'oref)
1471           ;;(signal 'invalid-slot-name (list (object-name obj) slot))
1472           )
1473       (if (not (eieio-object-p obj))
1474           (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1475       (eieio-barf-if-slot-unbound (aref obj c) obj slot 'oref))))
1476
1477 (defalias 'slot-value 'eieio-oref)
1478 (defalias 'set-slot-value 'eieio-oset)
1479
1480 (defmacro oref-default (obj slot)
1481   "Get the default value of OBJ (maybe a class) for SLOT.
1482 The default value is the value installed in a class with the :initform
1483 tag.  SLOT can be the slot name, or the tag specified by the :initarg
1484 tag in the `defclass' call."
1485   `(eieio-oref-default ,obj (quote ,slot)))
1486
1487 (defun eieio-oref-default (obj slot)
1488   "Do the work for the macro `oref-default' with similar parameters.
1489 Fills in OBJ's SLOT with its default value."
1490   (if (not (or (eieio-object-p obj) (class-p obj))) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1491   (if (not (symbolp slot)) (signal 'wrong-type-argument (list 'symbolp slot)))
1492   (let* ((cl (if (eieio-object-p obj) (aref obj object-class) obj))
1493          (c (eieio-slot-name-index cl obj slot)))
1494     (if (not c)
1495         ;; It might be missing because it is a :class allocated slot.
1496         ;; Lets check that info out.
1497         (if (setq c
1498                   (eieio-class-slot-name-index cl slot))
1499             ;; Oref that slot.
1500             (aref (aref (class-v cl) class-class-allocation-values)
1501                   c)
1502           (slot-missing obj slot 'oref-default)
1503           ;;(signal 'invalid-slot-name (list (class-name cl) slot))
1504           )
1505       (eieio-barf-if-slot-unbound
1506        (let ((val (nth (- c 3) (aref (class-v cl) class-public-d))))
1507          (eieio-default-eval-maybe val))
1508        obj cl 'oref-default))))
1509
1510 (defsubst eieio-eval-default-p (val)
1511   "Whether the default value VAL should be evaluated for use."
1512   (and (consp val) (symbolp (car val)) (fboundp (car val))))
1513
1514 (defun eieio-default-eval-maybe (val)
1515   "Check VAL, and return what `oref-default' would provide."
1516   (cond
1517    ;; Is it a function call?  If so, evaluate it.
1518    ((eieio-eval-default-p val)
1519     (eval val))
1520    ;;;; check for quoted things, and unquote them
1521    ;;((and (consp val) (eq (car val) 'quote))
1522    ;; (car (cdr val)))
1523    ;; return it verbatim
1524    (t val)))
1525
1526 ;;; Object Set macros
1527 ;;
1528 (defmacro oset (obj slot value)
1529   "Set the value in OBJ for slot SLOT to VALUE.
1530 SLOT is the slot name as specified in `defclass' or the tag created
1531 with in the :initarg slot.  VALUE can be any Lisp object."
1532   `(eieio-oset ,obj (quote ,slot) ,value))
1533
1534 (defun eieio-oset (obj slot value)
1535   "Do the work for the macro `oset'.
1536 Fills in OBJ's SLOT with VALUE."
1537   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1538   (if (not (symbolp slot)) (signal 'wrong-type-argument (list 'symbolp slot)))
1539   (let ((c (eieio-slot-name-index (object-class-fast obj) obj slot)))
1540     (if (not c)
1541         ;; It might be missing because it is a :class allocated slot.
1542         ;; Lets check that info out.
1543         (if (setq c
1544                   (eieio-class-slot-name-index (aref obj object-class) slot))
1545             ;; Oset that slot.
1546             (progn
1547               (eieio-validate-class-slot-value (object-class-fast obj) c value slot)
1548               (aset (aref (class-v (aref obj object-class))
1549                           class-class-allocation-values)
1550                     c value))
1551           ;; See oref for comment on `slot-missing'
1552           (slot-missing obj slot 'oset value)
1553           ;;(signal 'invalid-slot-name (list (object-name obj) slot))
1554           )
1555       (eieio-validate-slot-value (object-class-fast obj) c value slot)
1556       (aset obj c value))))
1557
1558 (defmacro oset-default (class slot value)
1559   "Set the default slot in CLASS for SLOT to VALUE.
1560 The default value is usually set with the :initform tag during class
1561 creation.  This allows users to change the default behavior of classes
1562 after they are created."
1563   `(eieio-oset-default ,class (quote ,slot) ,value))
1564
1565 (defun eieio-oset-default (class slot value)
1566   "Do the work for the macro `oset-default'.
1567 Fills in the default value in CLASS' in SLOT with VALUE."
1568   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1569   (if (not (symbolp slot)) (signal 'wrong-type-argument (list 'symbolp slot)))
1570   (let* ((scoped-class class)
1571          (c (eieio-slot-name-index class nil slot)))
1572     (if (not c)
1573         ;; It might be missing because it is a :class allocated slot.
1574         ;; Lets check that info out.
1575         (if (setq c (eieio-class-slot-name-index class slot))
1576             (progn
1577               ;; Oref that slot.
1578               (eieio-validate-class-slot-value class c value slot)
1579               (aset (aref (class-v class) class-class-allocation-values) c
1580                     value))
1581           (signal 'invalid-slot-name (list (class-name class) slot)))
1582       (eieio-validate-slot-value class c value slot)
1583       ;; Set this into the storage for defaults.
1584       (setcar (nthcdr (- c 3) (aref (class-v class) class-public-d))
1585               value)
1586       ;; Take the value, and put it into our cache object.
1587       (eieio-oset (aref (class-v class) class-default-object-cache)
1588                   slot value)
1589       )))
1590
1591 ;;; Handy CLOS macros
1592 ;;
1593 (defmacro with-slots (spec-list object &rest body)
1594   "Bind SPEC-LIST lexically to slot values in OBJECT, and execute BODY.
1595 This establishes a lexical environment for referring to the slots in
1596 the instance named by the given slot-names as though they were
1597 variables.  Within such a context the value of the slot can be
1598 specified by using its slot name, as if it were a lexically bound
1599 variable.  Both setf and setq can be used to set the value of the
1600 slot.
1601
1602 SPEC-LIST is of a form similar to `let'.  For example:
1603
1604   ((VAR1 SLOT1)
1605     SLOT2
1606     SLOTN
1607    (VARN+1 SLOTN+1))
1608
1609 Where each VAR is the local variable given to the associated
1610 SLOT.  A slot specified without a variable name is given a
1611 variable name of the same name as the slot."
1612   (declare (indent 2))
1613   ;; Transform the spec-list into a symbol-macrolet spec-list.
1614   (let ((mappings (mapcar (lambda (entry)
1615                             (let ((var  (if (listp entry) (car entry) entry))
1616                                   (slot (if (listp entry) (cadr entry) entry)))
1617                               (list var `(slot-value ,object ',slot))))
1618                           spec-list)))
1619     (append (list 'symbol-macrolet mappings)
1620             body)))
1621 \f
1622 ;;; Simple generators, and query functions.  None of these would do
1623 ;;  well embedded into an object.
1624 ;;
1625 (defmacro object-class-fast (obj) "Return the class struct defining OBJ with no check."
1626   `(aref ,obj object-class))
1627
1628 (defun class-name (class) "Return a Lisp like symbol name for CLASS."
1629   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1630   ;; I think this is supposed to return a symbol, but to me CLASS is a symbol,
1631   ;; and I wanted a string.  Arg!
1632   (format "#<class %s>" (symbol-name class)))
1633
1634 (defun object-name (obj &optional extra)
1635   "Return a Lisp like symbol string for object OBJ.
1636 If EXTRA, include that in the string returned to represent the symbol."
1637   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1638   (format "#<%s %s%s>" (symbol-name (object-class-fast obj))
1639           (aref obj object-name) (or extra "")))
1640
1641 (defun object-name-string (obj) "Return a string which is OBJ's name."
1642   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1643   (aref obj object-name))
1644
1645 (defun object-set-name-string (obj name) "Set the string which is OBJ's NAME."
1646   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1647   (if (not (stringp name)) (signal 'wrong-type-argument (list 'stringp name)))
1648   (aset obj object-name name))
1649
1650 (defun object-class (obj) "Return the class struct defining OBJ."
1651   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1652   (object-class-fast obj))
1653 (defalias 'class-of 'object-class)
1654
1655 (defun object-class-name (obj) "Return a Lisp like symbol name for OBJ's class."
1656   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1657   (class-name (object-class-fast obj)))
1658
1659 (defmacro class-parents-fast (class) "Return parent classes to CLASS with no check."
1660   `(aref (class-v ,class) class-parent))
1661
1662 (defun class-parents (class)
1663   "Return parent classes to CLASS.  (overload of variable).
1664
1665 The CLOS function `class-direct-superclasses' is aliased to this function."
1666   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1667   (class-parents-fast class))
1668
1669 (defmacro class-children-fast (class) "Return child classes to CLASS with no check."
1670   `(aref (class-v ,class) class-children))
1671
1672 (defun class-children (class)
1673 "Return child classes to CLASS.
1674
1675 The CLOS function `class-direct-subclasses' is aliased to this function."
1676   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1677   (class-children-fast class))
1678
1679 (defun eieio-c3-candidate (class remaining-inputs)
1680   "Returns CLASS if it can go in the result now, otherwise nil"
1681   ;; Ensure CLASS is not in any position but the first in any of the
1682   ;; element lists of REMAINING-INPUTS.
1683   (and (not (let ((found nil))
1684               (while (and remaining-inputs (not found))
1685                 (setq found (member class (cdr (car remaining-inputs)))
1686                       remaining-inputs (cdr remaining-inputs)))
1687               found))
1688        class))
1689
1690 (defun eieio-c3-merge-lists (reversed-partial-result remaining-inputs)
1691   "Merge REVERSED-PARTIAL-RESULT REMAINING-INPUTS in a consistent order, if possible.
1692 If a consistent order does not exist, signal an error."
1693   (if (let ((tail remaining-inputs)
1694             (found nil))
1695         (while (and tail (not found))
1696           (setq found (car tail) tail (cdr tail)))
1697         (not found))
1698       ;; If all remaining inputs are empty lists, we are done.
1699       (nreverse reversed-partial-result)
1700     ;; Otherwise, we try to find the next element of the result. This
1701     ;; is achieved by considering the first element of each
1702     ;; (non-empty) input list and accepting a candidate if it is
1703     ;; consistent with the rests of the input lists.
1704     (let* ((found nil)
1705            (tail remaining-inputs)
1706            (next (progn
1707                    (while (and tail (not found))
1708                      (setq found (and (car tail)
1709                                       (eieio-c3-candidate (caar tail)
1710                                                           remaining-inputs))
1711                            tail (cdr tail)))
1712                    found)))
1713       (if next
1714           ;; The graph is consistent so far, add NEXT to result and
1715           ;; merge input lists, dropping NEXT from their heads where
1716           ;; applicable.
1717           (eieio-c3-merge-lists
1718            (cons next reversed-partial-result)
1719            (mapcar (lambda (l) (if (eq (first l) next) (rest l) l))
1720                    remaining-inputs))
1721         ;; The graph is inconsistent, give up
1722         (signal 'inconsistent-class-hierarchy (list remaining-inputs))))))
1723
1724 (defun eieio-class-precedence-dfs (class)
1725   "Return all parents of CLASS in depth-first order."
1726   (let* ((parents (class-parents-fast class))
1727          (classes (copy-sequence
1728                    (apply #'append
1729                           (list class)
1730                           (or
1731                            (mapcar
1732                             (lambda (parent)
1733                               (cons parent
1734                                     (eieio-class-precedence-dfs parent)))
1735                             parents)
1736                            '((eieio-default-superclass))))))
1737          (tail classes))
1738     ;; Remove duplicates.
1739     (while tail
1740       (setcdr tail (delq (car tail) (cdr tail)))
1741       (setq tail (cdr tail)))
1742     classes))
1743
1744 (defun eieio-class-precedence-bfs (class)
1745   "Return all parents of CLASS in breadth-first order."
1746   (let ((result)
1747         (queue (or (class-parents-fast class)
1748                    '(eieio-default-superclass))))
1749     (while queue
1750       (let ((head (pop queue)))
1751         (unless (member head result)
1752           (push head result)
1753           (unless (eq head 'eieio-default-superclass)
1754             (setq queue (append queue (or (class-parents-fast head)
1755                                           '(eieio-default-superclass))))))))
1756     (cons class (nreverse result)))
1757   )
1758
1759 (defun eieio-class-precedence-c3 (class)
1760   "Return all parents of CLASS in c3 order."
1761   (let ((parents (class-parents-fast class)))
1762     (eieio-c3-merge-lists
1763      (list class)
1764      (append
1765       (or
1766        (mapcar
1767         (lambda (x)
1768           (eieio-class-precedence-c3 x))
1769         parents)
1770        '((eieio-default-superclass)))
1771       (list parents))))
1772   )
1773
1774 (defun class-precedence-list (class)
1775   "Return (transitively closed) list of parents of CLASS.
1776 The order, in which the parents are returned depends on the
1777 method invocation orders of the involved classes."
1778   (if (or (null class) (eq class 'eieio-default-superclass))
1779       nil
1780     (case (class-method-invocation-order class)
1781       (:depth-first
1782        (eieio-class-precedence-dfs class))
1783       (:breadth-first
1784        (eieio-class-precedence-bfs class))
1785       (:c3
1786        (eieio-class-precedence-c3 class))))
1787   )
1788
1789 ;; Official CLOS functions.
1790 (defalias 'class-direct-superclasses 'class-parents)
1791 (defalias 'class-direct-subclasses 'class-children)
1792
1793 (defmacro class-parent-fast (class) "Return first parent class to CLASS with no check."
1794   `(car (class-parents-fast ,class)))
1795
1796 (defmacro class-parent (class) "Return first parent class to CLASS.  (overload of variable)."
1797   `(car (class-parents ,class)))
1798
1799 (defmacro same-class-fast-p (obj class) "Return t if OBJ is of class-type CLASS with no error checking."
1800   `(eq (aref ,obj object-class) ,class))
1801
1802 (defun same-class-p (obj class) "Return t if OBJ is of class-type CLASS."
1803   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1804   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1805   (same-class-fast-p obj class))
1806
1807 (defun object-of-class-p (obj class)
1808   "Return non-nil if OBJ is an instance of CLASS or CLASS' subclasses."
1809   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1810   ;; class will be checked one layer down
1811   (child-of-class-p (aref obj object-class) class))
1812 ;; Backwards compatibility
1813 (defalias 'obj-of-class-p 'object-of-class-p)
1814
1815 (defun child-of-class-p (child class)
1816   "Return non-nil if CHILD class is a subclass of CLASS."
1817   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1818   (if (not (class-p child)) (signal 'wrong-type-argument (list 'class-p child)))
1819   (let ((p nil))
1820     (while (and child (not (eq child class)))
1821       (setq p (append p (aref (class-v child) class-parent))
1822             child (car p)
1823             p (cdr p)))
1824     (if child t)))
1825
1826 (defun object-slots (obj)
1827   "Return list of slots available in OBJ."
1828   (if (not (eieio-object-p obj)) (signal 'wrong-type-argument (list 'eieio-object-p obj)))
1829   (aref (class-v (object-class-fast obj)) class-public-a))
1830
1831 (defun class-slot-initarg (class slot) "Fetch from CLASS, SLOT's :initarg."
1832   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1833   (let ((ia (aref (class-v class) class-initarg-tuples))
1834         (f nil))
1835     (while (and ia (not f))
1836       (if (eq (cdr (car ia)) slot)
1837           (setq f (car (car ia))))
1838       (setq ia (cdr ia)))
1839     f))
1840
1841 ;;; CLOS queries into classes and slots
1842 ;;
1843 (defun slot-boundp (object slot)
1844   "Return non-nil if OBJECT's SLOT is bound.
1845 Setting a slot's value makes it bound.  Calling `slot-makeunbound' will
1846 make a slot unbound.
1847 OBJECT can be an instance or a class."
1848   ;; Skip typechecking while retrieving this value.
1849   (let ((eieio-skip-typecheck t))
1850     ;; Return nil if the magic symbol is in there.
1851     (not (eq (cond
1852               ((eieio-object-p object) (eieio-oref object slot))
1853               ((class-p object)        (eieio-oref-default object slot))
1854               (t (signal 'wrong-type-argument (list 'eieio-object-p object))))
1855              eieio-unbound))))
1856
1857 (defun slot-makeunbound (object slot)
1858   "In OBJECT, make SLOT unbound."
1859   (eieio-oset object slot eieio-unbound))
1860
1861 (defun slot-exists-p (object-or-class slot)
1862   "Return non-nil if OBJECT-OR-CLASS has SLOT."
1863   (let ((cv (class-v (cond ((eieio-object-p object-or-class)
1864                             (object-class object-or-class))
1865                            ((class-p object-or-class)
1866                             object-or-class))
1867                      )))
1868     (or (memq slot (aref cv class-public-a))
1869         (memq slot (aref cv class-class-allocation-a)))
1870     ))
1871
1872 (defun find-class (symbol &optional errorp)
1873   "Return the class that SYMBOL represents.
1874 If there is no class, nil is returned if ERRORP is nil.
1875 If ERRORP is non-nil, `wrong-argument-type' is signaled."
1876   (if (not (class-p symbol))
1877       (if errorp (signal 'wrong-type-argument (list 'class-p symbol))
1878         nil)
1879     (class-v symbol)))
1880
1881 ;;; Slightly more complex utility functions for objects
1882 ;;
1883 (defun object-assoc (key slot list)
1884   "Return an object if KEY is `equal' to SLOT's value of an object in LIST.
1885 LIST is a list of objects whose slots are searched.
1886 Objects in LIST do not need to have a slot named SLOT, nor does
1887 SLOT need to be bound.  If these errors occur, those objects will
1888 be ignored."
1889   (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
1890   (while (and list (not (condition-case nil
1891                             ;; This prevents errors for missing slots.
1892                             (equal key (eieio-oref (car list) slot))
1893                           (error nil))))
1894     (setq list (cdr list)))
1895   (car list))
1896
1897 (defun object-assoc-list (slot list)
1898   "Return an association list with the contents of SLOT as the key element.
1899 LIST must be a list of objects with SLOT in it.
1900 This is useful when you need to do completing read on an object group."
1901   (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
1902   (let ((assoclist nil))
1903     (while list
1904       (setq assoclist (cons (cons (eieio-oref (car list) slot)
1905                                   (car list))
1906                             assoclist))
1907       (setq list (cdr list)))
1908     (nreverse assoclist)))
1909
1910 (defun object-assoc-list-safe (slot list)
1911   "Return an association list with the contents of SLOT as the key element.
1912 LIST must be a list of objects, but those objects do not need to have
1913 SLOT in it.  If it does not, then that element is left out of the association
1914 list."
1915   (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
1916   (let ((assoclist nil))
1917     (while list
1918       (if (slot-exists-p (car list) slot)
1919           (setq assoclist (cons (cons (eieio-oref (car list) slot)
1920                                       (car list))
1921                                 assoclist)))
1922       (setq list (cdr list)))
1923     (nreverse assoclist)))
1924
1925 (defun object-add-to-list (object slot item &optional append)
1926   "In OBJECT's SLOT, add ITEM to the list of elements.
1927 Optional argument APPEND indicates we need to append to the list.
1928 If ITEM already exists in the list in SLOT, then it is not added.
1929 Comparison is done with `equal' through the `member' function call.
1930 If SLOT is unbound, bind it to the list containing ITEM."
1931   (let (ov)
1932     ;; Find the originating list.
1933     (if (not (slot-boundp object slot))
1934         (setq ov (list item))
1935       (setq ov (eieio-oref object slot))
1936       ;; turn it into a list.
1937       (unless (listp ov)
1938         (setq ov (list ov)))
1939       ;; Do the combination
1940       (if (not (member item ov))
1941           (setq ov
1942                 (if append
1943                     (append ov (list item))
1944                   (cons item ov)))))
1945     ;; Set back into the slot.
1946     (eieio-oset object slot ov)))
1947
1948 (defun object-remove-from-list (object slot item)
1949   "In OBJECT's SLOT, remove occurrences of ITEM.
1950 Deletion is done with `delete', which deletes by side effect,
1951 and comparisons are done with `equal'.
1952 If SLOT is unbound, do nothing."
1953   (if (not (slot-boundp object slot))
1954       nil
1955     (eieio-oset object slot (delete item (eieio-oref object slot)))))
1956 \f
1957 ;;; EIEIO internal search functions
1958 ;;
1959 (defun eieio-slot-originating-class-p (start-class slot)
1960   "Return non-nil if START-CLASS is the first class to define SLOT.
1961 This is for testing if `scoped-class' is the class that defines SLOT
1962 so that we can protect private slots."
1963   (let ((par (class-parents start-class))
1964         (ret t))
1965     (if (not par)
1966         t
1967       (while (and par ret)
1968         (if (intern-soft (symbol-name slot)
1969                          (aref (class-v (car par))
1970                                class-symbol-obarray))
1971             (setq ret nil))
1972         (setq par (cdr par)))
1973       ret)))
1974
1975 (defun eieio-slot-name-index (class obj slot)
1976   "In CLASS for OBJ find the index of the named SLOT.
1977 The slot is a symbol which is installed in CLASS by the `defclass'
1978 call.  OBJ can be nil, but if it is an object, and the slot in question
1979 is protected, access will be allowed if OBJ is a child of the currently
1980 `scoped-class'.
1981 If SLOT is the value created with :initarg instead,
1982 reverse-lookup that name, and recurse with the associated slot value."
1983   ;; Removed checks to outside this call
1984   (let* ((fsym (intern-soft (symbol-name slot)
1985                             (aref (class-v class)
1986                                   class-symbol-obarray)))
1987          (fsi (if (symbolp fsym) (symbol-value fsym) nil)))
1988     (if (integerp fsi)
1989         (cond
1990          ((not (get fsym 'protection))
1991           (+ 3 fsi))
1992          ((and (eq (get fsym 'protection) 'protected)
1993                scoped-class
1994                (or (child-of-class-p class scoped-class)
1995                    (and (eieio-object-p obj)
1996                         (child-of-class-p class (object-class obj)))))
1997           (+ 3 fsi))
1998          ((and (eq (get fsym 'protection) 'private)
1999                (or (and scoped-class
2000                         (eieio-slot-originating-class-p scoped-class slot))
2001                    eieio-initializing-object))
2002           (+ 3 fsi))
2003          (t nil))
2004       (let ((fn (eieio-initarg-to-attribute class slot)))
2005         (if fn (eieio-slot-name-index class obj fn) nil)))))
2006
2007 (defun eieio-class-slot-name-index (class slot)
2008   "In CLASS find the index of the named SLOT.
2009 The slot is a symbol which is installed in CLASS by the `defclass'
2010 call.  If SLOT is the value created with :initarg instead,
2011 reverse-lookup that name, and recurse with the associated slot value."
2012   ;; This will happen less often, and with fewer slots.  Do this the
2013   ;; storage cheap way.
2014   (let* ((a (aref (class-v class) class-class-allocation-a))
2015          (l1 (length a))
2016          (af (memq slot a))
2017          (l2 (length af)))
2018     ;; Slot # is length of the total list, minus the remaining list of
2019     ;; the found slot.
2020     (if af (- l1 l2))))
2021 \f
2022 ;;; CLOS generics internal function handling
2023 ;;
2024 (defvar eieio-generic-call-methodname nil
2025   "When using `call-next-method', provides a context on how to do it.")
2026 (defvar eieio-generic-call-arglst nil
2027   "When using `call-next-method', provides a context for parameters.")
2028 (defvar eieio-generic-call-key nil
2029   "When using `call-next-method', provides a context for the current key.
2030 Keys are a number representing :before, :primary, and :after methods.")
2031 (defvar eieio-generic-call-next-method-list nil
2032   "When executing a PRIMARY or STATIC method, track the 'next-method'.
2033 During executions, the list is first generated, then as each next method
2034 is called, the next method is popped off the stack.")
2035
2036 (defvar eieio-pre-method-execution-hooks nil
2037   "*Hooks run just before a method is executed.
2038 The hook function must accept one argument, the list of forms
2039 about to be executed.")
2040
2041 (defun eieio-generic-call (method args)
2042   "Call METHOD with ARGS.
2043 ARGS provides the context on which implementation to use.
2044 This should only be called from a generic function."
2045   ;; We must expand our arguments first as they are always
2046   ;; passed in as quoted symbols
2047   (let ((newargs nil) (mclass nil)  (lambdas nil) (tlambdas nil) (keys nil)
2048         (eieio-generic-call-methodname method)
2049         (eieio-generic-call-arglst args)
2050         (firstarg nil)
2051         (primarymethodlist nil))
2052     ;; get a copy
2053     (setq newargs args
2054           firstarg (car newargs))
2055     ;; Is the class passed in autoloaded?
2056     ;; Since class names are also constructors, they can be autoloaded
2057     ;; via the autoload command.  Check for this, and load them in.
2058     ;; It's ok if it doesn't turn out to be a class.  Probably want that
2059     ;; function loaded anyway.
2060     (if (and (symbolp firstarg)
2061              (fboundp firstarg)
2062              (listp (symbol-function firstarg))
2063              (eq 'autoload (car (symbol-function firstarg))))
2064         (load (nth 1 (symbol-function firstarg))))
2065     ;; Determine the class to use.
2066     (cond ((eieio-object-p firstarg)
2067            (setq mclass (object-class-fast firstarg)))
2068           ((class-p firstarg)
2069            (setq mclass firstarg))
2070           )
2071     ;; Make sure the class is a valid class
2072     ;; mclass can be nil (meaning a generic for should be used.
2073     ;; mclass cannot have a value that is not a class, however.
2074     (when (and (not (null mclass)) (not (class-p mclass)))
2075       (error "Cannot dispatch method %S on class %S"
2076              method mclass)
2077       )
2078     ;; Now create a list in reverse order of all the calls we have
2079     ;; make in order to successfully do this right.  Rules:
2080     ;; 1) Only call generics if scoped-class is not defined
2081     ;;    This prevents multiple calls in the case of recursion
2082     ;; 2) Only call static if this is a static method.
2083     ;; 3) Only call specifics if the definition allows for them.
2084     ;; 4) Call in order based on :before, :primary, and :after
2085     (when (eieio-object-p firstarg)
2086       ;; Non-static calls do all this stuff.
2087
2088       ;; :after methods
2089       (setq tlambdas
2090             (if mclass
2091                 (eieiomt-method-list method method-after mclass)
2092               (list (eieio-generic-form method method-after nil)))
2093             ;;(or (and mclass (eieio-generic-form method method-after mclass))
2094             ;;  (eieio-generic-form method method-after nil))
2095             )
2096       (setq lambdas (append tlambdas lambdas)
2097             keys (append (make-list (length tlambdas) method-after) keys))
2098
2099       ;; :primary methods
2100       (setq tlambdas
2101             (or (and mclass (eieio-generic-form method method-primary mclass))
2102                 (eieio-generic-form method method-primary nil)))
2103       (when tlambdas
2104         (setq lambdas (cons tlambdas lambdas)
2105               keys (cons method-primary keys)
2106               primarymethodlist
2107               (eieiomt-method-list method method-primary mclass)))
2108
2109       ;; :before methods
2110       (setq tlambdas
2111             (if mclass
2112                 (eieiomt-method-list method method-before mclass)
2113               (list (eieio-generic-form method method-before nil)))
2114             ;;(or (and mclass (eieio-generic-form method method-before mclass))
2115             ;;  (eieio-generic-form method method-before nil))
2116             )
2117       (setq lambdas (append tlambdas lambdas)
2118             keys (append (make-list (length tlambdas) method-before) keys))
2119       )
2120
2121     (if mclass
2122         ;; For the case of a class,
2123         ;; if there were no methods found, then there could be :static methods.
2124         (when (not lambdas)
2125           (setq tlambdas
2126                 (eieio-generic-form method method-static mclass))
2127           (setq lambdas (cons tlambdas lambdas)
2128                 keys (cons method-static keys)
2129                 primarymethodlist  ;; Re-use even with bad name here
2130                 (eieiomt-method-list method method-static mclass)))
2131       ;; For the case of no class (ie - mclass == nil) then there may
2132       ;; be a primary method.
2133       (setq tlambdas
2134             (eieio-generic-form method method-primary nil))
2135       (when tlambdas
2136         (setq lambdas (cons tlambdas lambdas)
2137               keys (cons method-primary keys)
2138               primarymethodlist
2139               (eieiomt-method-list method method-primary nil)))
2140       )
2141
2142     (run-hook-with-args 'eieio-pre-method-execution-hooks
2143                         primarymethodlist)
2144
2145     ;; Now loop through all occurrences forms which we must execute
2146     ;; (which are happily sorted now) and execute them all!
2147     (let ((rval nil) (lastval nil) (rvalever nil) (found nil))
2148       (while lambdas
2149         (if (car lambdas)
2150             (let* ((scoped-class (cdr (car lambdas)))
2151                    (eieio-generic-call-key (car keys))
2152                    (has-return-val
2153                     (or (= eieio-generic-call-key method-primary)
2154                         (= eieio-generic-call-key method-static)))
2155                    (eieio-generic-call-next-method-list
2156                     ;; Use the cdr, as the first element is the fcn
2157                     ;; we are calling right now.
2158                     (when has-return-val (cdr primarymethodlist)))
2159                    )
2160               (setq found t)
2161               ;;(setq rval (apply (car (car lambdas)) newargs))
2162               (setq lastval (apply (car (car lambdas)) newargs))
2163               (when has-return-val
2164                 (setq rval lastval
2165                       rvalever t))
2166               ))
2167         (setq lambdas (cdr lambdas)
2168               keys (cdr keys)))
2169       (if (not found)
2170           (if (eieio-object-p (car args))
2171               (setq rval (apply 'no-applicable-method (car args) method args)
2172                     rvalever t)
2173             (signal
2174              'no-method-definition
2175              (list method args))))
2176       ;; Right Here... it could be that lastval is returned when
2177       ;; rvalever is nil.  Is that right?
2178       rval)))
2179
2180 (defun eieio-generic-call-primary-only (method args)
2181   "Call METHOD with ARGS for methods with only :PRIMARY implementations.
2182 ARGS provides the context on which implementation to use.
2183 This should only be called from a generic function.
2184
2185 This method is like `eieio-generic-call', but only
2186 implementations in the :PRIMARY slot are queried.  After many
2187 years of use, it appears that over 90% of methods in use
2188 have :PRIMARY implementations only.  We can therefore optimize
2189 for this common case to improve performance."
2190   ;; We must expand our arguments first as they are always
2191   ;; passed in as quoted symbols
2192   (let ((newargs nil) (mclass nil)  (lambdas nil)
2193         (eieio-generic-call-methodname method)
2194         (eieio-generic-call-arglst args)
2195         (firstarg nil)
2196         (primarymethodlist nil)
2197         )
2198     ;; get a copy
2199     (setq newargs args
2200           firstarg (car newargs))
2201
2202     ;; Determine the class to use.
2203     (cond ((eieio-object-p firstarg)
2204            (setq mclass (object-class-fast firstarg)))
2205           ((not firstarg)
2206            (error "Method %s called on nil" method))
2207           ((not (eieio-object-p firstarg))
2208            (error "Primary-only method %s called on something not an object" method))
2209           (t
2210            (error "EIEIO Error: Improperly classified method %s as primary only"
2211                   method)
2212           ))
2213     ;; Make sure the class is a valid class
2214     ;; mclass can be nil (meaning a generic for should be used.
2215     ;; mclass cannot have a value that is not a class, however.
2216     (when (null mclass)
2217       (error "Cannot dispatch method %S on class %S" method mclass)
2218       )
2219
2220     ;; :primary methods
2221     (setq lambdas (eieio-generic-form method method-primary mclass))
2222     (setq primarymethodlist  ;; Re-use even with bad name here
2223           (eieiomt-method-list method method-primary mclass))
2224
2225     ;; Now loop through all occurrences forms which we must execute
2226     ;; (which are happily sorted now) and execute them all!
2227     (let* ((rval nil) (lastval nil) (rvalever nil)
2228            (scoped-class (cdr lambdas))
2229            (eieio-generic-call-key method-primary)
2230            ;; Use the cdr, as the first element is the fcn
2231            ;; we are calling right now.
2232            (eieio-generic-call-next-method-list (cdr primarymethodlist))
2233            )
2234
2235       (if (or (not lambdas) (not (car lambdas)))
2236
2237           ;; No methods found for this impl...
2238           (if (eieio-object-p (car args))
2239               (setq rval (apply 'no-applicable-method (car args) method args)
2240                     rvalever t)
2241             (signal
2242              'no-method-definition
2243              (list method args)))
2244
2245         ;; Do the regular implementation here.
2246
2247         (run-hook-with-args 'eieio-pre-method-execution-hooks
2248                             lambdas)
2249
2250         (setq lastval (apply (car lambdas) newargs))
2251         (setq rval lastval
2252               rvalever t)
2253         )
2254
2255       ;; Right Here... it could be that lastval is returned when
2256       ;; rvalever is nil.  Is that right?
2257       rval)))
2258
2259 (defun eieiomt-method-list (method key class)
2260   "Return an alist list of methods lambdas.
2261 METHOD is the method name.
2262 KEY represents either :before, or :after methods.
2263 CLASS is the starting class to search from in the method tree.
2264 If CLASS is nil, then an empty list of methods should be returned."
2265   ;; Note: eieiomt - the MT means MethodTree.  See more comments below
2266   ;; for the rest of the eieiomt methods.
2267
2268   ;; Collect lambda expressions stored for the class and its parent
2269   ;; classes.
2270   (let (lambdas)
2271     (dolist (ancestor (class-precedence-list class))
2272       ;; Lookup the form to use for the PRIMARY object for the next level
2273       (let ((tmpl (eieio-generic-form method key ancestor)))
2274         (when (and tmpl
2275                    (or (not lambdas)
2276                        ;; This prevents duplicates coming out of the
2277                        ;; class method optimizer.  Perhaps we should
2278                        ;; just not optimize before/afters?
2279                        (not (member tmpl lambdas))))
2280           (push tmpl lambdas))))
2281
2282     ;; Return collected lambda. For :after methods, return in current
2283     ;; order (most general class last); Otherwise, reverse order.
2284     (if (eq key method-after)
2285         lambdas
2286       (nreverse lambdas))))
2287
2288 (defun next-method-p ()
2289   "Return non-nil if there is a next method.
2290 Returns a list of lambda expressions which is the `next-method'
2291 order."
2292   eieio-generic-call-next-method-list)
2293
2294 (defun call-next-method (&rest replacement-args)
2295   "Call the superclass method from a subclass method.
2296 The superclass method is specified in the current method list,
2297 and is called the next method.
2298
2299 If REPLACEMENT-ARGS is non-nil, then use them instead of
2300 `eieio-generic-call-arglst'.  The generic arg list are the
2301 arguments passed in at the top level.
2302
2303 Use `next-method-p' to find out if there is a next method to call."
2304   (if (not scoped-class)
2305       (error "`call-next-method' not called within a class specific method"))
2306   (if (and (/= eieio-generic-call-key method-primary)
2307            (/= eieio-generic-call-key method-static))
2308       (error "Cannot `call-next-method' except in :primary or :static methods")
2309     )
2310   (let ((newargs (or replacement-args eieio-generic-call-arglst))
2311         (next (car eieio-generic-call-next-method-list))
2312         )
2313     (if (or (not next) (not (car next)))
2314         (apply 'no-next-method (car newargs) (cdr newargs))
2315       (let* ((eieio-generic-call-next-method-list
2316               (cdr eieio-generic-call-next-method-list))
2317              (eieio-generic-call-arglst newargs)
2318              (scoped-class (cdr next))
2319              (fcn (car next))
2320              )
2321         (apply fcn newargs)
2322         ))))
2323 \f
2324 ;;;
2325 ;; eieio-method-tree : eieiomt-
2326 ;;
2327 ;; Stored as eieio-method-tree in property list of a generic method
2328 ;;
2329 ;; (eieio-method-tree . [BEFORE PRIMARY AFTER
2330 ;;                       genericBEFORE genericPRIMARY genericAFTER])
2331 ;; and
2332 ;; (eieio-method-obarray . [BEFORE PRIMARY AFTER
2333 ;;                          genericBEFORE genericPRIMARY genericAFTER])
2334 ;;    where the association is a vector.
2335 ;;    (aref 0  -- all static methods.
2336 ;;    (aref 1  -- all methods classified as :before
2337 ;;    (aref 2  -- all methods classified as :primary
2338 ;;    (aref 3  -- all methods classified as :after
2339 ;;    (aref 4  -- a generic classified as :before
2340 ;;    (aref 5  -- a generic classified as :primary
2341 ;;    (aref 6  -- a generic classified as :after
2342 ;;
2343 (defvar eieiomt-optimizing-obarray nil
2344   "While mapping atoms, this contain the obarray being optimized.")
2345
2346 (defun eieiomt-install (method-name)
2347   "Install the method tree, and obarray onto METHOD-NAME.
2348 Do not do the work if they already exist."
2349   (let ((emtv (get method-name 'eieio-method-tree))
2350         (emto (get method-name 'eieio-method-obarray)))
2351     (if (or (not emtv) (not emto))
2352         (progn
2353           (setq emtv (put method-name 'eieio-method-tree
2354                           (make-vector method-num-slots nil))
2355                 emto (put method-name 'eieio-method-obarray
2356                           (make-vector method-num-slots nil)))
2357           (aset emto 0 (make-vector 11 0))
2358           (aset emto 1 (make-vector 11 0))
2359           (aset emto 2 (make-vector 41 0))
2360           (aset emto 3 (make-vector 11 0))
2361           ))))
2362
2363 (defun eieiomt-add (method-name method key class)
2364   "Add to METHOD-NAME the forms METHOD in a call position KEY for CLASS.
2365 METHOD-NAME is the name created by a call to `defgeneric'.
2366 METHOD are the forms for a given implementation.
2367 KEY is an integer (see comment in eieio.el near this function) which
2368 is associated with the :static :before :primary and :after tags.
2369 It also indicates if CLASS is defined or not.
2370 CLASS is the class this method is associated with."
2371   (if (or (> key method-num-slots) (< key 0))
2372       (error "eieiomt-add: method key error!"))
2373   (let ((emtv (get method-name 'eieio-method-tree))
2374         (emto (get method-name 'eieio-method-obarray)))
2375     ;; Make sure the method tables are available.
2376     (if (or (not emtv) (not emto))
2377         (error "Programmer error: eieiomt-add"))
2378     ;; only add new cells on if it doesn't already exist!
2379     (if (assq class (aref emtv key))
2380         (setcdr (assq class (aref emtv key)) method)
2381       (aset emtv key (cons (cons class method) (aref emtv key))))
2382     ;; Add function definition into newly created symbol, and store
2383     ;; said symbol in the correct obarray, otherwise use the
2384     ;; other array to keep this stuff
2385     (if (< key method-num-lists)
2386         (let ((nsym (intern (symbol-name class) (aref emto key))))
2387           (fset nsym method)))
2388     ;; Now optimize the entire obarray
2389     (if (< key method-num-lists)
2390         (let ((eieiomt-optimizing-obarray (aref emto key)))
2391           ;; @todo - Is this overkill?  Should we just clear the symbol?
2392           (mapatoms 'eieiomt-sym-optimize eieiomt-optimizing-obarray)))
2393     ))
2394
2395 (defun eieiomt-next (class)
2396   "Return the next parent class for CLASS.
2397 If CLASS is a superclass, return variable `eieio-default-superclass'.
2398 If CLASS is variable `eieio-default-superclass' then return nil.
2399 This is different from function `class-parent' as class parent returns
2400 nil for superclasses.  This function performs no type checking!"
2401   ;; No type-checking because all calls are made from functions which
2402   ;; are safe and do checking for us.
2403   (or (class-parents-fast class)
2404       (if (eq class 'eieio-default-superclass)
2405           nil
2406         '(eieio-default-superclass))))
2407
2408 (defun eieiomt-sym-optimize (s)
2409   "Find the next class above S which has a function body for the optimizer."
2410   ;; Set the value to nil in case there is no nearest cell.
2411   (set s nil)
2412   ;; Find the nearest cell that has a function body. If we find one,
2413   ;; we replace the nil from above.
2414   (let ((external-symbol (intern-soft (symbol-name s))))
2415     (catch 'done
2416       (dolist (ancestor (rest (class-precedence-list external-symbol)))
2417         (let ((ov (intern-soft (symbol-name ancestor)
2418                                eieiomt-optimizing-obarray)))
2419           (when (fboundp ov)
2420             (set s ov) ;; store ov as our next symbol
2421             (throw 'done ancestor)))))))
2422
2423 (defun eieio-generic-form (method key class)
2424  "Return the lambda form belonging to METHOD using KEY based upon CLASS.
2425 If CLASS is not a class then use `generic' instead.  If class has
2426 no form, but has a parent class, then trace to that parent class.
2427 The first time a form is requested from a symbol, an optimized path
2428 is memorized for faster future use."
2429  (let ((emto (aref (get method 'eieio-method-obarray)
2430                    (if class key (eieio-specialized-key-to-generic-key key)))))
2431    (if (class-p class)
2432        ;; 1) find our symbol
2433        (let ((cs (intern-soft (symbol-name class) emto)))
2434          (if (not cs)
2435              ;; 2) If there isn't one, then make one.
2436              ;;    This can be slow since it only occurs once
2437              (progn
2438                (setq cs (intern (symbol-name class) emto))
2439                ;; 2.1) Cache its nearest neighbor with a quick optimize
2440                ;;      which should only occur once for this call ever
2441                (let ((eieiomt-optimizing-obarray emto))
2442                  (eieiomt-sym-optimize cs))))
2443          ;; 3) If it's bound return this one.
2444          (if (fboundp  cs)
2445              (cons cs (aref (class-v class) class-symbol))
2446            ;; 4) If it's not bound then this variable knows something
2447            (if (symbol-value cs)
2448                (progn
2449                  ;; 4.1) This symbol holds the next class in its value
2450                  (setq class (symbol-value cs)
2451                        cs (intern-soft (symbol-name class) emto))
2452                  ;; 4.2) The optimizer should always have chosen a
2453                  ;;      function-symbol
2454                  ;;(if (fboundp cs)
2455                  (cons cs (aref (class-v (intern (symbol-name class)))
2456                                 class-symbol))
2457                    ;;(error "EIEIO optimizer: erratic data loss!"))
2458                  )
2459                ;; There never will be a funcall...
2460                nil)))
2461      ;; for a generic call, what is a list, is the function body we want.
2462      (let ((emtl (aref (get method 'eieio-method-tree)
2463                        (if class key (eieio-specialized-key-to-generic-key key)))))
2464        (if emtl
2465            ;; The car of EMTL is supposed to be a class, which in this
2466            ;; case is nil, so skip it.
2467            (cons (cdr (car emtl)) nil)
2468          nil)))))
2469
2470 ;;;
2471 ;; Way to assign slots based on a list.  Used for constructors, or
2472 ;; even resetting an object at run-time
2473 ;;
2474 (defun eieio-set-defaults (obj &optional set-all)
2475   "Take object OBJ, and reset all slots to their defaults.
2476 If SET-ALL is non-nil, then when a default is nil, that value is
2477 reset.  If SET-ALL is nil, the slots are only reset if the default is
2478 not nil."
2479   (let ((scoped-class (aref obj object-class))
2480         (eieio-initializing-object t)
2481         (pub (aref (class-v (aref obj object-class)) class-public-a)))
2482     (while pub
2483       (let ((df (eieio-oref-default obj (car pub))))
2484         (if (or df set-all)
2485             (eieio-oset obj (car pub) df)))
2486       (setq pub (cdr pub)))))
2487
2488 (defun eieio-initarg-to-attribute (class initarg)
2489   "For CLASS, convert INITARG to the actual attribute name.
2490 If there is no translation, pass it in directly (so we can cheat if
2491 need be... May remove that later...)"
2492   (let ((tuple (assoc initarg (aref (class-v class) class-initarg-tuples))))
2493     (if tuple
2494         (cdr tuple)
2495       nil)))
2496
2497 (defun eieio-attribute-to-initarg (class attribute)
2498   "In CLASS, convert the ATTRIBUTE into the corresponding init argument tag.
2499 This is usually a symbol that starts with `:'."
2500   (let ((tuple (rassoc attribute (aref (class-v class) class-initarg-tuples))))
2501     (if tuple
2502         (car tuple)
2503       nil)))
2504
2505 \f
2506 ;;; Here are some special types of errors
2507 ;;
2508 (intern "no-method-definition")
2509 (put 'no-method-definition 'error-conditions '(no-method-definition error))
2510 (put 'no-method-definition 'error-message "No method definition")
2511
2512 (intern "no-next-method")
2513 (put 'no-next-method 'error-conditions '(no-next-method error))
2514 (put 'no-next-method 'error-message "No next method")
2515
2516 (intern "invalid-slot-name")
2517 (put 'invalid-slot-name 'error-conditions '(invalid-slot-name error))
2518 (put 'invalid-slot-name 'error-message "Invalid slot name")
2519
2520 (intern "invalid-slot-type")
2521 (put 'invalid-slot-type 'error-conditions '(invalid-slot-type error nil))
2522 (put 'invalid-slot-type 'error-message "Invalid slot type")
2523
2524 (intern "unbound-slot")
2525 (put 'unbound-slot 'error-conditions '(unbound-slot error nil))
2526 (put 'unbound-slot 'error-message "Unbound slot")
2527
2528 (intern "inconsistent-class-hierarchy")
2529 (put 'inconsistent-class-hierarchy 'error-conditions
2530      '(inconsistent-class-hierarchy error nil))
2531 (put 'inconsistent-class-hierarchy 'error-message "Inconsistent class hierarchy")
2532
2533 ;;; Here are some CLOS items that need the CL package
2534 ;;
2535
2536 (defsetf slot-value (obj slot) (store) (list 'eieio-oset obj slot store))
2537 (defsetf eieio-oref (obj slot) (store) (list 'eieio-oset obj slot store))
2538
2539 ;; The below setf method was written by Arnd Kohrs <kohrs@acm.org>
2540 (define-setf-method oref (obj slot)
2541   (with-no-warnings
2542     (require 'cl)
2543     (let ((obj-temp (gensym))
2544           (slot-temp (gensym))
2545           (store-temp (gensym)))
2546       (list (list obj-temp slot-temp)
2547             (list obj `(quote ,slot))
2548             (list store-temp)
2549             (list 'set-slot-value obj-temp slot-temp
2550                   store-temp)
2551             (list 'slot-value obj-temp slot-temp)))))
2552
2553 \f
2554 ;;;
2555 ;; We want all objects created by EIEIO to have some default set of
2556 ;; behaviours so we can create object utilities, and allow various
2557 ;; types of error checking.  To do this, create the default EIEIO
2558 ;; class, and when no parent class is specified, use this as the
2559 ;; default.  (But don't store it in the other classes as the default,
2560 ;; allowing for transparent support.)
2561 ;;
2562
2563 (defclass eieio-default-superclass nil
2564   nil
2565   "Default parent class for classes with no specified parent class.
2566 Its slots are automatically adopted by classes with no specified parents.
2567 This class is not stored in the `parent' slot of a class vector."
2568   :abstract t)
2569
2570 (defalias 'standard-class 'eieio-default-superclass)
2571
2572 (defgeneric constructor (class newname &rest slots)
2573   "Default constructor for CLASS `eieio-default-superclass'.")
2574
2575 (defmethod constructor :static
2576   ((class eieio-default-superclass) newname &rest slots)
2577   "Default constructor for CLASS `eieio-default-superclass'.
2578 NEWNAME is the name to be given to the constructed object.
2579 SLOTS are the initialization slots used by `shared-initialize'.
2580 This static method is called when an object is constructed.
2581 It allocates the vector used to represent an EIEIO object, and then
2582 calls `shared-initialize' on that object."
2583   (let* ((new-object (copy-sequence (aref (class-v class)
2584                                           class-default-object-cache))))
2585     ;; Update the name for the newly created object.
2586     (aset new-object object-name newname)
2587     ;; Call the initialize method on the new object with the slots
2588     ;; that were passed down to us.
2589     (initialize-instance new-object slots)
2590     ;; Return the created object.
2591     new-object))
2592
2593 (defgeneric shared-initialize (obj slots)
2594   "Set slots of OBJ with SLOTS which is a list of name/value pairs.
2595 Called from the constructor routine.")
2596
2597 (defmethod shared-initialize ((obj eieio-default-superclass) slots)
2598   "Set slots of OBJ with SLOTS which is a list of name/value pairs.
2599 Called from the constructor routine."
2600   (let ((scoped-class (aref obj object-class)))
2601     (while slots
2602       (let ((rn (eieio-initarg-to-attribute (object-class-fast obj)
2603                                             (car slots))))
2604         (if (not rn)
2605             (slot-missing obj (car slots) 'oset (car (cdr slots)))
2606           (eieio-oset obj rn (car (cdr slots)))))
2607       (setq slots (cdr (cdr slots))))))
2608
2609 (defgeneric initialize-instance (this &optional slots)
2610   "Construct the new object THIS based on SLOTS.")
2611
2612 (defmethod initialize-instance ((this eieio-default-superclass)
2613                                 &optional slots)
2614   "Construct the new object THIS based on SLOTS.
2615 SLOTS is a tagged list where odd numbered elements are tags, and
2616 even numbered elements are the values to store in the tagged slot.
2617 If you overload the `initialize-instance', there you will need to
2618 call `shared-initialize' yourself, or you can call `call-next-method'
2619 to have this constructor called automatically.  If these steps are
2620 not taken, then new objects of your class will not have their values
2621 dynamically set from SLOTS."
2622     ;; First, see if any of our defaults are `lambda', and
2623     ;; re-evaluate them and apply the value to our slots.
2624     (let* ((scoped-class (class-v (aref this object-class)))
2625            (slot (aref scoped-class class-public-a))
2626            (defaults (aref scoped-class class-public-d)))
2627       (while slot
2628         ;; For each slot, see if we need to evaluate it.
2629         ;;
2630         ;; Paul Landes said in an email:
2631         ;; > CL evaluates it if it can, and otherwise, leaves it as
2632         ;; > the quoted thing as you already have.  This is by the
2633         ;; > Sonya E. Keene book and other things I've look at on the
2634         ;; > web.
2635         (let ((dflt (eieio-default-eval-maybe (car defaults))))
2636           (when (not (eq dflt (car defaults)))
2637             (eieio-oset this (car slot) dflt) ))
2638         ;; Next.
2639         (setq slot (cdr slot)
2640               defaults (cdr defaults))))
2641     ;; Shared initialize will parse our slots for us.
2642     (shared-initialize this slots))
2643
2644 (defgeneric slot-missing (object slot-name operation &optional new-value)
2645   "Method invoked when an attempt to access a slot in OBJECT fails.")
2646
2647 (defmethod slot-missing ((object eieio-default-superclass) slot-name
2648                          operation &optional new-value)
2649   "Method invoked when an attempt to access a slot in OBJECT fails.
2650 SLOT-NAME is the name of the failed slot, OPERATION is the type of access
2651 that was requested, and optional NEW-VALUE is the value that was desired
2652 to be set.
2653
2654 This method is called from `oref', `oset', and other functions which
2655 directly reference slots in EIEIO objects."
2656   (signal 'invalid-slot-name (list (object-name object)
2657                                    slot-name)))
2658
2659 (defgeneric slot-unbound (object class slot-name fn)
2660   "Slot unbound is invoked during an attempt to reference an unbound slot.")
2661
2662 (defmethod slot-unbound ((object eieio-default-superclass)
2663                          class slot-name fn)
2664   "Slot unbound is invoked during an attempt to reference an unbound slot.
2665 OBJECT is the instance of the object being reference.  CLASS is the
2666 class of OBJECT, and SLOT-NAME is the offending slot.  This function
2667 throws the signal `unbound-slot'.  You can overload this function and
2668 return the value to use in place of the unbound value.
2669 Argument FN is the function signaling this error.
2670 Use `slot-boundp' to determine if a slot is bound or not.
2671
2672 In CLOS, the argument list is (CLASS OBJECT SLOT-NAME), but
2673 EIEIO can only dispatch on the first argument, so the first two are swapped."
2674   (signal 'unbound-slot (list (class-name class) (object-name object)
2675                               slot-name fn)))
2676
2677 (defgeneric no-applicable-method (object method &rest args)
2678   "Called if there are no implementations for OBJECT in METHOD.")
2679
2680 (defmethod no-applicable-method ((object eieio-default-superclass)
2681                                  method &rest args)
2682   "Called if there are no implementations for OBJECT in METHOD.
2683 OBJECT is the object which has no method implementation.
2684 ARGS are the arguments that were passed to METHOD.
2685
2686 Implement this for a class to block this signal.  The return
2687 value becomes the return value of the original method call."
2688   (signal 'no-method-definition (list method (object-name object)))
2689   )
2690
2691 (defgeneric no-next-method (object &rest args)
2692 "Called from `call-next-method' when no additional methods are available.")
2693
2694 (defmethod no-next-method ((object eieio-default-superclass)
2695                            &rest args)
2696   "Called from `call-next-method' when no additional methods are available.
2697 OBJECT is othe object being called on `call-next-method'.
2698 ARGS are the arguments it is called by.
2699 This method signals `no-next-method' by default.  Override this
2700 method to not throw an error, and its return value becomes the
2701 return value of `call-next-method'."
2702   (signal 'no-next-method (list (object-name object) args))
2703 )
2704
2705 (defgeneric clone (obj &rest params)
2706   "Make a copy of OBJ, and then supply PARAMS.
2707 PARAMS is a parameter list of the same form used by `initialize-instance'.
2708
2709 When overloading `clone', be sure to call `call-next-method'
2710 first and modify the returned object.")
2711
2712 (defmethod clone ((obj eieio-default-superclass) &rest params)
2713   "Make a copy of OBJ, and then apply PARAMS."
2714   (let ((nobj (copy-sequence obj))
2715         (nm (aref obj object-name))
2716         (passname (and params (stringp (car params))))
2717         (num 1))
2718     (if params (shared-initialize nobj (if passname (cdr params) params)))
2719     (if (not passname)
2720         (save-match-data
2721           (if (string-match "-\\([0-9]+\\)" nm)
2722               (setq num (1+ (string-to-number (match-string 1 nm)))
2723                     nm (substring nm 0 (match-beginning 0))))
2724           (aset nobj object-name (concat nm "-" (int-to-string num))))
2725       (aset nobj object-name (car params)))
2726     nobj))
2727
2728 (defgeneric destructor (this &rest params)
2729   "Destructor for cleaning up any dynamic links to our object.")
2730
2731 (defmethod destructor ((this eieio-default-superclass) &rest params)
2732   "Destructor for cleaning up any dynamic links to our object.
2733 Argument THIS is the object being destroyed.  PARAMS are additional
2734 ignored parameters."
2735   ;; No cleanup... yet.
2736   )
2737
2738 (defgeneric object-print (this &rest strings)
2739   "Pretty printer for object THIS.  Call function `object-name' with STRINGS.
2740
2741 It is sometimes useful to put a summary of the object into the
2742 default #<notation> string when using EIEIO browsing tools.
2743 Implement this method to customize the summary.")
2744
2745 (defmethod object-print ((this eieio-default-superclass) &rest strings)
2746   "Pretty printer for object THIS.  Call function `object-name' with STRINGS.
2747 The default method for printing object THIS is to use the
2748 function `object-name'.
2749
2750 It is sometimes useful to put a summary of the object into the
2751 default #<notation> string when using EIEIO browsing tools.
2752
2753 Implement this function and specify STRINGS in a call to
2754 `call-next-method' to provide additional summary information.
2755 When passing in extra strings from child classes, always remember
2756 to prepend a space."
2757   (object-name this (apply 'concat strings)))
2758
2759 (defvar eieio-print-depth 0
2760   "When printing, keep track of the current indentation depth.")
2761
2762 (defgeneric object-write (this &optional comment)
2763   "Write out object THIS to the current stream.
2764 Optional COMMENT will add comments to the beginning of the output.")
2765
2766 (defmethod object-write ((this eieio-default-superclass) &optional comment)
2767   "Write object THIS out to the current stream.
2768 This writes out the vector version of this object.  Complex and recursive
2769 object are discouraged from being written.
2770   If optional COMMENT is non-nil, include comments when outputting
2771 this object."
2772   (when comment
2773     (princ ";; Object ")
2774     (princ (object-name-string this))
2775     (princ "\n")
2776     (princ comment)
2777     (princ "\n"))
2778   (let* ((cl (object-class this))
2779          (cv (class-v cl)))
2780     ;; Now output readable lisp to recreate this object
2781     ;; It should look like this:
2782     ;; (<constructor> <name> <slot> <slot> ... )
2783     ;; Each slot's slot is writen using its :writer.
2784     (princ (make-string (* eieio-print-depth 2) ? ))
2785     (princ "(")
2786     (princ (symbol-name (class-constructor (object-class this))))
2787     (princ " \"")
2788     (princ (object-name-string this))
2789     (princ "\"\n")
2790     ;; Loop over all the public slots
2791     (let ((publa (aref cv class-public-a))
2792           (publd (aref cv class-public-d))
2793           (publp (aref cv class-public-printer))
2794           (eieio-print-depth (1+ eieio-print-depth)))
2795       (while publa
2796         (when (slot-boundp this (car publa))
2797           (let ((i (class-slot-initarg cl (car publa)))
2798                 (v (eieio-oref this (car publa)))
2799                 )
2800             (unless (or (not i) (equal v (car publd)))
2801               (princ (make-string (* eieio-print-depth 2) ? ))
2802               (princ (symbol-name i))
2803               (princ " ")
2804               (if (car publp)
2805                   ;; Use our public printer
2806                   (funcall (car publp) v)
2807                 ;; Use our generic override prin1 function.
2808                 (eieio-override-prin1 v))
2809               (princ "\n"))))
2810         (setq publa (cdr publa) publd (cdr publd)
2811               publp (cdr publp)))
2812       (princ (make-string (* eieio-print-depth 2) ? )))
2813     (princ ")\n")))
2814
2815 (defun eieio-override-prin1 (thing)
2816   "Perform a `prin1' on THING taking advantage of object knowledge."
2817   (cond ((eieio-object-p thing)
2818          (object-write thing))
2819         ((listp thing)
2820          (eieio-list-prin1 thing))
2821         ((class-p thing)
2822          (princ (class-name thing)))
2823         ((symbolp thing)
2824          (princ (concat "'" (symbol-name thing))))
2825         (t (prin1 thing))))
2826
2827 (defun eieio-list-prin1 (list)
2828   "Display LIST where list may contain objects."
2829   (if (not (eieio-object-p (car list)))
2830       (progn
2831         (princ "'")
2832         (prin1 list))
2833     (princ "(list ")
2834     (if (eieio-object-p (car list)) (princ "\n "))
2835     (while list
2836       (if (eieio-object-p (car list))
2837           (object-write (car list))
2838         (princ "'")
2839         (prin1 (car list)))
2840       (princ " ")
2841       (setq list (cdr list)))
2842     (princ (make-string (* eieio-print-depth 2) ? ))
2843     (princ ")")))
2844
2845 \f
2846 ;;; Unimplemented functions from CLOS
2847 ;;
2848 (defun change-class (obj class)
2849   "Change the class of OBJ to type CLASS.
2850 This may create or delete slots, but does not affect the return value
2851 of `eq'."
2852   (error "EIEIO: `change-class' is unimplemented"))
2853
2854 )
2855
2856 \f
2857 ;;; Interfacing with edebug
2858 ;;
2859 (defun eieio-edebug-prin1-to-string (object &optional noescape)
2860   "Display EIEIO OBJECT in fancy format.
2861 Overrides the edebug default.
2862 Optional argument NOESCAPE is passed to `prin1-to-string' when appropriate."
2863   (cond ((class-p object) (class-name object))
2864         ((eieio-object-p object) (object-print object))
2865         ((and (listp object) (or (class-p (car object))
2866                                  (eieio-object-p (car object))))
2867          (concat "(" (mapconcat 'eieio-edebug-prin1-to-string object " ") ")"))
2868         (t (prin1-to-string object noescape))))
2869
2870 (add-hook 'edebug-setup-hook
2871           (lambda ()
2872             (def-edebug-spec defmethod
2873               (&define                  ; this means we are defining something
2874                [&or name ("setf" :name setf name)]
2875                ;; ^^ This is the methods symbol
2876                [ &optional symbolp ]    ; this is key :before etc
2877                list              ; arguments
2878                [ &optional stringp ]    ; documentation string
2879                def-body                 ; part to be debugged
2880                ))
2881             ;; The rest of the macros
2882             (def-edebug-spec oref (form quote))
2883             (def-edebug-spec oref-default (form quote))
2884             (def-edebug-spec oset (form quote form))
2885             (def-edebug-spec oset-default (form quote form))
2886             (def-edebug-spec class-v form)
2887             (def-edebug-spec class-p form)
2888             (def-edebug-spec eieio-object-p form)
2889             (def-edebug-spec class-constructor form)
2890             (def-edebug-spec generic-p form)
2891             (def-edebug-spec with-slots (list list def-body))
2892             ;; I suspect this isn't the best way to do this, but when
2893             ;; cust-print was used on my system all my objects
2894             ;; appeared as "#1 =" which was not useful.  This allows
2895             ;; edebug to print my objects in the nice way they were
2896             ;; meant to with `object-print' and `class-name'
2897             ;; (defalias 'edebug-prin1-to-string 'eieio-edebug-prin1-to-string)
2898             )
2899           )
2900
2901 ;;; Interfacing with imenu in emacs lisp mode
2902 ;;    (Only if the expression is defined)
2903 ;;
2904 (if (eval-when-compile (boundp 'list-imenu-generic-expression))
2905 (progn
2906
2907 (defun eieio-update-lisp-imenu-expression ()
2908   "Examine `lisp-imenu-generic-expression' and modify it to find `defmethod'."
2909   (let ((exp lisp-imenu-generic-expression))
2910     (while exp
2911       ;; it's of the form '( ( title expr indx ) ... )
2912       (let* ((subcar (cdr (car exp)))
2913              (substr (car subcar)))
2914         (if (and (not (string-match "|method\\\\" substr))
2915                  (string-match "|advice\\\\" substr))
2916             (setcar subcar
2917                     (replace-match "|advice\\|method\\" t t substr 0))))
2918       (setq exp (cdr exp)))))
2919
2920 (eieio-update-lisp-imenu-expression)
2921
2922 ))
2923
2924 ;;; Autoloading some external symbols, and hooking into the help system
2925 ;;
2926
2927 \f
2928 ;;; Start of automatically extracted autoloads.
2929 \f
2930 ;;;### (autoloads (customize-object) "eieio-custom" "eieio-custom.el"
2931 ;;;;;;  "cf1bd64c76a6e6406545e8c5a5530d43")
2932 ;;; Generated autoloads from eieio-custom.el
2933
2934 (autoload 'customize-object "eieio-custom" "\
2935 Customize OBJ in a custom buffer.
2936 Optional argument GROUP is the sub-group of slots to display.
2937
2938 \(fn OBJ &optional GROUP)" nil nil)
2939
2940 ;;;***
2941 \f
2942 ;;;### (autoloads (eieio-help-mode-augmentation-maybee eieio-describe-generic
2943 ;;;;;;  eieio-describe-constructor eieio-describe-class eieio-browse)
2944 ;;;;;;  "eieio-opt" "eieio-opt.el" "1bed0a56310f402683419139ebc18d7f")
2945 ;;; Generated autoloads from eieio-opt.el
2946
2947 (autoload 'eieio-browse "eieio-opt" "\
2948 Create an object browser window to show all objects.
2949 If optional ROOT-CLASS, then start with that, otherwise start with
2950 variable `eieio-default-superclass'.
2951
2952 \(fn &optional ROOT-CLASS)" t nil)
2953
2954 (defalias 'describe-class 'eieio-describe-class)
2955
2956 (autoload 'eieio-describe-class "eieio-opt" "\
2957 Describe a CLASS defined by a string or symbol.
2958 If CLASS is actually an object, then also display current values of that object.
2959 Optional HEADERFCN should be called to insert a few bits of info first.
2960
2961 \(fn CLASS &optional HEADERFCN)" t nil)
2962
2963 (autoload 'eieio-describe-constructor "eieio-opt" "\
2964 Describe the constructor function FCN.
2965 Uses `eieio-describe-class' to describe the class being constructed.
2966
2967 \(fn FCN)" t nil)
2968
2969 (defalias 'describe-generic 'eieio-describe-generic)
2970
2971 (autoload 'eieio-describe-generic "eieio-opt" "\
2972 Describe the generic function GENERIC.
2973 Also extracts information about all methods specific to this generic.
2974
2975 \(fn GENERIC)" t nil)
2976
2977 (autoload 'eieio-help-mode-augmentation-maybee "eieio-opt" "\
2978 For buffers thrown into help mode, augment for EIEIO.
2979 Arguments UNUSED are not used.
2980
2981 \(fn &rest UNUSED)" nil nil)
2982
2983 ;;;***
2984 \f
2985 ;;; End of automatically extracted autoloads.
2986
2987 (provide 'eieio)
2988
2989 ;;; eieio ends here