Initial Commit
[packages] / xemacs-packages / eieio / eieio.el
1 ;;; eieio.el --- Enhanced Implementation of Emacs Interpreted Objects
2 ;;               or maybe Eric's Implementation of Emacs Intrepreted Objects
3
4 ;;;
5 ;; Copyright (C) 95,96,98,99,2000,01,02,03,04,05,06,07 Eric M. Ludlam
6 ;;
7 ;; Author: <zappo@gnu.org>
8 ;; RCS: $Id: eieio.el,v 1.4 2007-11-26 15:01:06 michaels Exp $
9 ;; Keywords: OO, lisp
10 (defvar eieio-version "1.0"
11   "Current version of EIEIO.")
12 ;;
13 ;; This program is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17 ;;
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22 ;;
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27 ;;
28 ;; Please send bug reports, etc. to zappo@gnu.org
29
30 ;;; Commentary:
31 ;;
32 ;; EIEIO is a series of Lisp routines which implements a subset of
33 ;; CLOS, the Common Lisp Object System.  In addition, EIEIO also adds
34 ;; a few new features which help it integrate more strongly with the
35 ;; Emacs running environment.
36 ;;
37 ;; See eieio.texi for complete documentation on using this package.
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 (require 'cl)
42 (load "cl-macs" nil t) ; No provide in this file.
43
44 ;;; Code:
45 (defun eieio-version ()
46   "Display the current version of EIEIO."
47   (interactive)
48   (message eieio-version))
49
50 (require 'inversion)
51
52 ;;;###autoload immediate
53 (autoload 'eieio-defclass "eieio")
54
55 (defun eieio-require-version (major minor &optional beta)
56   "Non-nil if this version of EIEIO does not satisfy a specific version.
57 Arguments can be:
58
59   (MAJOR MINOR &optional BETA)
60
61   Values MAJOR and MINOR must be integers.  BETA can be an integer, or
62 excluded if a released version is required.
63
64 It is assumed that if the current version is newer than that specified,
65 everything passes.  Exceptions occur when known incompatibilities are
66 introduced."
67   (inversion-test 'eieio
68                   (format "%s.%s%s" major minor
69                           (if beta (format "beta%s" beta) ""))))
70
71 (eval-and-compile
72 ;; Abount the above.  EIEIO must process it's own code when it compiles
73 ;; itself, thus, by eval-and-compiling outselves, we solve the problem.
74
75 ;; Compatibility
76 (if (fboundp 'compiled-function-arglist)
77
78     ;; XEmacs can only access a compiled functions arglist like this:
79     (defalias 'eieio-compiled-function-arglist 'compiled-function-arglist)
80
81   ;; Emacs doesn't have this function, but since FUNC is a vector, we can just
82   ;; grab the appropriate element.
83   (defun eieio-compiled-function-arglist (func)
84     "Return the argument list for the compiled function FUNC."
85     (aref func 0))
86
87   )
88
89 \f
90 ;;;
91 ;; Variable declarations.
92 ;;
93
94 (defvar eieio-hook nil
95   "*This hook is executed, then cleared each time `defclass' is called.
96 The immediate effect is that I can safely keep track of common-lisp
97 `setf' definitions regardless of the order.  Users can add hooks to
98 this variable without worrying about weather this package has been
99 loaded or not.")
100
101 (defvar eieio-error-unsupported-class-tags nil
102   "*Non nil to throw an error if an encountered tag us unsupported.
103 This may prevent classes from CLOS applications from being used with EIEIO
104 since EIEIO does not support all CLOS tags.")
105
106 (defvar eieio-skip-typecheck nil
107   "*If non-nil, skip all slot typechecking.
108 Set this to t permanently if a program is functioning well to get a
109 small speed increase.  This variable is also used internally to handle
110 default setting for optimization purposes.")
111
112 ;; State Variables
113 (defvar this nil
114   "Inside a method, this variable is the object in question.
115 DO NOT SET THIS YOURSELF unless you are trying to simulate friendly fields.
116
117 Note: Embedded methods are no longer supported.  The variable THIS is
118 still set for CLOS methods for the sake of routines like
119 `call-next-method'")
120
121 (defvar scoped-class nil
122   "This is set to a class when a method is running.
123 This is so we know we are allowed to check private parts or how to
124 execute a `call-next-method'.  DO NOT SET THIS YOURSELF!")
125
126 (defvar eieio-initializing-object  nil
127   "Set to non-nil while initializing an object.")
128
129 (defconst eieio-unbound (make-symbol "unbound")
130   "Uninterned symbol representing an unbound slot in an object.")
131
132 ;; This is a bootstrap for eieio-default-superclass so it has a value
133 ;; while it is being built itself.
134 (defvar eieio-default-superclass nil)
135
136 (defconst class-symbol 1 "Class's symbol (self-referencing.).")
137 (defconst class-parent 2 "Class parent field.")
138 (defconst class-children 3 "Class children class field.")
139 (defconst class-symbol-obarray 4 "Obarray permitting fast access to variable position indexes.")
140 (defconst class-public-a 5 "Class public attribute index.")
141 (defconst class-public-d 6 "Class public attribute defaults index.")
142 (defconst class-public-doc 7 "Class public documentation strings for attributes.")
143 (defconst class-public-type 8 "Class public type for a slot.")
144 (defconst class-public-custom 9 "Class public custom type for a slot.")
145 (defconst class-public-custom-label 10 "Class public custom group for a slot.")
146 (defconst class-public-custom-group 11 "Class public custom group for a slot.")
147 (defconst class-protection 12 "Class protection for a slot.")
148 (defconst class-initarg-tuples 13 "Class initarg tuples list.")
149 (defconst class-class-allocation-a 14 "Class allocated attributes.")
150 (defconst class-class-allocation-doc 15 "Class allocated documentation.")
151 (defconst class-class-allocation-type 16 "Class allocated value type.")
152 (defconst class-class-allocation-custom 17 "Class allocated custom descriptor.")
153 (defconst class-class-allocation-custom-label 18 "Class allocated custom descriptor.")
154 (defconst class-class-allocation-custom-group 19 "Class allocated custom group.")
155 (defconst class-class-allocation-protection 20 "Class allocated protection list.")
156 (defconst class-class-allocation-values 21 "Class allocated value vector.")
157 (defconst class-default-object-cache 22
158   "Cache index of what a newly created object would look like.
159 This will speed up instantiation time as only a `copy-sequence' will
160 be needed, instead of looping over all the values and setting them
161 from the default.")
162 (defconst class-options 23
163   "Storage location of tagged class options.
164 Stored outright without modifications or stripping.")
165
166 (defconst class-num-fields 24
167   "Number of fields in the class definition object.")
168
169 (defconst object-class 1 "Index in an object vector where the class is stored.")
170 (defconst object-name 2 "Index in an object where the name is stored.")
171
172 (defconst method-static 0 "Index into :STATIC tag on a method.")
173 (defconst method-before 1 "Index into :BEFORE tag on a method.")
174 (defconst method-primary 2 "Index into :PRIMARY tag on a method.")
175 (defconst method-after 3 "Index into :AFTER tag on a method.")
176 (defconst method-num-lists 4 "Number of indexes into methods vector in which groups of functions are kept.")
177 (defconst method-generic-before 4 "Index into generic :BEFORE tag on a method.")
178 (defconst method-generic-primary 5 "Index into generic :PRIMARY tag on a method.")
179 (defconst method-generic-after 6 "Index into generic :AFTER tag on a method.")
180 (defconst method-num-fields 7 "Number of indexes into a method's vector.")
181
182 ;; How to specialty compile stuff.
183 (autoload 'byte-compile-file-form-defmethod "eieio-comp"
184   "This function is used to byte compile methods in a nice way.")
185 (put 'defmethod 'byte-hunk-handler 'byte-compile-file-form-defmethod)
186
187 (eval-when-compile (require 'eieio-comp))
188
189 \f
190 ;;; Important macros used in eieio.
191 ;;
192 (defmacro class-v (class) "Internal: Return the class vector from the CLASS symbol."
193   ;; No check: If eieio gets this far, it's probably been checked already.
194   `(get ,class `eieio-class-definition))
195
196 (defmacro class-p (class)
197   "Return t if CLASS is a valid class vector.
198 CLASS is a symbol.  Defclass will assign the class symbol to itself, so
199 the shortcut (class-p foo) will work.  The form (class-p 'foo) is more
200 robust."
201   ;; this new method is faster since it doesn't waste time checking lots of
202   ;; things.
203   `(condition-case nil
204        (eq (aref (class-v ,class) 0) 'defclass)
205      (error nil)))
206
207 (defmacro object-p (obj) "Return t if OBJ is an object vector."
208   `(condition-case nil
209        (let ((tobj ,obj))
210          (and (eq (aref tobj 0) 'object)
211               (class-p (aref tobj object-class))))
212      (error nil)))
213
214 (defmacro class-constructor (class)
215   "Return the symbol representing the constructor of CLASS."
216   `(aref (class-v ,class) class-symbol))
217
218 (defmacro generic-p (method)
219   "Return t if symbol METHOD is a generic function.
220 Only methods have the symbol `eieio-method-obarray' as a property (which
221 contains a list of all bindings to that method type.)"
222   `(and (fboundp ,method) (get ,method 'eieio-method-obarray)))
223
224 (defmacro class-option-assoc (list option)
225   "Return from LIST the found OPTION.  Nil if it doesn't exist."
226   `(car-safe (cdr (memq ,option ,list))))
227
228 (defmacro class-option (class option)
229   "Return the value stored for CLASS' OPTION.
230 Return nil if that option doesn't exist."
231   `(class-option-assoc (aref (class-v ,class) class-options) ',option))
232
233 (defmacro class-abstract-p (class)
234   "Return non-nil if CLASS is abstract.
235 Abstract classes cannot be instantiated."
236   `(class-option ,class :abstract))
237
238 \f
239 ;;; Defining a new class
240 ;;
241 (defmacro defclass (name superclass fields &rest options-and-doc)
242   "Define NAME as a new class derived from SUPERCLASS with FIELDS.
243 OPTIONS-AND-DOC is used as the class' options and base documentation.
244 SUPERCLASS is a list of superclasses to inherit from, with FIELDS
245 being the fields residing in that class definition.  NOTE: Currently
246 only one field may exist in SUPERCLASS as multiple inheritance is not
247 yet supported.  Supported tags are:
248
249   :initform   - initializing form
250   :initarg    - tag used during initialization
251   :accessor   - tag used to create a function to access this field
252   :allocation - specify where the value is stored.
253                 defaults to `:instance', but could also be `:class'
254   :writer     - a function symbol which will `write' an object's slot
255   :reader     - a function symbol which will `read' an object
256   :type       - the type of data allowed in this slot (see `typep')
257   :documentation
258               - A string documenting use of this slot.
259
260 The following are extensions on CLOS:
261   :protection - Specify protection for this slot.
262                 Defaults to `:public'.  Also use `:protected', or `:private'
263   :custom     - When customizing an object, the custom :type.  Public only.
264   :label      - A text string label used for a slot when customizing.
265   :group      - Name of a customization group this slot belongs in.
266
267 A class can also have optional options.  These options happen in place
268 of documentation, (including a :documentation tag) in addition to
269 documentation, or not at all.  Supported options are:
270
271   :documentation - The doc-string used for this class.
272
273 Options added to EIEIO:
274
275   :allow-nil-initform - Non-nil to skip typechecking of initforms if nil.
276   :custom-groups      - List of custom group names.  Organizes slots into
277                         reasonable groups for customizations.
278   :abstract           - Non-nil to prevent instances of this class.
279                         If a string, use as an error string if someone does
280                         try to make an instance.
281
282 Options in CLOS not supported in EIEIO:
283
284   :metaclass - Class to use in place of `standard-class'
285   :default-initargs - Initargs to use when initializing new objects of
286                       this class.
287
288 Due to the way class options are set up, you can add any tags in you
289 wish, and reference them using the function `class-option'."
290   ;; We must `eval-and-compile' this so that when we byte compile
291   ;; an eieio program, there is no need to load it ahead of time.
292   ;; It also provides lots of nice debugging errors at compile time.
293   `(eval-and-compile
294      (eieio-defclass ',name ',superclass ',fields ',options-and-doc)))
295
296 (defun eieio-defclass (cname superclasses fields options-and-doc)
297   "See `defclass' for more information.
298 Define CNAME as a new subclass of SUPERCLASSES, with FIELDS being the
299 fields residing in that class definition, and with options or documentation
300 OPTIONS-AND-DOC as the toplevel documentation for this class."
301   ;; Run our eieio-hook each time, and clear it when we are done.
302   ;; This way people can add hooks safely if they want to modify eieio
303   ;; or add definitions when eieio is loaded or something like that.
304   (run-hooks 'eieio-hook)
305   (setq eieio-hook nil)
306
307   (if (not (symbolp cname)) (signal 'wrong-type-argument '(symbolp cname)))
308   (if (not (listp superclasses)) (signal 'wrong-type-argument '(listp superclasses)))
309
310   (let* ((pname (if superclasses superclasses nil))
311          (newc (make-vector class-num-fields nil))
312          (oldc (when (class-p cname) (class-v cname)))
313          (groups nil) ;; list of groups id'd from slots
314          (options nil)
315          (clearparent nil))
316
317     (aset newc 0 'defclass)
318     (aset newc class-symbol cname)
319
320     ;; If this class already existed, and we are updating it's structure,
321     ;; make sure we keep the old child list.  This can cause bugs, but
322     ;; if no new slots are created, it also saves time, and prevents
323     ;; method table breakage, particularly when the users is only
324     ;; byte compiling an EIEIO file.
325     (when oldc
326       (aset newc class-children (aref oldc class-children)))
327
328     (cond ((and (stringp (car options-and-doc))
329                 (/= 1 (% (length options-and-doc) 2)))
330            (error "Too many arguments to `defclass'"))
331           ((and (symbolp (car options-and-doc))
332                 (/= 0 (% (length options-and-doc) 2)))
333            (error "Too many arguments to `defclass'"))
334           )
335
336     (setq options
337           (if (stringp (car options-and-doc))
338               (cons :documentation options-and-doc)
339             options-and-doc))
340
341     (if pname
342         (progn
343           (while pname
344             (if (and (car pname) (symbolp (car pname)))
345                 (if (not (class-p (car pname)))
346                     ;; bad class
347                     (error "Given parent class %s is not a class" (car pname))
348                   ;; good parent class...
349                   ;; save new child in parent
350                   (if (not (member cname (aref (class-v (car pname)) class-children)))
351                       (aset (class-v (car pname)) class-children
352                             (cons cname (aref (class-v (car pname)) class-children))))
353                   ;; Get custom groups, and store them into our local copy.
354                   (mapcar (lambda (g) (add-to-list 'groups g))
355                           (class-option (car pname) :custom-groups))
356                   ;; save parent in child
357                   (aset newc class-parent (cons (car pname) (aref newc class-parent))))
358               (error "Invalid parent class %s" pname))
359             (setq pname (cdr pname)))
360           ;; Reverse the list of our parents so that they are prioritized in
361           ;; the same order as specified in the code.
362           (aset newc class-parent (nreverse (aref newc class-parent))) )
363       ;; If there is nothing to loop over, then inherit from the
364       ;; default superclass.
365       (unless (eq cname 'eieio-default-superclass)
366         ;; adopt the default parent here, but clear it later...
367         (setq clearparent t)
368         ;; save new child in parent
369         (if (not (member cname (aref (class-v 'eieio-default-superclass) class-children)))
370             (aset (class-v 'eieio-default-superclass) class-children
371                   (cons cname (aref (class-v 'eieio-default-superclass) class-children))))
372         ;; save parent in child
373         (aset newc class-parent (list eieio-default-superclass))))
374     
375     ;; turn this into a useable self-pointing symbol
376     (set cname cname)
377
378     ;; These two tests must be created right away so we can have self-
379     ;; referencing classes.  ei, a class whose slot can contain only
380     ;; pointers to itself.
381
382     ;; Create the test function
383     (let ((csym (intern (concat (symbol-name cname) "-p"))))
384       (fset csym
385             (list 'lambda (list 'obj)
386                   (format "Test OBJ to see if it an object of type %s" cname)
387                   (list 'and '(object-p obj)
388                         (list 'same-class-p 'obj cname)))))
389
390     ;; Create a handy child test too
391     (let ((csym (intern (concat (symbol-name cname) "-child-p"))))
392       (fset csym
393             `(lambda (obj)
394                ,(format
395                   "Test OBJ to see if it an object is a child of type %s"
396                   cname)
397                (and (object-p obj)
398                     (object-of-class-p obj ,cname))))
399     
400       ;; When using typep, (typep OBJ 'myclass) returns t for objects which
401       ;; are subclasses of myclass.  For our predicates, however, it is
402       ;; important for EIEIO to be backwards compatible, where
403       ;; myobject-p, and myobject-child-p are different.
404       ;; "cl" uses this technique to specify symbols with specific typep
405       ;; test, so we can let typep have the CLOS documented behavior
406       ;; while keeping our above predicate clean.
407       (eval `(deftype ,cname ()
408                '(satisfies
409                  ,(intern (concat (symbol-name cname) "-child-p")))))
410
411       )
412
413     ;; before adding new fields, lets add all the methods and classes
414     ;; in from the parent class
415     (eieio-copy-parents-into-subclass newc superclasses)
416
417     ;; Store the new class vector definition into the symbol.  We need to
418     ;; do this first so that we can call defmethod for the accessor.
419     ;; The vector will be updated by the following while loop and will not
420     ;; need to be stored a second time.
421     (put cname 'eieio-class-definition newc)
422
423     ;; Query each field in the declaration list and mangle into the
424     ;; class structure I have defined.
425     (while fields
426       (let* ((field1  (car fields))
427              (name    (car field1))
428              (field   (cdr field1))
429              (acces   (plist-get field ':accessor))
430              (init    (or (plist-get field ':initform)
431                           (if (member ':initform field) nil
432                             eieio-unbound)))
433              (initarg (plist-get field ':initarg))
434              (docstr  (plist-get field ':documentation))
435              (prot    (plist-get field ':protection))
436              (reader  (plist-get field ':reader))
437              (writer  (plist-get field ':writer))
438              (alloc   (plist-get field ':allocation))
439              (type    (plist-get field ':type))
440              (custom  (plist-get field ':custom))
441              (label   (plist-get field ':label))
442              (customg (plist-get field ':group))
443              
444              (skip-nil (class-option-assoc options :allow-nil-initform))
445              )
446
447         (if eieio-error-unsupported-class-tags
448             (let ((tmp field))
449               (while tmp
450                 (if (not (member (car tmp) '(:accessor
451                                              :initform
452                                              :initarg
453                                              :documentation
454                                              :protection
455                                              :reader
456                                              :writer
457                                              :allocation
458                                              :type
459                                              :custom
460                                              :label
461                                              :group
462                                              :allow-nil-initform
463                                              :custom-groups)))
464                     (signal 'invalid-slot-type (list (car tmp))))
465                 (setq tmp (cdr (cdr tmp))))))
466
467         ;; Clean up the meaning of protection.
468         (cond ((or (eq prot 'public) (eq prot :public)) (setq prot nil))
469               ((or (eq prot 'protected) (eq prot :protected)) (setq prot 'protected))
470               ((or (eq prot 'private) (eq prot :private)) (setq prot 'private))
471               ((eq prot nil) nil)
472               (t (signal 'invalid-slot-type (list ':protection prot))))
473
474         ;; Make sure the :allocation parameter has a valid value.
475         (if (not (or (not alloc) (eq alloc :class) (eq alloc :instance)))
476             (signal 'invalid-slot-type (list ':allocation alloc)))
477
478         ;; The default type specifier is supposed to be t, meaning anything.
479         (if (not type) (setq type t))
480
481         ;; Label is nil, or a string
482         (if (not (or (null label) (stringp label)))
483             (signal 'invalid-slot-type (list ':label label)))
484         
485         ;; Is there an initarg, but allocation of class?
486         (if (and initarg (eq alloc :class))
487             (message "Class allocated slots do not need :initarg"))
488
489         ;; intern the symbol so we can use it blankly
490         (if initarg (set initarg initarg))
491
492         ;; The customgroup should be a list of symbols
493         (cond ((null customg)
494                (setq customg '(default)))
495               ((not (listp customg))
496                (setq customg (list customg))))
497         ;; The customgroup better be a symbol, or list o symbols.
498         (mapcar (lambda (cg)
499                   (if (not (symbolp cg))
500                       (signal 'invalid-slot-type (list ':group cg))))
501                 customg)
502
503         ;; First up, add this field into our new class.
504         (eieio-add-new-field newc name init docstr type custom label customg
505                              prot initarg alloc 'defaultoverride skip-nil)
506
507         ;; We need to id the group, and store them in a group list attribute.
508         (mapcar (lambda (cg) (add-to-list 'groups cg)) customg)
509
510         ;; anyone can have an accessor function.  This creates a function
511         ;; of the specified name, and also performs a `defsetf' if applicable
512         ;; so that users can `setf' the space returned by this function
513         (if acces
514             (progn
515               (eieio-defmethod acces
516                 (list (if (eq alloc :class) :STATIC :PRIMARY)
517                       (list (list 'this cname))
518                       (format
519                        "Retrieves the slot `%s' from an object of class `%s'"
520                        name cname)
521                       (list 'eieio-oref 'this (list 'quote name))))
522               ;; Thanks Pascal Bourguignon <pjb@informatimago.com>
523               ;; For this complex macro.
524               (eval (macroexpand
525                      (list  'defsetf acces '(widget) '(store)
526                             (list 'list ''eieio-oset 'widget
527                                   (list 'quote (list 'quote name)) 'store))))
528               ;;`(defsetf ,acces (widget) (store) (eieio-oset widget ',cname store))
529               )
530           )
531         ;; If a writer is defined, then create a generic method of that
532         ;; name whose purpose is to set the value of the slot.
533         (if writer
534             (progn
535               (eieio-defmethod writer
536                 (list (list (list 'this cname) 'value)
537                       (format "Set the slot `%s' of an object of class `%s'"
538                               name cname)
539                       `(setf (slot-value this ',name) value)))
540               ))
541         ;; If a reader is defined, then create a generic method
542         ;; of that name whose purpose is to access this slot value.
543         (if reader
544             (progn
545               (eieio-defmethod reader
546                 (list (list (list 'this cname))
547                       (format "Access the slot `%s' from object of class `%s'"
548                               name cname)
549                       `(slot-value this ',name)))))
550         )
551       (setq fields (cdr fields)))
552
553     ;; Now that everything has been loaded up, all our lists are backwards!  Fix that up now.
554     (aset newc class-public-a (nreverse (aref newc class-public-a)))
555     (aset newc class-public-d (nreverse (aref newc class-public-d)))
556     (aset newc class-public-doc (nreverse (aref newc class-public-doc)))
557     (aset newc class-public-type
558           (apply 'vector (nreverse (aref newc class-public-type))))
559     (aset newc class-public-custom (nreverse (aref newc class-public-custom)))
560     (aset newc class-public-custom-label (nreverse (aref newc class-public-custom-label)))
561     (aset newc class-public-custom-group (nreverse (aref newc class-public-custom-group)))
562     (aset newc class-protection (nreverse (aref newc class-protection)))
563     (aset newc class-initarg-tuples (nreverse (aref newc class-initarg-tuples)))
564
565     ;; The storage for class-class-allocation-type needs to be turned into
566     ;; a vector now.
567     (aset newc class-class-allocation-type
568           (apply 'vector (aref newc class-class-allocation-type)))
569
570     ;; Also, take class allocated values, and vectorize them for speed.
571     (aset newc class-class-allocation-values
572           (apply 'vector (aref newc class-class-allocation-values)))
573
574     ;; Attach field symbols into an obarray, and store the index of
575     ;; this field as the variable slot in this new symbol.  We need to
576     ;; know about primes, because obarrays are best set in vectors of
577     ;; prime number length, and we also need to make our vector small
578     ;; to save space, and also optimal for the number of items we have.
579     (let* ((cnt 0)
580            (pubsyms (aref newc class-public-a))
581            (prots (aref newc class-protection))
582            (l (length pubsyms))
583            (vl (let ((primes '( 3 5 7 11 13 17 19 23 29 31 37 41 43 47
584                                   53 59 61 67 71 73 79 83 89 97 101 )))
585                  (while (and primes (< (car primes) l))
586                    (setq primes (cdr primes)))
587                  (car primes)))
588            (oa (make-vector vl 0))
589            (newsym))
590       (while pubsyms
591         (setq newsym (intern (symbol-name (car pubsyms)) oa))
592         (set newsym cnt)
593         (setq cnt (1+ cnt))
594         (if (car prots) (put newsym 'protection (car prots)))
595         (setq pubsyms (cdr pubsyms)
596               prots (cdr prots)))
597       (aset newc class-symbol-obarray oa)
598       )
599
600     ;; Create the constructor function
601     (if (class-option-assoc options :abstract)
602         ;; Abstract classes cannot be instantiated.  Say so.
603         (let ((abs (class-option-assoc options :abstract)))
604           (if (not (stringp abs))
605               (setq abs (format "Class %s is abstract" cname)))
606           (fset cname
607                 `(lambda (&rest stuff)
608                    ,(format "You cannot create a new object of type %s" cname)
609                    (error ,abs))))
610
611       ;; Non-abstract classes need a constructor.
612       (fset cname
613             `(lambda (newname &rest fields)
614                ,(format "Create a new object with name NAME of class type %s" cname)
615                (apply 'constructor ,cname newname fields)))
616       )
617
618     ;; Set up a specialized doc string.
619     ;; Use stored value since it is calculated in a non-trivial way
620     (put cname 'variable-documentation
621          (class-option-assoc options :documentation))
622
623     ;; We have a list of custom groups.  Store them into the options.
624     (let ((g (class-option-assoc options :custom-groups)))
625       (mapcar (lambda (cg) (add-to-list 'g cg)) groups)
626       (if (memq :custom-groups options)
627           (setcar (cdr (memq :custom-groups options)) g)
628         (setq options (cons :custom-groups (cons g options)))))
629
630     ;; Set up the options we have collected.
631     (aset newc class-options options)
632
633     ;; if this is a superclass, clear out parent (which was set to the
634     ;; default superclass eieio-default-superclass)
635     (if clearparent (aset newc class-parent nil))
636
637     ;; Create the cached default object.
638     (let ((cache (make-vector (+ (length (aref newc class-public-a))
639                                  3) nil)))
640       (aset cache 0 'object)
641       (aset cache object-class cname)
642       (aset cache object-name 'default-cache-object)
643       (let ((eieio-skip-typecheck t))
644         ;; All type-checking has been done to our satisfaction
645         ;; before this call.  Don't waste our time in this call..
646         (eieio-set-defaults cache t))
647       (aset newc class-default-object-cache cache))
648
649     ;; Return our new class object
650     newc
651     ))
652
653 (defun eieio-perform-slot-validation-for-default (field spec value skipnil)
654   "For FIELD, signal if SPEC does not match VALUE.
655 If SKIPNIL is non-nil, then if VALUE is nil, return t."
656   (let ((val (eieio-default-eval-maybe value)))
657     (if (and (not eieio-skip-typecheck)
658              (not (and skipnil (null val)))
659              (not (eieio-perform-slot-validation spec val)))
660         (signal 'invalid-slot-type (list field spec val)))))
661
662 (defun eieio-add-new-field (newc a d doc type cust label custg prot init alloc
663                                  &optional defaultoverride skipnil)
664   "Add into NEWC attribute A.
665 If A already exists in NEWC, then do nothing.  If it doesn't exist,
666 then also add in D (defualt), DOC, TYPE, CUST, LABEL, CUSTG, PROT, and INIT arg.
667 Argument ALLOC specifies if the field is allocated per instance, or per class.
668 If optional DEFAULTOVERRIDE is non-nil, then if A exists in NEWC,
669 we must override it's value for a default.
670 Optional argument SKIPNIL indicates if type checking should be skipped
671 if default value is nil."
672   ;; Make sure we duplicate those items that are sequences.
673   (if (sequencep d) (setq d (copy-sequence d)))
674   (if (sequencep type) (setq type (copy-sequence type)))
675   (if (sequencep cust) (setq cust (copy-sequence cust)))
676   (if (sequencep custg) (setq custg (copy-sequence custg)))
677
678   ;; To prevent override information w/out specification of storage,
679   ;; we need to do this little hack.
680   (if (member a (aref newc class-class-allocation-a)) (setq alloc ':class))
681
682   (if (or (not alloc) (and (symbolp alloc) (eq alloc ':instance)))
683       ;; In this case, we modify the INSTANCE version of a given slot.
684       ;; Only add this element if it is so-far unique
685       (if (not (member a (aref newc class-public-a)))
686           (progn
687             (eieio-perform-slot-validation-for-default a type d skipnil)
688             (aset newc class-public-a (cons a (aref newc class-public-a)))
689             (aset newc class-public-d (cons d (aref newc class-public-d)))
690             (aset newc class-public-doc (cons doc (aref newc class-public-doc)))
691             (aset newc class-public-type (cons type (aref newc class-public-type)))
692             (aset newc class-public-custom (cons cust (aref newc class-public-custom)))
693             (aset newc class-public-custom-label (cons label (aref newc class-public-custom-label)))
694             (aset newc class-public-custom-group (cons custg (aref newc class-public-custom-group)))
695             (aset newc class-protection (cons prot (aref newc class-protection)))
696             (aset newc class-initarg-tuples (cons (cons init a) (aref newc class-initarg-tuples)))
697             )
698         ;; When defaultoverride is true, we are usually adding new local
699         ;; attributes which must override the default value of any field
700         ;; passed in by one of the parent classes.
701         (if defaultoverride
702             (progn
703               ;; There is a match, and we must override the old value.
704               (let* ((ca (aref newc class-public-a))
705                      (np (member a ca))
706                      (num (- (length ca) (length np)))
707                      (dp (if np (nthcdr num (aref newc class-public-d))
708                            nil))
709                      (tp (if np (nth num (aref newc class-public-type))))
710                      )
711                 (if (not np)
712                     (error "Eieio internal error overriding default value for %s"
713                            a)
714                   ;; If type is passed in, is it the same?
715                   (if (not (eq type t))
716                       (if (not (equal type tp))
717                           (error
718                            "Child slot type `%s' does not match inherited type `%s' for `%s'"
719                            type tp a)))
720                   ;; If we have a repeat, only update the initarg...
721                   (eieio-perform-slot-validation-for-default a tp d skipnil)
722                   (setcar dp d)
723                   ;; If we have a new initarg, check for it.
724                   (when init
725                     (let* ((inits (aref newc class-initarg-tuples))
726                            (inita (rassq a inits)))
727                       ;; Replace the CAR of the associate INITA.
728                       ;;(message "Initarg: %S replace %s" inita init)
729                       (setcar inita init)
730                       ))
731                   ;; TODO:
732                   ;;  For other slots (protection, etc) we should get the
733                   ;;  original value, and make sure each is equal to the
734                   ;;  last value and throw an error, or accept it.
735                   )))))
736     (let ((value (eieio-default-eval-maybe d)))
737       (if (not (member a (aref newc class-class-allocation-a)))
738           (progn
739             (eieio-perform-slot-validation-for-default a type value skipnil)
740             ;; Here we have found a :class version of a slot.  This
741             ;; requires a very different aproach.
742             (aset newc class-class-allocation-a (cons a (aref newc class-class-allocation-a)))
743             (aset newc class-class-allocation-doc (cons doc (aref newc class-class-allocation-doc)))
744             (aset newc class-class-allocation-type (cons type (aref newc class-class-allocation-type)))
745             (aset newc class-class-allocation-custom (cons cust (aref newc class-class-allocation-custom)))
746             (aset newc class-class-allocation-custom-label (cons label (aref newc class-class-allocation-custom-label)))
747             (aset newc class-class-allocation-custom-group (cons custg (aref newc class-class-allocation-custom-group)))
748             (aset newc class-class-allocation-protection (cons prot (aref newc class-class-allocation-protection)))
749   ;; Default value is stored in the 'values section, since new objects
750             ;; can't initialize from this element.
751             (aset newc class-class-allocation-values (cons value (aref newc class-class-allocation-values))))
752         (if defaultoverride
753             (progn
754               ;; There is a match, and we must override the old value.
755               (let* ((ca (aref newc class-class-allocation-a))
756                      (np (member a ca))
757                      (num (- (length ca) (length np)))
758                      (dp (if np
759                              (nthcdr num
760                                      (aref newc class-class-allocation-values))
761                            nil))
762                      (tp (if np (nth num (aref newc class-class-allocation-type))
763                            nil)))
764                 (if (not np)
765                     (error "Eieio internal error overriding default value for %s"
766                            a)
767                   ;; If type is passed in, is it the same?
768                   (if (not (eq type t))
769                       (if (not (equal type tp))
770                           (error
771                            "Child slot type `%s' does not match inherited type `%s' for `%s'"
772                            type tp a)))
773                   ;; If we have a repeat, only update the vlaue...
774                   (eieio-perform-slot-validation-for-default a tp value skipnil)
775                   (setcar dp value))
776                 )))))
777     ))
778
779 (defun eieio-copy-parents-into-subclass (newc parents)
780   "Copy into NEWC the fields of PARENTS.
781 Follow the rules of not overwritting early parents when applying to
782 the new child class."
783   (let ((ps (aref newc class-parent))
784         (sn (class-option-assoc (aref newc class-options)
785                                 ':allow-nil-initform)))
786     (while ps
787       ;; First, duplicate all the fields of the parent.
788       (let ((pcv (class-v (car ps))))
789         (let ((pa (aref pcv class-public-a))
790               (pd (aref pcv class-public-d))
791               (pdoc (aref pcv class-public-doc))
792               (ptype (aref pcv class-public-type))
793               (pcust (aref pcv class-public-custom))
794               (plabel (aref pcv class-public-custom-label))
795               (pcustg (aref pcv class-public-custom-group))
796               (pprot (aref pcv class-protection))
797               (pinit (aref pcv class-initarg-tuples))
798               (i 0))
799           (while pa
800             (eieio-add-new-field newc
801                                  (car pa) (car pd) (car pdoc) (aref ptype i)
802                                  (car pcust) (car plabel) (car pcustg)
803                                  (car pprot) (car-safe (car pinit)) nil nil sn)
804             ;; Increment each value.
805             (setq pa (cdr pa)
806                   pd (cdr pd)
807                   pdoc (cdr pdoc)
808                   i (1+ i)
809                   pcust (cdr pcust)
810                   plabel (cdr plabel)
811                   pcustg (cdr pcustg)
812                   pprot (cdr pprot)
813                   pinit (cdr pinit))
814             )) ;; while/let
815         ;; Now duplicate all the class alloc fields.
816         (let ((pa (aref pcv class-class-allocation-a))
817               (pdoc (aref pcv class-class-allocation-doc))
818               (ptype (aref pcv class-class-allocation-type))
819               (pcust (aref pcv class-class-allocation-custom))
820               (plabel (aref pcv class-class-allocation-custom-label))
821               (pcustg (aref pcv class-class-allocation-custom-group))
822               (pprot (aref pcv class-class-allocation-protection))
823               (pval (aref pcv class-class-allocation-values))
824               (i 0))
825           (while pa
826             (eieio-add-new-field newc
827                                  (car pa) (aref pval i) (car pdoc) (aref ptype i)
828                                  (car pcust) (car plabel) (car pcustg)
829                                  (car pprot) nil ':class sn)
830             ;; Increment each value.
831             (setq pa (cdr pa)
832                   pdoc (cdr pdoc)
833                   pcust (cdr pcust)
834                   plabel (cdr plabel)
835                   pcustg (cdr pcustg)
836                   pprot (cdr pprot)
837                   i (1+ i))
838             ))) ;; while/let
839       ;; Loop over each parent class
840       (setq ps (cdr ps)))
841     ))
842
843 ;;; CLOS style implementation of object creators.
844 ;;
845 (defun make-instance (class &rest initargs)
846   "Make a new instance of CLASS with NAME and initialization based on INITARGS.
847 The class' constructor requires a name for use when printing.
848 `make-instance' in CLOS doesn't use names the way Emacs does, so the
849 class is used as the name slot instead when INITARGS doesn't start with
850 a string.  The rest of INITARGS are label/value pairs.  The label's
851 are the symbols created with the :initarg tag from the `defclass' call.
852 The value is the value stored in that slot.
853 CLASS is a symbol.  Defclass will assign the class symbol to itself, so
854 the shortcut (make-instance foo) will work.  The form (make-instance 'foo)
855 is more robust."
856   (if (and (car initargs) (stringp (car initargs)))
857       (apply (class-constructor class) initargs)
858     (apply  (class-constructor class)
859             (cond ((symbolp class) (symbol-name class))
860                   (t (format "%S" class)))
861             initargs)))
862
863 \f
864 ;;; CLOS methods and generics
865 ;;
866 (defmacro defgeneric (method args &optional doc-string)
867   "Create a generic function METHOD.  ARGS is ignored.
868 DOC-STRING is the base documentation for this class.  A generic
869 function has no body, as it's purpose is to decide which method body
870 is appropriate to use.  Use `defmethod' to create methods, and it
871 calls defgeneric for you.  With this implementation the arguments are
872 currently ignored.  You can use `defgeneric' to apply specialized
873 top level documentation to a method."
874   `(eieio-defgeneric (quote ,method) ,doc-string))
875
876 (defun eieio-defgeneric-form (method doc-string)
877   "The lambda form that would be used as the function defined on METHOD.
878 All methods should call the same EIEIO function for dispatch.
879 DOC-STRING is the documentation attached to METHOD."
880   `(lambda (&rest local-args)
881      ,doc-string
882      (eieio-generic-call (quote ,method) local-args)))
883
884 (defun eieio-defgeneric (method doc-string)
885   "Engine part to `defgeneric' macro defining METHOD with DOC-STRING."
886   (if (and (fboundp method) (not (generic-p method))
887            (or (byte-code-function-p (symbol-function method))
888                (not (eq 'autoload (car (symbol-function method)))))
889            )
890       (error "You cannot create a generic/method over an existing symbol: %s"
891              method))
892   ;; Don't do this over and over.
893   (unless (fboundp 'method)
894     ;; This defun tells emacs where the first definition of this
895     ;; method is defined.
896     `(defun ,method nil)
897     ;; Apply the actual body of this function.
898     (fset method (eieio-defgeneric-form method doc-string))
899     ;; Make sure the method tables are installed.
900     (eieiomt-install method)
901     ;; Return the method
902     'method))
903
904 (defun eieio-unbind-method-implementations (method)
905   "Make the generic method METHOD have no implementations..
906 It will leave the original generic function in place, but remove
907 reference to all implementations of METHOD."
908   (put method 'eieio-method-tree nil)
909   (put method 'eieio-method-obarray nil))
910
911 (defmacro defmethod (method &rest args)
912   "Create a new METHOD through `defgeneric' with ARGS.
913 ARGS lists any keys (such as :BEFORE, :PRIMARY, :AFTER, or :STATIC),
914 the arglst, and doc string, and eventually the body, such as:
915
916  (defmethod mymethod [:BEFORE | :PRIMARY | :AFTER | :STATIC] (args)
917     doc-string body)"
918   `(eieio-defmethod (quote ,method) (quote ,args)))
919
920 (defun eieio-defmethod (method args)
921   "Work part of the `defmethod' macro defining METHOD with ARGS."
922   (let ((key nil) (body nil) (firstarg nil) (argfix nil) (argclass nil) loopa)
923     ;; find optional keys
924     (setq key
925           (cond ((eq ':BEFORE (car args))
926                  (setq args (cdr args))
927                  method-before)
928                 ((eq ':AFTER (car args))
929                  (setq args (cdr args))
930                  method-after)
931                 ((eq ':PRIMARY (car args))
932                  (setq args (cdr args))
933                  method-primary)
934                 ((eq ':STATIC (car args))
935                  (setq args (cdr args))
936                  method-static)
937                 ;; Primary key
938                 (t method-primary)))
939     ;; get body, and fix contents of args to be the arguments of the fn.
940     (setq body (cdr args)
941           args (car args))
942     (setq loopa args)
943     ;; Create a fixed version of the arguments
944     (while loopa
945       (setq argfix (cons (if (listp (car loopa)) (car (car loopa)) (car loopa))
946                          argfix))
947       (setq loopa (cdr loopa)))
948     ;; make sure there is a generic
949     (eieio-defgeneric
950      method
951      (if (stringp (car body))
952          (car body) (format "Generically created method `%s'" method)))
953     ;; create symbol for property to bind to.  If the first arg is of
954     ;; the form (varname vartype) and `vartype' is a class, then
955     ;; that class will be the type symbol.  If not, then it will fall
956     ;; under the type `primary' which is a non-specific calling of the
957     ;; function.
958     (setq firstarg (car args))
959     (if (listp firstarg)
960         (progn
961           (setq argclass  (nth 1 firstarg))
962           (if (not (class-p argclass))
963               (error "Unknown class type %s in method parameters"
964                      (nth 1 firstarg))))
965       (if (= key -1)
966           (signal 'wrong-type-argument (list :STATIC 'non-class-arg)))
967       ;; generics are higher
968       (setq key (+ key 3)))
969     ;; Put this lambda into the symbol so we can find it
970     (if (byte-code-function-p (car-safe body))
971         (eieiomt-add method (car-safe body) key argclass)
972       (eieiomt-add method (append (list 'lambda (reverse argfix)) body)
973                    key argclass))
974     )
975   method)
976
977 ;;; Slot type validation
978 ;;
979 (defun eieio-perform-slot-validation (spec value)
980   "Return non-nil if SPEC does not match VALUE."
981   ;; typep is in cl-macs
982   (or (eq spec t)                       ; t always passes
983       (eq value eieio-unbound)          ; unbound always passes
984       (typep value spec)))
985
986 (defun eieio-validate-slot-value (class field-idx value field)
987   "Make sure that for CLASS referencing FIELD-IDX, that VALUE is valid.
988 Checks the :type specifier.
989 FIELD is the field that is being checked, and is only used when throwing
990 and error."
991   (if eieio-skip-typecheck
992       nil
993     ;; Trim off object IDX junk added in for the object index.
994     (setq field-idx (- field-idx 3))
995     (let ((st (aref (aref (class-v class) class-public-type) field-idx)))
996       (if (not (eieio-perform-slot-validation st value))
997           (signal 'invalid-slot-type (list class field st value))))))
998
999 (defun eieio-validate-class-slot-value (class field-idx value field)
1000   "Make sure that for CLASS referencing FIELD-IDX, that VALUE is valid.
1001 Checks the :type specifier.
1002 FIELD is the field that is being checked, and is only used when throwing
1003 and error."
1004   (if eieio-skip-typecheck
1005       nil
1006     (let ((st (aref (aref (class-v class) class-class-allocation-type)
1007                     field-idx)))
1008       (if (not (eieio-perform-slot-validation st value))
1009           (signal 'invalid-slot-type (list class field st value))))))
1010
1011 (defun eieio-barf-if-slot-unbound (value instance slotname fn)
1012   "Throw a signal if VALUE is a representation of an UNBOUND slot.
1013 INSTANCE is the object being referenced.  SLOTNAME is the offending
1014 slot.  If the slot is ok, return VALUE.
1015 Argument FN is the function calling this verifier."
1016   (if (and (eq value eieio-unbound) (not eieio-skip-typecheck))
1017       (slot-unbound instance (object-class instance) slotname fn)
1018     value))
1019
1020 ;;; Missing types that are useful to me.
1021 ;;
1022 (defun boolean-p (bool)
1023   "Return non-nil if BOOL is nil or t."
1024   (or (null bool) (eq bool t)))
1025
1026 ;;; Get/Set slots in an object.
1027 ;;
1028 (defmacro oref (obj field)
1029   "Retrieve the value stored in OBJ in the slot named by FIELD.
1030 Field is the name of the slot when created by `defclass' or the label
1031 created by the :initarg tag."
1032   `(eieio-oref ,obj (quote ,field)))
1033
1034 (defun eieio-oref (obj field)
1035   "Return the value in OBJ at FIELD in the object vector."
1036   (if (not (or (object-p obj) (class-p obj)))
1037       (signal 'wrong-type-argument (list '(or object-p class-p) obj)))
1038   (if (not (symbolp field))
1039       (signal 'wrong-type-argument (list 'symbolp field)))
1040   (let* ((class (if (class-p obj) obj (aref obj object-class)))
1041          (c (eieio-field-name-index class obj field)))
1042     (if (not c)
1043         ;; It might be missing because it is a :class allocated field.
1044         ;; Lets check that info out.
1045         (if (setq c (eieio-class-field-name-index class field))
1046             ;; Oref that slot.
1047             (aref (aref (class-v class) class-class-allocation-values) c)
1048           ;; The slot-missing method is a cool way of allowing an object author
1049           ;; to intercept missing slot definitions.  Since it is also the LAST
1050           ;; thing called in this fn, it's return value would be retrieved.
1051           (slot-missing obj field 'oref)
1052           ;;(signal 'invalid-slot-name (list (object-name obj) field))
1053           )
1054       (if (not (object-p obj))
1055           (signal 'wrong-type-argument (list 'object-p obj)))
1056       (eieio-barf-if-slot-unbound (aref obj c) obj field 'oref))))
1057
1058 (defalias 'slot-value 'eieio-oref)
1059 (defalias 'set-slot-value 'eieio-oset)
1060
1061 ;; This alias is needed so that functions can be written
1062 ;; for defaults, but still behave like lambdas.
1063 (defmacro lambda-default (&rest cdr)
1064   "The same as `lambda' but is used as a default value in `defclass'.
1065 As such, the form (lambda-default ARGS DOCSTRING INTERACTIVE BODY) is
1066 self quoting.  This macro is meant for the sole purpose of quoting
1067 lambda expressions into class defaults.  Any `lambda-default'
1068 expression is automatically transformed into a `lambda' expression
1069 when copied from the defaults into a new object.  The use of
1070 `oref-default', however, will return a `lambda-default' expression.
1071 CDR is function definition and body."
1072   ;; This definition is copied directly from subr.el for lambda
1073   (list 'function (cons 'lambda-default cdr)))
1074
1075 (put 'lambda-default 'lisp-indent-function 'defun)
1076 (put 'lambda-default 'byte-compile 'byte-compile-lambda-form)
1077
1078 (defmacro oref-default (obj field)
1079   "Gets the default value of OBJ (maybe a class) for FIELD.
1080 The default value is the value installed in a class with the :initform
1081 tag.  FIELD can be the slot name, or the tag specified by the :initarg
1082 tag in the `defclass' call."
1083   `(eieio-oref-default ,obj (quote ,field)))
1084
1085 (defun eieio-oref-default (obj field)
1086   "Does the work for the macro `oref-default' with similar parameters.
1087 Fills in OBJ's FIELD with it's default value."
1088   (if (not (or (object-p obj) (class-p obj))) (signal 'wrong-type-argument (list 'object-p obj)))
1089   (if (not (symbolp field)) (signal 'wrong-type-argument (list 'symbolp field)))
1090   (let* ((cl (if (object-p obj) (aref obj object-class) obj))
1091          (c (eieio-field-name-index cl obj field)))
1092     (if (not c)
1093         ;; It might be missing because it is a :class allocated field.
1094         ;; Lets check that info out.
1095         (if (setq c
1096                   (eieio-class-field-name-index cl field))
1097             ;; Oref that slot.
1098             (aref (aref (class-v cl) class-class-allocation-values)
1099                   c)
1100           (slot-missing obj field 'oref-default)
1101           ;;(signal 'invalid-slot-name (list (class-name cl) field))
1102           )
1103       (eieio-barf-if-slot-unbound
1104        (let ((val (nth (- c 3) (aref (class-v cl) class-public-d))))
1105          (eieio-default-eval-maybe val))
1106        obj cl 'oref-default))))
1107
1108 (defun eieio-default-eval-maybe (val)
1109   "Check VAL, and return what `oref-default' would provide."
1110   ;; check for functions to evaluate
1111   (if (and (listp val) (equal (car val) 'lambda))
1112       (funcall val)
1113     ;; check for quoted things, and unquote them
1114     (if (and (listp val) (eq (car val) 'quote))
1115         (car (cdr val))
1116       ;; return it verbatim
1117       (if (and (listp val) (eq (car val) 'lambda-default))
1118           (let ((s (copy-sequence val)))
1119             (setcar s 'lambda)
1120             s)
1121         val))))
1122
1123 ;;; Object Set macros
1124 ;;
1125 (defmacro oset (obj field value)
1126   "Set the value in OBJ for slot FIELD to VALUE.
1127 FIELD is the slot name as specified in `defclass' or the tag created
1128 with in the :initarg slot.  VALUE can be any Lisp object."
1129   `(eieio-oset ,obj (quote ,field) ,value))
1130
1131 (defun eieio-oset (obj field value)
1132   "Does the work for the macro `oset'.
1133 Fills in OBJ's FIELD with VALUE."
1134   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1135   (if (not (symbolp field)) (signal 'wrong-type-argument (list 'symbolp field)))
1136   (let ((c (eieio-field-name-index (object-class-fast obj) obj field)))
1137     (if (not c)
1138         ;; It might be missing because it is a :class allocated field.
1139         ;; Lets check that info out.
1140         (if (setq c
1141                   (eieio-class-field-name-index (aref obj object-class) field))
1142             ;; Oset that slot.
1143             (progn
1144               (eieio-validate-class-slot-value (object-class-fast obj) c value field)
1145               (aset (aref (class-v (aref obj object-class))
1146                           class-class-allocation-values)
1147                     c value))
1148           ;; See oref for comment on `slot-missing'
1149           (slot-missing obj field 'oset value)
1150           ;;(signal 'invalid-slot-name (list (object-name obj) field))
1151           )
1152       (eieio-validate-slot-value (object-class-fast obj) c value field)
1153       (aset obj c value))))
1154
1155 (defmacro oset-default (class field value)
1156   "Set the default slot in CLASS for FIELD to VALUE.
1157 The default value is usually set with the :initform tag during class
1158 creation.  This allows users to change the default behavior of classes
1159 after they are created."
1160   `(eieio-oset-default ,class (quote ,field) ,value))
1161
1162 (defun eieio-oset-default (class field value)
1163   "Does the work for the macro `oset-default'.
1164 Fills in the default value in CLASS' in FIELD with VALUE."
1165   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1166   (if (not (symbolp field)) (signal 'wrong-type-argument (list 'symbolp field)))
1167   (let* ((scoped-class class)
1168          (c (eieio-field-name-index class nil field)))
1169     (if (not c)
1170         ;; It might be missing because it is a :class allocated field.
1171         ;; Lets check that info out.
1172         (if (setq c (eieio-class-field-name-index class field))
1173             (progn
1174               ;; Oref that slot.
1175               (eieio-validate-class-slot-value class c value field)
1176               (aset (aref (class-v class) class-class-allocation-values) c
1177                     value))
1178           (signal 'invalid-slot-name (list (class-name class) field)))
1179       (eieio-validate-slot-value class c value field)
1180       ;; Set this into the storage for defaults.
1181       (setcar (nthcdr (- c 3) (aref (class-v class) class-public-d))
1182               value)
1183       ;; Take the value, and put it into our cache object.
1184       (eieio-oset (aref (class-v class) class-default-object-cache)
1185                   field value)
1186       )))
1187
1188 ;;; Handy CLOS macros
1189 ;;
1190 (defmacro with-slots (spec-list object &rest body)
1191   "The macro with-slots establishes a lexical environment for
1192 referring to the slots in the instance named by the given
1193 slot-names as though they were variables. Within such a context
1194 the value of the slot can be specified by using its slot name,
1195 as if it were a lexically bound variable. Both setf and setq
1196 can be used to set the value of the slot."
1197   ;; Transform the spec-list into a symbol-macrolet spec-list.
1198   (let ((mappings (mapcar (lambda (entry)
1199                             (let ((var  (if (listp entry) (car entry) entry))
1200                                   (slot (if (listp entry) (cadr entry) entry)))
1201                               (list var `(slot-value ,object ',slot))))
1202                           spec-list)))
1203     (append (list 'symbol-macrolet mappings)
1204             body)))
1205 (put 'with-slots 'lisp-indent-function 2)
1206
1207 \f
1208 ;;; Simple generators, and query functions.  None of these would do
1209 ;;  well embedded into an object.
1210 ;;
1211 (defmacro object-class-fast (obj) "Return the class struct defining OBJ with no check."
1212   `(aref ,obj object-class))
1213   
1214 (defun class-name (class) "Return a Lisp like symbol name for CLASS."
1215   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1216   ;; I think this is supposed to return a symbol, but to me CLASS is a symbol,
1217   ;; and I wanted a string.  Arg!
1218   (format "#<class %s>" (symbol-name class)))
1219
1220 (defun object-name (obj &optional extra)
1221   "Return a Lisp like symbol string for object OBJ.
1222 If EXTRA, include that in the string returned to represent the symbol."
1223   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1224   (format "#<%s %s%s>" (symbol-name (object-class-fast obj))
1225           (aref obj object-name) (or extra "")))
1226
1227 (defun object-name-string (obj) "Return a string which is OBJ's name."
1228   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1229   (aref obj object-name))
1230
1231 (defun object-set-name-string (obj name) "Set the string which is OBJ's NAME."
1232   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1233   (if (not (stringp name)) (signal 'wrong-type-argument (list 'stringp name)))
1234   (aset obj object-name name))
1235
1236 (defun object-class (obj) "Return the class struct defining OBJ."
1237   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1238   (object-class-fast obj))
1239 (defalias 'class-of 'object-class)
1240
1241 (defun object-class-name (obj) "Return a Lisp like symbol name for OBJ's class."
1242   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1243   (class-name (object-class-fast obj)))
1244
1245 (defmacro class-parents-fast (class) "Return parent classes to CLASS with no check."
1246   `(aref (class-v ,class) class-parent))
1247
1248 (defun class-parents (class) "Return parent classes to CLASS.  (overload of variable)."
1249   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1250   (class-parents-fast class))
1251
1252 (defmacro class-children-fast (class) "Return child classes to CLASS with no check."
1253   `(aref (class-v ,class) class-children))
1254
1255 (defun class-children (class) "Return child classses to CLASS."
1256   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1257   (class-children-fast class))
1258
1259 (defmacro class-parent-fast (class) "Return first parent class to CLASS with no check."
1260   `(car (class-parents-fast ,class)))
1261
1262 (defmacro class-parent (class) "Return first parent class to CLASS.  (overload of variable)."
1263   `(car (class-parents ,class)))
1264
1265 (defmacro same-class-fast-p (obj class) "Return t if OBJ is of class-type CLASS with no error checking."
1266   `(eq (aref ,obj object-class) ,class))
1267
1268 (defun same-class-p (obj class) "Return t if OBJ is of class-type CLASS."
1269   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1270   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1271   (same-class-fast-p obj class))
1272
1273 (defun object-of-class-p (obj class)
1274   "Return non-nil if OBJ is an instance of CLASS or CLASS' subclasses."
1275   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1276   ;; class will be checked one layer down
1277   (child-of-class-p (aref obj object-class) class))
1278 ;; Backwards compatibility
1279 (defalias 'obj-of-class-p 'object-of-class-p)
1280
1281 (defun child-of-class-p (child class)
1282   "If CHILD class is a subclass of CLASS."
1283   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1284   (if (not (class-p child)) (signal 'wrong-type-argument (list 'class-p child)))
1285   (let ((p nil))
1286     (while (and child (not (eq child class)))
1287       (setq p (append p (aref (class-v child) class-parent))
1288             child (car p)
1289             p (cdr p)))
1290     (if child t)))
1291
1292 (defun object-slots (obj) "List of slots available in OBJ."
1293   (if (not (object-p obj)) (signal 'wrong-type-argument (list 'object-p obj)))
1294   (aref (class-v (object-class-fast obj)) class-public-a))
1295
1296 (defun class-slot-initarg (class slot) "Fetch from CLASS, SLOT's :initarg."
1297   (if (not (class-p class)) (signal 'wrong-type-argument (list 'class-p class)))
1298   (let ((ia (aref (class-v class) class-initarg-tuples))
1299         (f nil))
1300     (while (and ia (not f))
1301       (if (eq (cdr (car ia)) slot)
1302           (setq f (car (car ia))))
1303       (setq ia (cdr ia)))
1304     f))
1305
1306 ;;; CLOS queries into classes and slots
1307 ;;
1308 (defun slot-boundp (object slot)
1309   "Non-nil if OBJECT's SLOT is bound.
1310 Setting a slot's value makes it bound.  Calling `slot-makeunbound' will
1311 make a slot unbound.
1312 OBJECT can be an instance or a class."
1313   ;; Skip typechecking while retrieving this value.
1314   (let ((eieio-skip-typecheck t))
1315     ;; Return nil if the magic symbol is in there.
1316     (if (object-p object)
1317         (if (eq (eieio-oref object slot) eieio-unbound) nil t)
1318       (if (class-p object)
1319           (if (eq (eieio-oref-default object slot) eieio-unbound) nil t)
1320         (signal 'wrong-type-argument (list 'object-p object))))))
1321
1322 (defun slot-makeunbound (object slot)
1323   "In OBJECT, make SLOT unbound."
1324   (eieio-oset object slot eieio-unbound))
1325
1326 (defun slot-exists-p (object-or-class slot)
1327   "Non-nil if OBJECT-OR-CLASS has SLOT."
1328   (let ((cv (class-v (cond ((object-p object-or-class)
1329                             (object-class object-or-class))
1330                            ((class-p object-or-class)
1331                             object-or-class))
1332                      )))
1333     (or (memq slot (aref cv class-public-a))
1334         (memq slot (aref cv class-class-allocation-a)))
1335     ))
1336
1337 (defun find-class (symbol &optional errorp)
1338   "Return the class that SYMBOL represents. (CLOS function)
1339 If there is no class, nil is returned if ERRORP is nil."
1340   (if (not (class-p symbol))
1341       (if errorp (signal 'wrong-type-argument (list 'class-p symbol))
1342         nil)
1343     (class-v symbol)))
1344
1345 ;;; Slightly more complex utility functions for objects
1346 ;;
1347 (defun object-assoc (key field list)
1348   "Return non-nil if KEY is `equal' to the FIELD of the car of objects in LIST.
1349 The value is actually the element of LIST whose field equals KEY."
1350   (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
1351   (while (and list (not (condition-case nil
1352                             ;; This prevents errors for missing slots.
1353                             (equal key (eieio-oref (car list) field))
1354                           (error nil))))
1355     (setq list (cdr list)))
1356   (car list))
1357
1358 (defun object-assoc-list (field list)
1359   "Return an association list with the contents of FIELD as the key element.
1360 LIST must be a list of objects with FIELD in it.
1361 This is useful when you need to do completing read on an object group."
1362   (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
1363   (let ((assoclist nil))
1364     (while list
1365       (setq assoclist (cons (cons (eieio-oref (car list) field)
1366                                   (car list))
1367                             assoclist))
1368       (setq list (cdr list)))
1369     (nreverse assoclist)))
1370
1371 (defun object-assoc-list-safe (field list)
1372   "Return an association list with the contents of FIELD as the key element.
1373 LIST must be a list of objects, but those objects do not need to have
1374 FIELD in it.  If it does not, then that element is left out of the association
1375 list."
1376   (if (not (listp list)) (signal 'wrong-type-argument (list 'listp list)))
1377   (let ((assoclist nil))
1378     (while list
1379       (if (slot-exists-p (car list) field)
1380           (setq assoclist (cons (cons (eieio-oref (car list) field)
1381                                       (car list))
1382                                 assoclist)))
1383       (setq list (cdr list)))
1384     (nreverse assoclist)))
1385
1386 (defun object-add-to-list (object slot item &optional append)
1387   "In OBJECT's SLOT, add ITEM to the pre-existing list of elements.
1388 Optional argument APPEND indicates we need to append to the list.
1389 If ITEM already exists in the list in SLOT, then it is not added.
1390 Comparison is done with `equal' through the `member' function call.
1391 If SLOT is unbound, bind it to the list containing ITEM."
1392   (let (ov)
1393     ;; Find the originating list.
1394     (if (not (slot-boundp object slot))
1395         (setq ov (list item))
1396       (setq ov (eieio-oref object slot))
1397       ;; turn it into a list.
1398       (unless (listp ov)
1399         (setq ov (list ov)))
1400       ;; Do the combination
1401       (if (not (member item ov))
1402           (setq ov
1403                 (if append
1404                     (append ov (list item))
1405                   (cons item ov)))))
1406     ;; Set back into the slot.
1407     (eieio-oset object slot ov)))
1408
1409 (defun object-remove-from-list (object slot item)
1410   "In OBJECT's SLOT, remove occurrences ITEM.
1411 If ITEM already exists in the list in SLOT, then it is not added.
1412 Comparison is done with `equal' through the `delete' function call.
1413 If SLOT is unbound, do nothing."
1414   (if (not (slot-boundp object slot))
1415       nil
1416     (eieio-oset object slot (delete item (eieio-oref object slot)))))
1417 \f
1418 ;;; EIEIO internal search functions
1419 ;;
1420 (defun eieio-field-originating-class-p (start-class field)
1421   "Return Non-nil if START-CLASS is the first class to define FIELD.
1422 This is for testing if `scoped-class' is the class that defines FIELD
1423 so that we can protect private slots."
1424   (let ((par (class-parents start-class))
1425         (ret t))
1426     (if (not par)
1427         t
1428       (while (and par ret)
1429         (if (intern-soft (symbol-name field)
1430                          (aref (class-v (car par))
1431                                class-symbol-obarray))
1432             (setq ret nil))
1433         (setq par (cdr par)))
1434       ret)))
1435
1436 (defun eieio-field-name-index (class obj field)
1437   "In CLASS for OBJ find the index of the named FIELD.
1438 The field is a symbol which is installed in CLASS by the `defclass'
1439 call.  OBJ can be nil, but if it is an object, and the slot in question
1440 is protected, access will be allowed if obj is a child of the currently
1441 `scoped-class'.
1442 If FIELD is the value created with :initarg instead,
1443 reverse-lookup that name, and recurse with the associated slot value."
1444   ;; Removed checks to outside this call
1445   (let* ((fsym (intern-soft (symbol-name field)
1446                             (aref (class-v class)
1447                                   class-symbol-obarray)))
1448          (fsi (if (symbolp fsym) (symbol-value fsym) nil)))
1449     (if (integerp fsi)
1450         (cond
1451          ((not (get fsym 'protection))
1452           (+ 3 fsi))
1453          ((and (eq (get fsym 'protection) 'protected)
1454                scoped-class
1455                (or (child-of-class-p class scoped-class)
1456                    (and (object-p obj)
1457                         (child-of-class-p class (object-class obj)))))
1458           (+ 3 fsi))
1459          ((and (eq (get fsym 'protection) 'private)
1460                (or (and scoped-class
1461                         (eieio-field-originating-class-p scoped-class field))
1462                    eieio-initializing-object))
1463           (+ 3 fsi))
1464          (t nil))
1465       (let ((fn (eieio-initarg-to-attribute class field)))
1466         (if fn (eieio-field-name-index class obj fn) nil)))))
1467
1468 (defun eieio-class-field-name-index (class field)
1469   "In CLASS find the index of the named FIELD.
1470 The field is a symbol which is installed in CLASS by the `defclass'
1471 call.  If FIELD is the value created with :initarg instead,
1472 reverse-lookup that name, and recurse with the associated slot value."
1473   ;; This will happen less often, and with fewer slots.  Do this the
1474   ;; storage cheap way.
1475   (let* ((a (aref (class-v class) class-class-allocation-a))
1476          (l1 (length a))
1477          (af (memq field a))
1478          (l2 (length af)))
1479     ;; Slot # is length of the total list, minus the remaining list of
1480     ;; the found slot.
1481     (if af (- l1 l2))))
1482 \f
1483 ;;; CLOS generics internal function handling
1484 ;;
1485 (defvar eieio-generic-call-methodname nil
1486   "When using `call-next-method', provides a context on how to do it.")
1487 (defvar eieio-generic-call-arglst nil
1488   "When using `call-next-method', provides a context for parameters.")
1489 (defvar eieio-generic-call-key nil
1490   "When using `call-next-method', provides a context for the current key.
1491 Keys are a number representing :BEFORE, :PRIMARY, and :AFTER methods.")
1492 (defvar eieio-generic-call-next-method-list nil
1493   "When executing a PRIMARY or STATIC method, track the 'next-method'.
1494 During executions, the list is first generated, then as each next method
1495 is called, the next method is popped off the stack.")
1496
1497 (defun eieio-generic-call (method args)
1498   "Call METHOD with ARGS.
1499 ARGS provides the context on which implementation to use.
1500 This should only be called from a generic function."
1501   ;; We must expand our arguments first as they are always
1502   ;; passed in as quoted symbols
1503   (let ((newargs nil) (mclass nil)  (lambdas nil) (tlambdas nil) (keys nil)
1504         (eieio-generic-call-methodname method)
1505         (eieio-generic-call-arglst args)
1506         (firstarg nil)
1507         (primarymethodlist nil))
1508     ;; get a copy
1509     (setq newargs args
1510           firstarg (car newargs))
1511     ;; Is the class passed in autoloaded?
1512     ;; Since class names are also constructors, they can be autoloaded
1513     ;; via the autoload command.  Check for this, and load them in.
1514     ;; It's ok if it doesn't turn out to be a class.  Probably want that
1515     ;; function loaded anyway.
1516     (if (and (symbolp firstarg)
1517              (fboundp firstarg)
1518              (listp (symbol-function firstarg))
1519              (eq 'autoload (car (symbol-function firstarg))))
1520         (load (nth 1 (symbol-function firstarg))))
1521     ;; lookup the forms to use
1522     (cond ((object-p firstarg)
1523            (setq mclass (object-class-fast firstarg)))
1524           ((class-p firstarg)
1525            (setq mclass firstarg
1526                  )))
1527     ;; Now create a list in reverse order of all the calls we have
1528     ;; make in order to successfully do this right.  Rules:
1529     ;; 1) Only call generics if scoped-class is not defined
1530     ;;    This prevents multiple calls in the case of recursion
1531     ;; 2) Only call static if this is a static method.
1532     ;; 3) Only call specifics if the definition allows for them.
1533     ;; 4) Call in order based on :BEFORE, :PRIMARY, and :AFTER
1534     (when (object-p firstarg)
1535       ;; Non-static calls do all this stuff.
1536
1537       ;; :AFTER methods
1538       (setq tlambdas
1539             (if mclass
1540                 (eieiomt-method-list method method-after mclass)
1541               (list (eieio-generic-form method method-after nil)))
1542             ;;(or (and mclass (eieio-generic-form method method-after mclass))
1543             ;;  (eieio-generic-form method method-after nil))
1544             )
1545       (setq lambdas (append tlambdas lambdas)
1546             keys (append (make-list (length tlambdas) method-after) keys))
1547       
1548       ;; :PRIMARY methods
1549       (setq tlambdas
1550             (or (and mclass (eieio-generic-form method method-primary mclass))
1551                 (eieio-generic-form method method-primary nil)))
1552       (when tlambdas
1553         (setq lambdas (cons tlambdas lambdas)
1554               keys (cons method-primary keys)
1555               primarymethodlist
1556               (eieiomt-method-list method method-primary mclass)))
1557
1558       ;; :BEFORE methods
1559       (setq tlambdas
1560             (if mclass
1561                 (eieiomt-method-list method method-before mclass)
1562               (list (eieio-generic-form method method-before nil)))
1563             ;;(or (and mclass (eieio-generic-form method method-before mclass))
1564             ;;  (eieio-generic-form method method-before nil))
1565             )
1566       (setq lambdas (append tlambdas lambdas)
1567             keys (append (make-list (length tlambdas) method-before) keys))
1568       )
1569
1570     ;; If there were no methods found, then there could be :STATIC methods.
1571     (when (not lambdas)
1572       (setq tlambdas
1573             (eieio-generic-form method method-static mclass))
1574       (setq lambdas (cons tlambdas lambdas)
1575             keys (cons method-static keys)
1576             primarymethodlist  ;; Re-use even with bad name here
1577             (eieiomt-method-list method method-static mclass)))
1578
1579     ;; Now loop through all occurances forms which we must execute
1580     ;; (which are happily sorted now) and execute them all!
1581     (let ((rval nil) (lastval nil) (rvalever nil) (found nil))
1582       (while lambdas
1583         (if (car lambdas)
1584             (let* ((scoped-class (cdr (car lambdas)))
1585                    (eieio-generic-call-key (car keys))
1586                    (has-return-val
1587                     (or (= eieio-generic-call-key method-primary)
1588                         (= eieio-generic-call-key method-static)))
1589                    (eieio-generic-call-next-method-list
1590                     ;; Use the cdr, as the first element is the fcn
1591                     ;; we are calling right now.
1592                     (when has-return-val (cdr primarymethodlist)))
1593                    )
1594               (setq found t)
1595               ;;(setq rval (apply (car (car lambdas)) newargs))
1596               (setq lastval (apply (car (car lambdas)) newargs))
1597               (when has-return-val
1598                 (setq rval lastval
1599                       rvalever t))
1600               ))
1601         (setq lambdas (cdr lambdas)
1602               keys (cdr keys)))
1603       (if (not found)
1604           (if (object-p (car args))
1605               (setq rval (no-applicable-method (car args) method)
1606                     rvalever t)
1607             (signal
1608              'no-method-definition
1609              (list method args))))
1610       ;; Right Here... it could be that lastval is returned when
1611       ;; rvalever is nil.  Is that right?
1612       rval)))
1613
1614 (defun eieiomt-method-list (method key class)
1615   "Return an alist list of methods lambdas.
1616 METHOD is the method name.
1617 KEY represents either :BEFORE, or :AFTER methods.
1618 CLASS is the starting class to search from in the method tree."
1619   (let ((lambdas nil)
1620         (mclass (list class)))
1621     (while mclass
1622       (when (car mclass)
1623         ;; lookup the form to use for the PRIMARY object for the next level
1624         (let ((tmpl (eieio-generic-form method key (car mclass))))
1625           (when (or (not lambdas) 
1626                     ;; This prevents duplicates coming out of the
1627                     ;; class method optimizer.  Perhaps we should
1628                     ;; just not optimize before/afters?
1629                     (not (eq (car tmpl) (car (car lambdas)))))
1630             (setq lambdas (cons tmpl lambdas))
1631             (if (null (car lambdas))
1632                 (setq lambdas (cdr lambdas))))))
1633       ;; Add new classes to mclass
1634       (setq mclass (append (cdr mclass) (eieiomt-next (car mclass))))
1635       )
1636     (if (eq key method-after)
1637         lambdas
1638       (nreverse lambdas))))
1639
1640 (defun next-method-p ()
1641   "Return a list of lambdas which qualify as the `next-method'."
1642   eieio-generic-call-next-method-list)
1643
1644 (defun call-next-method (&rest replacement-args)
1645   "Call the next logical method from another method.
1646 The next logical method is the method belong to the parent class of
1647 the currently running method.  If REPLACEMENT-ARGS is non-nil, then
1648 use them instead of `eieio-generic-call-arglst'.  The generic arg list
1649 are the arguments passed in at the top level."
1650   (if (not scoped-class)
1651       (error "Call-next-method not called within a class specific method"))
1652   (if (and (/= eieio-generic-call-key method-primary)
1653            (/= eieio-generic-call-key method-static))
1654       (error "Cannot `call-next-method' except in :PRIMARY or :STATIC methods")
1655     )
1656   (let ((newargs (or replacement-args eieio-generic-call-arglst))
1657         (next (car eieio-generic-call-next-method-list))
1658         (returnval nil)
1659         )
1660     (if (or (not next) (not (car next)))
1661         (no-next-method (car newargs))
1662       (let* ((eieio-generic-call-next-method-list
1663               (cdr eieio-generic-call-next-method-list))
1664              (scoped-class (cdr next))
1665              (fcn (car next))
1666              )
1667         (apply fcn newargs)
1668         ))))
1669 \f
1670 ;;;
1671 ;; eieio-method-tree : eieiomt-
1672 ;;
1673 ;; Stored as eieio-method-tree in property list of a generic method
1674 ;;
1675 ;; (eieio-method-tree . [BEFORE PRIMARY AFTER
1676 ;;                       genericBEFORE genericPRIMARY genericAFTER])
1677 ;; and
1678 ;; (eieio-method-obarray . [BEFORE PRIMARY AFTER
1679 ;;                          genericBEFORE genericPRIMARY genericAFTER])
1680 ;;    where the association is a vector.
1681 ;;    (aref 0  -- all static methods.
1682 ;;    (aref 1  -- all methods classified as :BEFORE
1683 ;;    (aref 2  -- all methods classified as :PRIMARY
1684 ;;    (aref 3  -- all methods classified as :AFTER
1685 ;;    (aref 4  -- a generic classified as :BEFORE
1686 ;;    (aref 5  -- a generic classified as :PRIMARY
1687 ;;    (aref 6  -- a generic classified as :AFTER
1688 ;;
1689 (defvar eieiomt-optimizing-obarray nil
1690   "While mapping atoms, this contain the obarray being optimized.")
1691
1692 (defun eieiomt-install (method-name)
1693   "Install the method tree, and obarray onto METHOD-NAME.
1694 Do not do the work if they already exist."
1695   (let ((emtv (get method-name 'eieio-method-tree))
1696         (emto (get method-name 'eieio-method-obarray)))
1697     (if (or (not emtv) (not emto))
1698         (progn
1699           (setq emtv (put method-name 'eieio-method-tree
1700                           (make-vector method-num-fields nil))
1701                 emto (put method-name 'eieio-method-obarray
1702                           (make-vector method-num-fields nil)))
1703           (aset emto 0 (make-vector 11 0))
1704           (aset emto 1 (make-vector 11 0))
1705           (aset emto 2 (make-vector 41 0))
1706           (aset emto 3 (make-vector 11 0))
1707           ))))
1708
1709 (defun eieiomt-add (method-name method key class)
1710   "Add to METHOD-NAME the forms METHOD in a call position KEY for CLASS.
1711 METHOD-NAME is the name created by a call to `defgeneric'.
1712 METHOD are the forms for a given implementation.
1713 KEY is an integer (see comment in eieio.el near this function) which
1714 is associated with the :STATIC :BEFORE :PRIMARY and :AFTER tags.
1715 It also indicates if CLASS is defined or not.
1716 CLASS is the class this method is associated with."
1717   (if (or (> key method-num-fields) (< key 0))
1718       (error "Eieiomt-add: method key error!"))
1719   (let ((emtv (get method-name 'eieio-method-tree))
1720         (emto (get method-name 'eieio-method-obarray)))
1721     ;; Make sure the method tables are available.
1722     (if (or (not emtv) (not emto))
1723         (error "Programmer error: eieiomt-add"))
1724     ;; only add new cells on if it doesn't already exist!
1725     (if (assq class (aref emtv key))
1726         (setcdr (assq class (aref emtv key)) method)
1727       (aset emtv key (cons (cons class method) (aref emtv key))))
1728     ;; Add function definition into newly created symbol, and store
1729     ;; said symbol in the correct obarray, otherwise use the
1730     ;; other array to keep this stuff
1731     (if (< key method-num-lists)
1732         (let ((nsym (intern (symbol-name class) (aref emto key))))
1733           (fset nsym method)))
1734     ;; Now optimize the entire obarray
1735     (if (< key method-num-lists)
1736         (let ((eieiomt-optimizing-obarray (aref emto key)))
1737           (mapatoms 'eieiomt-sym-optimize eieiomt-optimizing-obarray)))
1738     ))
1739
1740 (defun eieiomt-next (class)
1741   "Return the next parent class for CLASS.
1742 If CLASS is a superclass, return variable `eieio-default-superclass'.  If CLASS
1743 is variable `eieio-default-superclass' then return nil.  This is different from
1744 function `class-parent' as class parent returns nil for superclasses.  This
1745 function performs no type checking!"
1746   ;; No type-checking because all calls are made from functions which
1747   ;; are safe and do checking for us.
1748   (or (class-parents-fast class)
1749       (if (eq class 'eieio-default-superclass)
1750           nil
1751         '(eieio-default-superclass))))
1752
1753 (defun eieiomt-sym-optimize (s)
1754   "Find the next class above S which has a function body for the optimizer."
1755   ;; (message "Optimizing %S" s)
1756   (let ((es (intern-soft (symbol-name s))) ;external symbol of class
1757         (ov nil)
1758         (cont t))
1759     ;; This converts ES from a single symbol to a list of parent classes.
1760     (setq es (eieiomt-next es))
1761     ;; Loop over ES, then it's children individually.
1762     ;; We can have multiple hits only at one level of the parent tree.
1763     (while (and es cont)
1764       (setq ov (intern-soft (symbol-name (car es)) eieiomt-optimizing-obarray))
1765       (if (fboundp ov)
1766           (progn
1767             (set s ov)                  ;store ov as our next symbol
1768             (setq cont nil))
1769         (setq es (append (cdr es) (eieiomt-next (car es))))))
1770     ;; If there is no nearest call, then set our value to nil
1771     (if (not es) (set s nil))
1772     ))
1773
1774 (defun eieio-generic-form (method key class)
1775  "Return the lambda form belonging to METHOD using KEY based upon CLASS.
1776 If CLASS is not a class then use `generic' instead.  If class has no
1777 form, but has a parent class, then trace to that parent class.  The
1778 first time a form is requested from a symbol, an optimized path is
1779 memoized for future faster use."
1780  (let ((emto (aref (get method 'eieio-method-obarray)
1781                    (if class key (+ key 3)))))
1782    (if (class-p class)
1783        ;; 1) find our symbol
1784        (let ((cs (intern-soft (symbol-name class) emto)))
1785          (if (not cs)
1786              ;; 2) If there isn't one, then make one.
1787              ;;    This can be slow since it only occurs once
1788              (progn
1789                (setq cs (intern (symbol-name class) emto))
1790                ;; 2.1) Cache it's nearest neighbor with a quick optimize
1791                ;;      which should only occur once for this call ever
1792                (let ((eieiomt-optimizing-obarray emto))
1793                  (eieiomt-sym-optimize cs))))
1794          ;; 3) If it's bound return this one.
1795          (if (fboundp  cs)
1796              (cons cs (aref (class-v class) class-symbol))
1797            ;; 4) If it's not bound then this variable knows something
1798            (if (symbol-value cs)
1799                (progn
1800                  ;; 4.1) This symbol holds the next class in it's value
1801                  (setq class (symbol-value cs)
1802                        cs (intern-soft (symbol-name class) emto))
1803                  ;; 4.2) The optimizer should always have chosen a
1804                  ;;      function-symbol
1805                  ;;(if (fboundp cs)
1806                  (cons cs (aref (class-v (intern (symbol-name class)))
1807                                 class-symbol))
1808                    ;;(error "EIEIO optimizer: erratic data loss!"))
1809                  )
1810                ;; There never will be a funcall...
1811                nil)))
1812      ;; for a generic call, what is a list, is the function body we want.
1813      (let ((emtl (aref (get method 'eieio-method-tree)
1814                        (if class key (+ key 3)))))
1815        (if emtl
1816            ;; The car of EMTL is supposed to be a class, which in this
1817            ;; case is nil, so skip it.
1818            (cons (cdr (car emtl)) nil)
1819          nil)))))
1820
1821 ;;;
1822 ;; Way to assign fields based on a list.  Used for constructors, or
1823 ;; even resetting an object at run-time
1824 ;;
1825 (defun eieio-set-defaults (obj &optional set-all)
1826   "Take object OBJ, and reset all fields to their defaults.
1827 If SET-ALL is non-nil, then when a default is nil, that value is
1828 reset.  If SET-ALL is nil, the fields are only reset if the default is
1829 not nil."
1830   (let ((scoped-class (aref obj object-class))
1831         (eieio-initializing-object t)
1832         (pub (aref (class-v (aref obj object-class)) class-public-a)))
1833     (while pub
1834       (let ((df (eieio-oref-default obj (car pub))))
1835         (if (and (listp df) (eq (car df) 'lambda-default))
1836             (progn
1837               (setq df (copy-sequence df))
1838               (setcar df 'lambda)))
1839         (if (or df set-all)
1840             (eieio-oset obj (car pub) df)))
1841       (setq pub (cdr pub)))))
1842
1843 (defun eieio-initarg-to-attribute (class initarg)
1844   "For CLASS, convert INITARG to the actual attribute name.
1845 If there is no translation, pass it in directly (so we can cheat if
1846 need be.. May remove that later...)"
1847   (let ((tuple (assoc initarg (aref (class-v class) class-initarg-tuples))))
1848     (if tuple
1849         (cdr tuple)
1850       nil)))
1851
1852 (defun eieio-attribute-to-initarg (class attribute)
1853   "In CLASS, convert the ATTRIBUTE into the corresponding init argument tag.
1854 This is usually a symbol that starts with `:'."
1855   (let ((tuple (rassoc attribute (aref (class-v class) class-initarg-tuples))))
1856     (if tuple
1857         (car tuple)
1858       nil)))
1859
1860 \f
1861 ;;; Here are some special types of errors
1862 ;;
1863 (intern "no-method-definition")
1864 (put 'no-method-definition 'error-conditions '(no-method-definition error))
1865 (put 'no-method-definition 'error-message "No method definition")
1866
1867 (intern "no-next-method")
1868 (put 'no-next-method 'error-conditions '(no-next-method error))
1869 (put 'no-next-method 'error-message "No next method")
1870
1871 (intern "invalid-slot-name")
1872 (put 'invalid-slot-name 'error-conditions '(invalid-slot-name error))
1873 (put 'invalid-slot-name 'error-message "Invalid slot name")
1874
1875 (intern "invalid-slot-type")
1876 (put 'invalid-slot-type 'error-conditions '(invalid-slot-type error nil))
1877 (put 'invalid-slot-type 'error-message "Invalid slot type")
1878
1879 (intern "unbound-slot")
1880 (put 'unbound-slot 'error-conditions '(unbound-slot error nil))
1881 (put 'unbound-slot 'error-message "Unbound slot")
1882
1883 ;;; Here are some CLOS items that need the CL package
1884 ;;
1885
1886 (defsetf slot-value (obj field) (store) (list 'eieio-oset obj field store))
1887 (defsetf eieio-oref (obj field) (store) (list 'eieio-oset obj field store))
1888
1889 ;; The below setf method was written by Arnd Kohrs <kohrs@acm.org>
1890 (define-setf-method oref (obj field) 
1891   (let ((obj-temp (gensym)) 
1892         (field-temp (gensym)) 
1893         (store-temp (gensym))) 
1894     (list (list obj-temp field-temp) 
1895           (list obj `(quote ,field)) 
1896           (list store-temp) 
1897           (list 'set-slot-value obj-temp field-temp
1898                 store-temp)
1899           (list 'slot-value obj-temp field-temp))))
1900
1901 \f
1902 ;;;
1903 ;; We want all objects created by EIEIO to have some default set of
1904 ;; behaviours so we can create object utilities, and allow various
1905 ;; types of error checking.  To do this, create the default EIEIO
1906 ;; class, and when no parent class is specified, use this as the
1907 ;; default.  (But don't store it in the other classes as the default,
1908 ;; allowing for transparent support.)
1909 ;;
1910
1911 (defclass eieio-default-superclass nil
1912   nil
1913   "Default class used as parent class for superclasses.
1914 Its fields are automatically adopted by such superclasses but not
1915 stored in the `parent' field.  When searching for attributes or
1916 methods, when the last parent is found, the search will recurse to
1917 this class."
1918   :abstract t)
1919
1920 (defalias 'standard-class 'eieio-default-superclass)
1921
1922 (defmethod constructor :STATIC
1923   ((class eieio-default-superclass) newname &rest fields)
1924   "Default constructor for CLASS `eieio-defualt-superclass'.
1925 NEWNAME is the name to be given to the constructed object.
1926 FIELDS are the initialization fields used by `shared-initialize'.
1927 This static method is called when an object is constructed.
1928 It allocates the vector used to represent an EIEIO object, and then
1929 calls `shared-initialize' on that object."
1930   (let* ((new-object (copy-sequence (aref (class-v class)
1931                                           class-default-object-cache))))
1932     ;; Update the name for the newly created object.
1933     (aset new-object object-name newname)
1934     ;; Call the initialize method on the new object with the fields
1935     ;; that were passed down to us.
1936     (initialize-instance new-object fields)
1937     ;; Return the created object.
1938     new-object))
1939
1940 (defmethod shared-initialize ((obj eieio-default-superclass) fields)
1941   "Set fields of OBJ with FIELDS which is a list of name/value pairs.
1942 Called from the constructor routine."
1943   (let ((scoped-class (aref obj object-class)))
1944     (while fields
1945       (let ((rn (eieio-initarg-to-attribute (object-class-fast obj)
1946                                             (car fields))))
1947         (if (not rn)
1948             (slot-missing obj (car fields) 'oset (car (cdr fields))))
1949         (eieio-oset obj rn (car (cdr fields))))
1950       (setq fields (cdr (cdr fields))))))
1951
1952 (defmethod initialize-instance ((this eieio-default-superclass)
1953                                 &optional fields)
1954     "Constructs the new object THIS based on FIELDS.
1955 FIELDS is a tagged list where odd numbered elements are tags, and
1956 even numbered elements are the values to store in the tagged slot.  If
1957 you overload the `initialize-instance', there you will need to call
1958 `shared-initialize' yourself, or you can call `call-next-method' to
1959 have this constructor called automatically.  If these steps are not
1960 taken, then new objects of your class will not have their values
1961 dynamically set from FIELDS."
1962     ;; First, see if any of our defaults are `lambda', and
1963     ;; re-evaluate them and apply the value to our slots.
1964     (let* ((scoped-class (class-v (aref this object-class)))
1965            (slot (aref scoped-class class-public-a))
1966            (defaults (aref scoped-class class-public-d)))
1967       (while slot
1968         (if (and (listp (car defaults))
1969                  (eq 'lambda (car (car defaults))))
1970             (eieio-oset this (car slot) (funcall (car defaults))))
1971         (setq slot (cdr slot)
1972               defaults (cdr defaults))))
1973     ;; Shared initialize will parse our fields for us.
1974     (shared-initialize this fields))
1975
1976 (defmethod slot-missing ((object eieio-default-superclass) slot-name
1977                          operation &optional new-value)
1978   "Slot missing is invoked when an attempt to access a slot in OBJECT fails.
1979 SLOT-NAME is the name of the failed slot, OPERATION is the type of access
1980 that was requested, and optional NEW-VALUE is the value that was desired
1981 to be set."
1982   (signal 'invalid-slot-name (list (object-name object)
1983                                    slot-name)))
1984
1985 (defmethod slot-unbound ((object eieio-default-superclass)
1986                          class slot-name fn)
1987   "Slot unbound is invoked during an attempt to reference an unbound slot.
1988 OBJECT is the instance of the object being reference.  CLASS is the
1989 class of OBJECT, and SLOT-NAME is the offending slot.  This function
1990 throws the signal `unbound-slot'.  You can overload this function and
1991 return the value to use in place of the unbound value.
1992 Argument FN is the function signaling this error.
1993 Use `slot-boundp' to determine if a slot is bound or not."
1994   (signal 'unbound-slot (list (class-name class) (object-name object)
1995                               slot-name fn)))
1996
1997 (defmethod no-applicable-method ((object eieio-default-superclass)
1998                                  method)
1999   "Called if there are no implementations for OBJECT in METHOD.
2000 OBJECT is the object which has no method implementation."
2001   (signal 'no-method-definition (list method (object-name object)))
2002   )
2003
2004 (defmethod no-next-method ((object eieio-default-superclass)
2005                            &rest args)
2006   "Called from `call-next-method' when no additional methods are available.
2007 OBJECT is othe object being called on `call-next-method'.
2008 ARGS are the  arguments it is called by.
2009 This method throws `no-next-method' by default.  Override this
2010 method to not throw an error, and it's return value becomes the
2011 return value of `call-next-method'."
2012   (signal 'no-next-method (list (object-name object) args))
2013 )
2014
2015 (defmethod clone ((obj eieio-default-superclass) &rest params)
2016   "Make a deep copy of OBJ, and then apply PARAMS.
2017 PARAMS is a parameter list of the same form as INITIALIZE-INSTANCE
2018 which are applied to change the object.  When overloading `clone', be
2019 sure to call `call-next-method' first and modify the returned object."
2020   (let ((nobj (copy-sequence obj))
2021         (nm (aref obj object-name))
2022         (passname (and params (stringp (car params))))
2023         (num 1))
2024     (if params (shared-initialize nobj (if passname (cdr params) params)))
2025     (if (not passname)
2026         (save-match-data
2027           (if (string-match "-\\([0-9]+\\)" nm)
2028               (setq num (1+ (string-to-number (match-string 1 nm)))
2029                     nm (substring nm 0 (match-beginning 0))))
2030           (aset nobj object-name (concat nm "-" (int-to-string num))))
2031       (aset nobj object-name (car params)))
2032     nobj))
2033
2034 (defmethod destructor ((this eieio-default-superclass) &rest params)
2035   "Destructor for cleaning up any dynamic links to our object.
2036 Argument THIS is the object being destroyed.  PARAMS are additional
2037 ignored parameters."
2038   ;; No cleanup... yet.
2039   )
2040
2041 (defmethod object-print ((this eieio-default-superclass) &rest strings)
2042   "Pretty printer for object THIS.  Call function `object-name' with STRINGS.
2043 The default method for printing object THIS is to use the
2044 function `object-name'.  At times it could be useful to put a summary
2045 of the object into the default #<notation> string.  Overload this
2046 function to allow summaries of your objects to be used by eieio
2047 browsing tools.  The optional parameter STRINGS is for additional
2048 summary parts to put into the name string.  When passing in extra
2049 strings from child classes, always remember to prepend a space."
2050   (object-name this (apply 'concat strings)))
2051
2052 (defvar eieio-print-depth 0
2053   "When printing, keep track of the current indentation depth.")
2054
2055 (defmethod object-write ((this eieio-default-superclass) &optional comment)
2056   "Write object THIS out to the current stream.
2057 This writes out the vector version of this object.  Complex and recursive
2058 object are discouraged from being written.
2059   If optional COMMENT is non-nil, include comments when outputting
2060 this object."
2061   (when comment
2062     (princ ";; Object ")
2063     (princ (object-name-string this))
2064     (princ "\n")
2065     (princ comment)
2066     (princ "\n"))
2067   (let* ((cl (object-class this))
2068          (cv (class-v cl)))
2069     ;; Now output readable lisp to recreate this object
2070     ;; It should look like this:
2071     ;; (<constructor> <name> <slot> <field> ... )
2072     ;; Each slot's field is writen using its :writer.
2073     (princ (make-string (* eieio-print-depth 2) ? ))
2074     (princ "(")
2075     (princ (symbol-name (class-constructor (object-class this))))
2076     (princ " \"")
2077     (princ (object-name-string this))
2078     (princ "\"\n")
2079     ;; Loop over all the public slots
2080     (let ((publa (aref cv class-public-a))
2081           (publd (aref cv class-public-d))
2082           (eieio-print-depth (1+ eieio-print-depth)))
2083       (while publa
2084         (when (slot-boundp this (car publa))
2085           (let ((i (class-slot-initarg cl (car publa)))
2086                 (v (eieio-oref this (car publa))))
2087             (unless (or (not i) (equal v (car publd)))
2088               (princ (make-string (* eieio-print-depth 2) ? ))
2089               (princ (symbol-name i))
2090               (princ " ")
2091               (eieio-override-prin1 v)
2092               (princ "\n"))))
2093         (setq publa (cdr publa) publd (cdr publd)))
2094       (princ (make-string (* eieio-print-depth 2) ? )))
2095     (princ ")\n")))
2096
2097 (defun eieio-override-prin1 (thing)
2098   "Perform a prin1 on THING taking advantage of object knowledge."
2099   (cond ((object-p thing)
2100          (object-write thing))
2101         ((listp thing)
2102          (eieio-list-prin1 thing))
2103         ((class-p thing)
2104          (princ (class-name thing)))
2105         ((symbolp thing)
2106          (princ (concat "'" (symbol-name thing))))
2107         (t (prin1 thing))))
2108
2109 (defun eieio-list-prin1 (list)
2110   "Display LIST where list may contain objects."
2111   (if (not (object-p (car list)))
2112       (progn
2113         (princ "'")
2114         (prin1 list))
2115     (princ "(list ")
2116     (if (object-p (car list)) (princ "\n "))
2117     (while list
2118       (if (object-p (car list))
2119           (object-write (car list))
2120         (princ "'")
2121         (prin1 (car list)))
2122       (princ " ")
2123       (setq list (cdr list)))
2124     (princ (make-string (* eieio-print-depth 2) ? ))
2125     (princ ")")))
2126
2127 \f
2128 ;;; Unimplemented functions from CLOS
2129 ;;
2130 (defun change-class (obj class)
2131   "Change the class of OBJ to type CLASS.
2132 This may create or delete slots, but does not affect the return value
2133 of `eq'."
2134   (error "Eieio: `change-class' is unimplemented"))
2135
2136 )
2137
2138 \f
2139 ;;; Interfacing with edebug
2140 ;;
2141 (defun eieio-edebug-prin1-to-string (object &optional noescape)
2142   "Display eieio OBJECT in fancy format.  Overrides the edebug default.
2143 Optional argument NOESCAPE is passed to `prin1-to-string' when appropriate."
2144   (cond ((class-p object) (class-name object))
2145         ((object-p object) (object-print object))
2146         ((and (listp object) (or (class-p (car object))
2147                                  (object-p (car object))))
2148          (concat "(" (mapconcat 'eieio-edebug-prin1-to-string object " ") ")"))
2149         (t (prin1-to-string object noescape))))
2150
2151 (add-hook 'edebug-setup-hook
2152           (lambda ()
2153             (def-edebug-spec defmethod
2154               (&define                  ; this means we are defining something
2155                [&or name ("setf" :name setf name)]
2156                ;; ^^ This is the methods symbol
2157                [ &optional symbolp ]    ; this is key :BEFORE etc
2158                list              ; arguments
2159                [ &optional stringp ]    ; documentation string
2160                def-body                 ; part to be debugged
2161                ))
2162             ;; The rest of the macros
2163             (def-edebug-spec oref (form quote))
2164             (def-edebug-spec oref-default (form quote))
2165             (def-edebug-spec oset (form quote form))
2166             (def-edebug-spec oset-default (form quote form))
2167             (def-edebug-spec class-v form)
2168             (def-edebug-spec class-p form)
2169             (def-edebug-spec object-p form)
2170             (def-edebug-spec class-constructor form)
2171             (def-edebug-spec generic-p form)
2172             (def-edebug-spec with-slots (list list def-body))
2173             ;; I suspect this isn't the best way to do this, but when
2174             ;; cust-print was used on my system all my objects
2175             ;; appeared as "#1 =" which was not useful.  This allows
2176             ;; edebug to print my objects in the nice way they were
2177             ;; meant to with `object-print' and `class-name'
2178             ;; (defalias 'edebug-prin1-to-string 'eieio-edebug-prin1-to-string)
2179             )
2180           )
2181
2182 (eval-after-load "cedet-edebug"
2183   '(progn
2184      (cedet-edebug-add-print-override '(class-p object) '(class-name object) )
2185      (cedet-edebug-add-print-override '(object-p object) '(object-print object) )
2186      (cedet-edebug-add-print-override '(and (listp object)
2187                                             (or (class-p (car object)) (object-p (car object))))
2188                                       '(cedet-edebug-prin1-recurse object) )
2189      ))
2190
2191 ;;; Interfacing with imenu in emacs lisp mode
2192 ;;    (Only if the expression is defined)
2193 ;;
2194 (if (eval-when-compile (boundp 'list-imenu-generic-expression))
2195 (progn
2196
2197 (defun eieio-update-lisp-imenu-expression ()
2198   "Examine `lisp-imenu-generic-expression' and modify it to find `defmethod'."
2199   (let ((exp lisp-imenu-generic-expression))
2200     (while exp
2201       ;; it's of the form '( ( title expr indx ) ... )
2202       (let* ((subcar (cdr (car exp)))
2203              (substr (car subcar)))
2204         (if (and (not (string-match "|method\\\\" substr))
2205                  (string-match "|advice\\\\" substr))
2206             (setcar subcar
2207                     (replace-match "|advice\\|method\\" t t substr 0))))
2208       (setq exp (cdr exp)))))
2209
2210 (eieio-update-lisp-imenu-expression)
2211
2212 ))
2213
2214 ;;; Autoloading some external symbols, and hooking into the help system
2215 ;;
2216
2217 (autoload 'eieio-help-mode-augmentation-maybee "eieio-opt" "For buffers thrown into help mode, augment for eieio.")
2218 (autoload 'eieio-browse "eieio-opt" "Create an object browser window" t)
2219 (autoload 'eieio-describe-class "eieio-opt" "Describe CLASS defined by a string or symbol" t)
2220 (autoload 'describe-class "eieio-opt" "Describe CLASS defined by a string or symbol" t)
2221 (autoload 'eieio-describe-generic "eieio-opt" "Describe GENERIC defined by a string or symbol" t)
2222 (autoload 'describe-generic "eieio-opt" "Describe GENERIC defined by a string or symbol" t)
2223 (autoload 'eieiodoc-class "eieio-doc" "Create texinfo documentation about a class hierarchy." t)
2224
2225 (autoload 'customize-object "eieio-custom" "Create a custom buffer editing OBJ.")
2226
2227 ;; make sure this shows up after the help mode hook.
2228 (add-hook 'temp-buffer-show-hook 'eieio-help-mode-augmentation-maybee t)
2229 (require 'advice)
2230 (defadvice describe-variable (around eieio-describe activate)
2231   "Display the full documentation of FUNCTION (a symbol).
2232 Returns the documentation as a string, also."
2233   (if (class-p (ad-get-arg 0))
2234       (eieio-describe-class (ad-get-arg 0))
2235     ad-do-it))
2236
2237 (defadvice describe-function (around eieio-describe activate)
2238   "Display the full documentation of VARIABLE (a symbol).
2239 Returns the documentation as a string, also."
2240   (if (generic-p (ad-get-arg 0))
2241       (eieio-describe-generic (ad-get-arg 0))
2242     ad-do-it))
2243
2244 (provide 'eieio)
2245 ;;; eieio ends here