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