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