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