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