Shrink EIEIO object header. Move generics to eieio-generic.el.
[emacs.git] / lisp / emacs-lisp / eieio-generic.el
blob0e90074660e40f899907ec5d197a5a3f909df01d
1 ;;; eieio-generic.el --- CLOS-style generics for EIEIO -*- lexical-binding:t -*-
3 ;; Copyright (C) 1995-1996, 1998-2015 Free Software Foundation, Inc.
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6 ;; Keywords: OO, lisp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; The "core" part of EIEIO is the implementation for the object
26 ;; system (such as eieio-defclass, or eieio-defmethod) but not the
27 ;; base classes for the object system, which are defined in EIEIO.
29 ;; See the commentary for eieio.el for more about EIEIO itself.
31 ;;; Code:
33 (require 'eieio-core)
34 (declare-function child-of-class-p "eieio")
36 (defconst eieio--method-static 0 "Index into :static tag on a method.")
37 (defconst eieio--method-before 1 "Index into :before tag on a method.")
38 (defconst eieio--method-primary 2 "Index into :primary tag on a method.")
39 (defconst eieio--method-after 3 "Index into :after tag on a method.")
40 (defconst eieio--method-num-lists 4 "Number of indexes into methods vector in which groups of functions are kept.")
41 (defconst eieio--method-generic-before 4 "Index into generic :before tag on a method.")
42 (defconst eieio--method-generic-primary 5 "Index into generic :primary tag on a method.")
43 (defconst eieio--method-generic-after 6 "Index into generic :after tag on a method.")
44 (defconst eieio--method-num-slots 7 "Number of indexes into a method's vector.")
46 (defsubst eieio--specialized-key-to-generic-key (key)
47 "Convert a specialized KEY into a generic method key."
48 (cond ((eq key eieio--method-static) 0) ;; don't convert
49 ((< key eieio--method-num-lists) (+ key 3)) ;; The conversion
50 (t key) ;; already generic.. maybe.
54 (defsubst generic-p (method)
55 "Return non-nil if symbol METHOD is a generic function.
56 Only methods have the symbol `eieio-method-hashtable' as a property
57 \(which contains a list of all bindings to that method type.)"
58 (and (fboundp method) (get method 'eieio-method-hashtable)))
60 (defun eieio--generic-primary-only-p (method)
61 "Return t if symbol METHOD is a generic function with only primary methods.
62 Only methods have the symbol `eieio-method-hashtable' as a property (which
63 contains a list of all bindings to that method type.)
64 Methods with only primary implementations are executed in an optimized way."
65 (and (generic-p method)
66 (let ((M (get method 'eieio-method-tree)))
67 (not (or (>= 0 (length (aref M eieio--method-primary)))
68 (aref M eieio--method-static)
69 (aref M eieio--method-before)
70 (aref M eieio--method-after)
71 (aref M eieio--method-generic-before)
72 (aref M eieio--method-generic-primary)
73 (aref M eieio--method-generic-after)))
74 )))
76 (defun eieio--generic-primary-only-one-p (method)
77 "Return t if symbol METHOD is a generic function with only primary methods.
78 Only methods have the symbol `eieio-method-hashtable' as a property (which
79 contains a list of all bindings to that method type.)
80 Methods with only primary implementations are executed in an optimized way."
81 (and (generic-p method)
82 (let ((M (get method 'eieio-method-tree)))
83 (not (or (/= 1 (length (aref M eieio--method-primary)))
84 (aref M eieio--method-static)
85 (aref M eieio--method-before)
86 (aref M eieio--method-after)
87 (aref M eieio--method-generic-before)
88 (aref M eieio--method-generic-primary)
89 (aref M eieio--method-generic-after)))
90 )))
92 (defun eieio--defgeneric-init-form (method doc-string)
93 "Form to use for the initial definition of a generic."
94 (while (and (fboundp method) (symbolp (symbol-function method)))
95 ;; Follow aliases, so methods applied to obsolete aliases still work.
96 (setq method (symbol-function method)))
98 (cond
99 ((or (not (fboundp method))
100 (eq 'autoload (car-safe (symbol-function method))))
101 ;; Make sure the method tables are installed.
102 (eieio--mt-install method)
103 ;; Construct the actual body of this function.
104 (put method 'function-documentation doc-string)
105 (eieio--defgeneric-form method))
106 ((generic-p method) (symbol-function method)) ;Leave it as-is.
107 (t (error "You cannot create a generic/method over an existing symbol: %s"
108 method))))
110 (defun eieio--defgeneric-form (method)
111 "The lambda form that would be used as the function defined on METHOD.
112 All methods should call the same EIEIO function for dispatch.
113 DOC-STRING is the documentation attached to METHOD."
114 (lambda (&rest local-args)
115 (eieio--generic-call method local-args)))
117 (defun eieio--defgeneric-form-primary-only (method)
118 "The lambda form that would be used as the function defined on METHOD.
119 All methods should call the same EIEIO function for dispatch.
120 DOC-STRING is the documentation attached to METHOD."
121 (lambda (&rest local-args)
122 (eieio--generic-call-primary-only method local-args)))
124 (defvar eieio--generic-call-arglst nil
125 "When using `call-next-method', provides a context for parameters.")
126 (defvar eieio--generic-call-key nil
127 "When using `call-next-method', provides a context for the current key.
128 Keys are a number representing :before, :primary, and :after methods.")
129 (defvar eieio--generic-call-next-method-list nil
130 "When executing a PRIMARY or STATIC method, track the 'next-method'.
131 During executions, the list is first generated, then as each next method
132 is called, the next method is popped off the stack.")
134 (defun eieio--defgeneric-form-primary-only-one (method class impl)
135 "The lambda form that would be used as the function defined on METHOD.
136 All methods should call the same EIEIO function for dispatch.
137 CLASS is the class symbol needed for private method access.
138 IMPL is the symbol holding the method implementation."
139 (lambda (&rest local-args)
140 ;; This is a cool cheat. Usually we need to look up in the
141 ;; method table to find out if there is a method or not. We can
142 ;; instead make that determination at load time when there is
143 ;; only one method. If the first arg is not a child of the class
144 ;; of that one implementation, then clearly, there is no method def.
145 (if (not (eieio-object-p (car local-args)))
146 ;; Not an object. Just signal.
147 (signal 'no-method-definition
148 (list method local-args))
150 ;; We do have an object. Make sure it is the right type.
151 (if (not (child-of-class-p (eieio--object-class-object (car local-args))
152 class))
154 ;; If not the right kind of object, call no applicable
155 (apply #'no-applicable-method (car local-args)
156 method local-args)
158 ;; It is ok, do the call.
159 ;; Fill in inter-call variables then evaluate the method.
160 (let ((eieio--generic-call-next-method-list nil)
161 (eieio--generic-call-key eieio--method-primary)
162 (eieio--generic-call-arglst local-args)
164 (eieio--with-scoped-class (eieio--class-v class)
165 (apply impl local-args)))))))
167 (defun eieio-unbind-method-implementations (method)
168 "Make the generic method METHOD have no implementations.
169 It will leave the original generic function in place,
170 but remove reference to all implementations of METHOD."
171 (put method 'eieio-method-tree nil)
172 (put method 'eieio-method-hashtable nil))
174 (defun eieio--method-optimize-primary (method)
175 (when eieio-optimize-primary-methods-flag
176 ;; Optimizing step:
178 ;; If this method, after this setup, only has primary methods, then
179 ;; we can setup the generic that way.
180 (let ((doc-string (documentation method 'raw)))
181 (put method 'function-documentation doc-string)
182 ;; Use `defalias' so as to interact properly with nadvice.el.
183 (defalias method
184 (if (eieio--generic-primary-only-p method)
185 ;; If there is only one primary method, then we can go one more
186 ;; optimization step.
187 (if (eieio--generic-primary-only-one-p method)
188 (let* ((M (get method 'eieio-method-tree))
189 (entry (car (aref M eieio--method-primary))))
190 (eieio--defgeneric-form-primary-only-one
191 method (car entry) (cdr entry)))
192 (eieio--defgeneric-form-primary-only method))
193 (eieio--defgeneric-form method))))))
195 (defun eieio--defmethod (method kind argclass code)
196 "Work part of the `defmethod' macro defining METHOD with ARGS."
197 (let ((key
198 ;; Find optional keys.
199 (cond ((memq kind '(:BEFORE :before)) eieio--method-before)
200 ((memq kind '(:AFTER :after)) eieio--method-after)
201 ((memq kind '(:STATIC :static)) eieio--method-static)
202 ((memq kind '(:PRIMARY :primary nil)) eieio--method-primary)
203 ;; Primary key.
204 ;; (t eieio--method-primary)
205 (t (error "Unknown method kind %S" kind)))))
207 (while (and (fboundp method) (symbolp (symbol-function method)))
208 ;; Follow aliases, so methods applied to obsolete aliases still work.
209 (setq method (symbol-function method)))
211 ;; Make sure there is a generic (when called from defclass).
212 (eieio--defalias
213 method (eieio--defgeneric-init-form
214 method (or (documentation code)
215 (format "Generically created method `%s'." method))))
216 ;; Create symbol for property to bind to. If the first arg is of
217 ;; the form (varname vartype) and `vartype' is a class, then
218 ;; that class will be the type symbol. If not, then it will fall
219 ;; under the type `primary' which is a non-specific calling of the
220 ;; function.
221 (if argclass
222 (if (not (class-p argclass)) ;FIXME: Accept cl-defstructs!
223 (error "Unknown class type %s in method parameters"
224 argclass))
225 ;; Generics are higher.
226 (setq key (eieio--specialized-key-to-generic-key key)))
227 ;; Put this lambda into the symbol so we can find it.
228 (eieio--mt-add method code key argclass)
231 (eieio--method-optimize-primary method)
233 method)
235 (define-obsolete-variable-alias 'eieio-pre-method-execution-hooks
236 'eieio-pre-method-execution-functions "24.3")
237 (defvar eieio-pre-method-execution-functions nil
238 "Abnormal hook run just before an EIEIO method is executed.
239 The hook function must accept one argument, the list of forms
240 about to be executed.")
242 (defun eieio--generic-call (method args)
243 "Call METHOD with ARGS.
244 ARGS provides the context on which implementation to use.
245 This should only be called from a generic function."
246 ;; We must expand our arguments first as they are always
247 ;; passed in as quoted symbols
248 (let ((newargs nil) (mclass nil) (lambdas nil) (tlambdas nil) (keys nil)
249 (eieio--generic-call-arglst args)
250 (firstarg nil)
251 (primarymethodlist nil))
252 ;; get a copy
253 (setq newargs args
254 firstarg (car newargs))
255 ;; Is the class passed in autoloaded?
256 ;; Since class names are also constructors, they can be autoloaded
257 ;; via the autoload command. Check for this, and load them in.
258 ;; It is ok if it doesn't turn out to be a class. Probably want that
259 ;; function loaded anyway.
260 (if (and (symbolp firstarg)
261 (fboundp firstarg)
262 (autoloadp (symbol-function firstarg)))
263 (autoload-do-load (symbol-function firstarg)))
264 ;; Determine the class to use.
265 (cond ((eieio-object-p firstarg)
266 (setq mclass (eieio--object-class-name firstarg)))
267 ((class-p firstarg)
268 (setq mclass firstarg))
270 ;; Make sure the class is a valid class
271 ;; mclass can be nil (meaning a generic for should be used.
272 ;; mclass cannot have a value that is not a class, however.
273 (unless (or (null mclass) (class-p mclass))
274 (error "Cannot dispatch method %S on class %S"
275 method mclass)
277 ;; Now create a list in reverse order of all the calls we have
278 ;; make in order to successfully do this right. Rules:
279 ;; 1) Only call generics if scoped-class is not defined
280 ;; This prevents multiple calls in the case of recursion
281 ;; 2) Only call static if this is a static method.
282 ;; 3) Only call specifics if the definition allows for them.
283 ;; 4) Call in order based on :before, :primary, and :after
284 (when (eieio-object-p firstarg)
285 ;; Non-static calls do all this stuff.
287 ;; :after methods
288 (setq tlambdas
289 (if mclass
290 (eieio--mt-method-list method eieio--method-after mclass)
291 (list (eieio--generic-form method eieio--method-after nil)))
292 ;;(or (and mclass (eieio--generic-form method eieio--method-after mclass))
293 ;; (eieio--generic-form method eieio--method-after nil))
295 (setq lambdas (append tlambdas lambdas)
296 keys (append (make-list (length tlambdas) eieio--method-after) keys))
298 ;; :primary methods
299 (setq tlambdas
300 (or (and mclass (eieio--generic-form method eieio--method-primary mclass))
301 (eieio--generic-form method eieio--method-primary nil)))
302 (when tlambdas
303 (setq lambdas (cons tlambdas lambdas)
304 keys (cons eieio--method-primary keys)
305 primarymethodlist
306 (eieio--mt-method-list method eieio--method-primary mclass)))
308 ;; :before methods
309 (setq tlambdas
310 (if mclass
311 (eieio--mt-method-list method eieio--method-before mclass)
312 (list (eieio--generic-form method eieio--method-before nil)))
313 ;;(or (and mclass (eieio--generic-form method eieio--method-before mclass))
314 ;; (eieio--generic-form method eieio--method-before nil))
316 (setq lambdas (append tlambdas lambdas)
317 keys (append (make-list (length tlambdas) eieio--method-before) keys))
320 (if mclass
321 ;; For the case of a class,
322 ;; if there were no methods found, then there could be :static methods.
323 (when (not lambdas)
324 (setq tlambdas
325 (eieio--generic-form method eieio--method-static mclass))
326 (setq lambdas (cons tlambdas lambdas)
327 keys (cons eieio--method-static keys)
328 primarymethodlist ;; Re-use even with bad name here
329 (eieio--mt-method-list method eieio--method-static mclass)))
330 ;; For the case of no class (ie - mclass == nil) then there may
331 ;; be a primary method.
332 (setq tlambdas
333 (eieio--generic-form method eieio--method-primary nil))
334 (when tlambdas
335 (setq lambdas (cons tlambdas lambdas)
336 keys (cons eieio--method-primary keys)
337 primarymethodlist
338 (eieio--mt-method-list method eieio--method-primary nil)))
341 (run-hook-with-args 'eieio-pre-method-execution-functions
342 primarymethodlist)
344 ;; Now loop through all occurrences forms which we must execute
345 ;; (which are happily sorted now) and execute them all!
346 (let ((rval nil) (lastval nil) (found nil))
347 (while lambdas
348 (if (car lambdas)
349 (eieio--with-scoped-class (cdr (car lambdas))
350 (let* ((eieio--generic-call-key (car keys))
351 (has-return-val
352 (or (= eieio--generic-call-key eieio--method-primary)
353 (= eieio--generic-call-key eieio--method-static)))
354 (eieio--generic-call-next-method-list
355 ;; Use the cdr, as the first element is the fcn
356 ;; we are calling right now.
357 (when has-return-val (cdr primarymethodlist)))
359 (setq found t)
360 ;;(setq rval (apply (car (car lambdas)) newargs))
361 (setq lastval (apply (car (car lambdas)) newargs))
362 (when has-return-val
363 (setq rval lastval))
365 (setq lambdas (cdr lambdas)
366 keys (cdr keys)))
367 (if (not found)
368 (if (eieio-object-p (car args))
369 (setq rval (apply #'no-applicable-method (car args) method args))
370 (signal
371 'no-method-definition
372 (list method args))))
373 rval)))
375 (defun eieio--generic-call-primary-only (method args)
376 "Call METHOD with ARGS for methods with only :PRIMARY implementations.
377 ARGS provides the context on which implementation to use.
378 This should only be called from a generic function.
380 This method is like `eieio--generic-call', but only
381 implementations in the :PRIMARY slot are queried. After many
382 years of use, it appears that over 90% of methods in use
383 have :PRIMARY implementations only. We can therefore optimize
384 for this common case to improve performance."
385 ;; We must expand our arguments first as they are always
386 ;; passed in as quoted symbols
387 (let ((newargs nil) (mclass nil) (lambdas nil)
388 (eieio--generic-call-arglst args)
389 (firstarg nil)
390 (primarymethodlist nil)
392 ;; get a copy
393 (setq newargs args
394 firstarg (car newargs))
396 ;; Determine the class to use.
397 (cond ((eieio-object-p firstarg)
398 (setq mclass (eieio--object-class-name firstarg)))
399 ((not firstarg)
400 (error "Method %s called on nil" method))
402 (error "Primary-only method %s called on something not an object" method)))
403 ;; Make sure the class is a valid class
404 ;; mclass can be nil (meaning a generic for should be used.
405 ;; mclass cannot have a value that is not a class, however.
406 (when (null mclass)
407 (error "Cannot dispatch method %S on class %S" method mclass)
410 ;; :primary methods
411 (setq lambdas (eieio--generic-form method eieio--method-primary mclass))
412 (setq primarymethodlist ;; Re-use even with bad name here
413 (eieio--mt-method-list method eieio--method-primary mclass))
415 ;; Now loop through all occurrences forms which we must execute
416 ;; (which are happily sorted now) and execute them all!
417 (eieio--with-scoped-class (cdr lambdas)
418 (let* ((rval nil) (lastval nil)
419 (eieio--generic-call-key eieio--method-primary)
420 ;; Use the cdr, as the first element is the fcn
421 ;; we are calling right now.
422 (eieio--generic-call-next-method-list (cdr primarymethodlist))
425 (if (or (not lambdas) (not (car lambdas)))
427 ;; No methods found for this impl...
428 (if (eieio-object-p (car args))
429 (setq rval (apply #'no-applicable-method
430 (car args) method args))
431 (signal
432 'no-method-definition
433 (list method args)))
435 ;; Do the regular implementation here.
437 (run-hook-with-args 'eieio-pre-method-execution-functions
438 lambdas)
440 (setq lastval (apply (car lambdas) newargs))
441 (setq rval lastval))
443 rval))))
445 (defun eieio--mt-method-list (method key class)
446 "Return an alist list of methods lambdas.
447 METHOD is the method name.
448 KEY represents either :before, or :after methods.
449 CLASS is the starting class to search from in the method tree.
450 If CLASS is nil, then an empty list of methods should be returned."
451 ;; Note: eieiomt - the MT means MethodTree. See more comments below
452 ;; for the rest of the eieiomt methods.
454 ;; Collect lambda expressions stored for the class and its parent
455 ;; classes.
456 (let (lambdas)
457 (dolist (ancestor (eieio--class-precedence-list (eieio--class-v class)))
458 ;; Lookup the form to use for the PRIMARY object for the next level
459 (let ((tmpl (eieio--generic-form method key ancestor)))
460 (when (and tmpl
461 (or (not lambdas)
462 ;; This prevents duplicates coming out of the
463 ;; class method optimizer. Perhaps we should
464 ;; just not optimize before/afters?
465 (not (member tmpl lambdas))))
466 (push tmpl lambdas))))
468 ;; Return collected lambda. For :after methods, return in current
469 ;; order (most general class last); Otherwise, reverse order.
470 (if (eq key eieio--method-after)
471 lambdas
472 (nreverse lambdas))))
476 ;; eieio-method-tree : eieio--mt-
478 ;; Stored as eieio-method-tree in property list of a generic method
480 ;; (eieio-method-tree . [BEFORE PRIMARY AFTER
481 ;; genericBEFORE genericPRIMARY genericAFTER])
482 ;; and
483 ;; (eieio-method-hashtable . [BEFORE PRIMARY AFTER
484 ;; genericBEFORE genericPRIMARY genericAFTER])
485 ;; where the association is a vector.
486 ;; (aref 0 -- all static methods.
487 ;; (aref 1 -- all methods classified as :before
488 ;; (aref 2 -- all methods classified as :primary
489 ;; (aref 3 -- all methods classified as :after
490 ;; (aref 4 -- a generic classified as :before
491 ;; (aref 5 -- a generic classified as :primary
492 ;; (aref 6 -- a generic classified as :after
494 (defvar eieio--mt--optimizing-hashtable nil
495 "While mapping atoms, this contain the hashtable being optimized.")
497 (defun eieio--mt-install (method-name)
498 "Install the method tree, and hashtable onto METHOD-NAME.
499 Do not do the work if they already exist."
500 (unless (and (get method-name 'eieio-method-tree)
501 (get method-name 'eieio-method-hashtable))
502 (put method-name 'eieio-method-tree
503 (make-vector eieio--method-num-slots nil))
504 (let ((emto (put method-name 'eieio-method-hashtable
505 (make-vector eieio--method-num-slots nil))))
506 (aset emto 0 (make-hash-table :test 'eq))
507 (aset emto 1 (make-hash-table :test 'eq))
508 (aset emto 2 (make-hash-table :test 'eq))
509 (aset emto 3 (make-hash-table :test 'eq)))))
511 (defun eieio--mt-add (method-name method key class)
512 "Add to METHOD-NAME the forms METHOD in a call position KEY for CLASS.
513 METHOD-NAME is the name created by a call to `defgeneric'.
514 METHOD are the forms for a given implementation.
515 KEY is an integer (see comment in eieio.el near this function) which
516 is associated with the :static :before :primary and :after tags.
517 It also indicates if CLASS is defined or not.
518 CLASS is the class this method is associated with."
519 (if (or (> key eieio--method-num-slots) (< key 0))
520 (error "eieio--mt-add: method key error!"))
521 (let ((emtv (get method-name 'eieio-method-tree))
522 (emto (get method-name 'eieio-method-hashtable)))
523 ;; Make sure the method tables are available.
524 (unless (and emtv emto)
525 (error "Programmer error: eieio--mt-add"))
526 ;; only add new cells on if it doesn't already exist!
527 (if (assq class (aref emtv key))
528 (setcdr (assq class (aref emtv key)) method)
529 (aset emtv key (cons (cons class method) (aref emtv key))))
530 ;; Add function definition into newly created symbol, and store
531 ;; said symbol in the correct hashtable, otherwise use the
532 ;; other array to keep this stuff.
533 (if (< key eieio--method-num-lists)
534 (puthash (eieio--class-v class) (list method) (aref emto key)))
535 ;; Save the defmethod file location in a symbol property.
536 (let ((fname (if load-in-progress
537 load-file-name
538 buffer-file-name)))
539 (when fname
540 (when (string-match "\\.elc\\'" fname)
541 (setq fname (substring fname 0 (1- (length fname)))))
542 (cl-pushnew (list class fname) (get method-name 'method-locations)
543 :test 'equal)))
544 ;; Now optimize the entire hashtable.
545 (if (< key eieio--method-num-lists)
546 (let ((eieio--mt--optimizing-hashtable (aref emto key)))
547 ;; @todo - Is this overkill? Should we just clear the symbol?
548 (maphash #'eieio--mt--sym-optimize eieio--mt--optimizing-hashtable)))
551 (defun eieio--mt-next (class)
552 "Return the next parent class for CLASS.
553 If CLASS is a superclass, return variable `eieio-default-superclass'.
554 If CLASS is variable `eieio-default-superclass' then return nil.
555 This is different from function `class-parent' as class parent returns
556 nil for superclasses. This function performs no type checking!"
557 ;; No type-checking because all calls are made from functions which
558 ;; are safe and do checking for us.
559 (or (eieio--class-parent (eieio--class-v class))
560 (if (eq class 'eieio-default-superclass)
562 '(eieio-default-superclass))))
564 (defun eieio--mt--sym-optimize (class s)
565 "Find the next class above S which has a function body for the optimizer."
566 ;; Set the value to nil in case there is no nearest cell.
567 (setcdr s nil)
568 ;; Find the nearest cell that has a function body. If we find one,
569 ;; we replace the nil from above.
570 (catch 'done
571 (dolist (ancestor
572 (cl-rest (eieio--class-precedence-list class)))
573 (let ((ov (gethash ancestor eieio--mt--optimizing-hashtable)))
574 (when (car ov)
575 (setcdr s ancestor) ;; store ov as our next symbol
576 (throw 'done ancestor))))))
578 (defun eieio--generic-form (method key class)
579 "Return the lambda form belonging to METHOD using KEY based upon CLASS.
580 If CLASS is not a class then use `generic' instead. If class has
581 no form, but has a parent class, then trace to that parent class.
582 The first time a form is requested from a symbol, an optimized path
583 is memorized for faster future use."
584 (if (symbolp class) (setq class (eieio--class-v class)))
585 (let ((emto (aref (get method 'eieio-method-hashtable)
586 (if class key (eieio--specialized-key-to-generic-key key)))))
587 (if (eieio--class-p class)
588 ;; 1) find our symbol
589 (let ((cs (gethash class emto)))
590 (unless cs
591 ;; 2) If there isn't one, then make one.
592 ;; This can be slow since it only occurs once
593 (puthash class (setq cs (list nil)) emto)
594 ;; 2.1) Cache its nearest neighbor with a quick optimize
595 ;; which should only occur once for this call ever
596 (let ((eieio--mt--optimizing-hashtable emto))
597 (eieio--mt--sym-optimize class cs)))
598 ;; 3) If it's bound return this one.
599 (if (car cs)
600 (cons (car cs) class)
601 ;; 4) If it's not bound then this variable knows something
602 (if (cdr cs)
603 (progn
604 ;; 4.1) This symbol holds the next class in its value
605 (setq class (cdr cs)
606 cs (gethash class emto))
607 ;; 4.2) The optimizer should always have chosen a
608 ;; function-symbol
609 ;;(if (car cs)
610 (cons (car cs) class)
611 ;;(error "EIEIO optimizer: erratic data loss!"))
613 ;; There never will be a funcall...
614 nil)))
615 ;; for a generic call, what is a list, is the function body we want.
616 (let ((emtl (aref (get method 'eieio-method-tree)
617 (if class key (eieio--specialized-key-to-generic-key key)))))
618 (if emtl
619 ;; The car of EMTL is supposed to be a class, which in this
620 ;; case is nil, so skip it.
621 (cons (cdr (car emtl)) nil)
622 nil)))))
625 (define-error 'no-method-definition "No method definition")
626 (define-error 'no-next-method "No next method")
628 ;;; CLOS methods and generics
630 (defmacro defgeneric (method _args &optional doc-string)
631 "Create a generic function METHOD.
632 DOC-STRING is the base documentation for this class. A generic
633 function has no body, as its purpose is to decide which method body
634 is appropriate to use. Uses `defmethod' to create methods, and calls
635 `defgeneric' for you. With this implementation the ARGS are
636 currently ignored. You can use `defgeneric' to apply specialized
637 top level documentation to a method."
638 (declare (doc-string 3))
639 `(eieio--defalias ',method
640 (eieio--defgeneric-init-form ',method ,doc-string)))
642 (defmacro defmethod (method &rest args)
643 "Create a new METHOD through `defgeneric' with ARGS.
645 The optional second argument KEY is a specifier that
646 modifies how the method is called, including:
647 :before - Method will be called before the :primary
648 :primary - The default if not specified
649 :after - Method will be called after the :primary
650 :static - First arg could be an object or class
651 The next argument is the ARGLIST. The ARGLIST specifies the arguments
652 to the method as with `defun'. The first argument can have a type
653 specifier, such as:
654 ((VARNAME CLASS) ARG2 ...)
655 where VARNAME is the name of the local variable for the method being
656 created. The CLASS is a class symbol for a class made with `defclass'.
657 A DOCSTRING comes after the ARGLIST, and is optional.
658 All the rest of the args are the BODY of the method. A method will
659 return the value of the last form in the BODY.
661 Summary:
663 (defmethod mymethod [:before | :primary | :after | :static]
664 ((typearg class-name) arg2 &optional opt &rest rest)
665 \"doc-string\"
666 body)"
667 (declare (doc-string 3)
668 (debug
669 (&define ; this means we are defining something
670 [&or name ("setf" :name setf name)]
671 ;; ^^ This is the methods symbol
672 [ &optional symbolp ] ; this is key :before etc
673 list ; arguments
674 [ &optional stringp ] ; documentation string
675 def-body ; part to be debugged
677 (let* ((key (if (keywordp (car args)) (pop args)))
678 (params (car args))
679 (arg1 (car params))
680 (fargs (if (consp arg1)
681 (cons (car arg1) (cdr params))
682 params))
683 (class (if (consp arg1) (nth 1 arg1)))
684 (code `(lambda ,fargs ,@(cdr args))))
685 `(progn
686 ;; Make sure there is a generic and the byte-compiler sees it.
687 (defgeneric ,method ,args
688 ,(or (documentation code)
689 (format "Generically created method `%s'." method)))
690 (eieio--defmethod ',method ',key ',class #',code))))
695 ;; Method Calling Functions
697 (defun next-method-p ()
698 "Return non-nil if there is a next method.
699 Returns a list of lambda expressions which is the `next-method'
700 order."
701 eieio--generic-call-next-method-list)
703 (defun call-next-method (&rest replacement-args)
704 "Call the superclass method from a subclass method.
705 The superclass method is specified in the current method list,
706 and is called the next method.
708 If REPLACEMENT-ARGS is non-nil, then use them instead of
709 `eieio--generic-call-arglst'. The generic arg list are the
710 arguments passed in at the top level.
712 Use `next-method-p' to find out if there is a next method to call."
713 (if (not (eieio--scoped-class))
714 (error "`call-next-method' not called within a class specific method"))
715 (if (and (/= eieio--generic-call-key eieio--method-primary)
716 (/= eieio--generic-call-key eieio--method-static))
717 (error "Cannot `call-next-method' except in :primary or :static methods")
719 (let ((newargs (or replacement-args eieio--generic-call-arglst))
720 (next (car eieio--generic-call-next-method-list))
722 (if (not (and next (car next)))
723 (apply #'no-next-method newargs)
724 (let* ((eieio--generic-call-next-method-list
725 (cdr eieio--generic-call-next-method-list))
726 (eieio--generic-call-arglst newargs)
727 (fcn (car next))
729 (eieio--with-scoped-class (cdr next)
730 (apply fcn newargs)) ))))
732 (defgeneric no-applicable-method (object method &rest args)
733 "Called if there are no implementations for OBJECT in METHOD.")
735 (defmethod no-applicable-method (object method &rest _args)
736 "Called if there are no implementations for OBJECT in METHOD.
737 OBJECT is the object which has no method implementation.
738 ARGS are the arguments that were passed to METHOD.
740 Implement this for a class to block this signal. The return
741 value becomes the return value of the original method call."
742 (signal 'no-method-definition (list method object)))
744 (defgeneric no-next-method (object &rest args)
745 "Called from `call-next-method' when no additional methods are available.")
747 (defmethod no-next-method (object &rest args)
748 "Called from `call-next-method' when no additional methods are available.
749 OBJECT is othe object being called on `call-next-method'.
750 ARGS are the arguments it is called by.
751 This method signals `no-next-method' by default. Override this
752 method to not throw an error, and its return value becomes the
753 return value of `call-next-method'."
754 (signal 'no-next-method (list object args)))
756 (add-hook 'help-fns-describe-function-functions 'eieio--help-generic)
757 (defun eieio--help-generic (generic)
758 "Describe GENERIC if it is a generic function."
759 (when (and (symbolp generic) (generic-p generic))
760 (save-excursion
761 (goto-char (point-min))
762 (when (re-search-forward " in `.+'.$" nil t)
763 (replace-match ".")))
764 (save-excursion
765 (insert "\n\nThis is a generic function"
766 (cond
767 ((and (eieio--generic-primary-only-p generic)
768 (eieio--generic-primary-only-one-p generic))
769 " with only one primary method")
770 ((eieio--generic-primary-only-p generic)
771 " with only primary methods")
772 (t ""))
773 ".\n\n")
774 (insert (propertize "Implementations:\n\n" 'face 'bold))
775 (let ((i 4)
776 (prefix [ ":STATIC" ":BEFORE" ":PRIMARY" ":AFTER" ] ))
777 ;; Loop over fanciful generics
778 (while (< i 7)
779 (let ((gm (aref (get generic 'eieio-method-tree) i)))
780 (when gm
781 (insert "Generic "
782 (aref prefix (- i 3))
783 "\n"
784 (or (nth 2 gm) "Undocumented")
785 "\n\n")))
786 (setq i (1+ i)))
787 (setq i 0)
788 ;; Loop over defined class-specific methods
789 (while (< i 4)
790 (let* ((gm (reverse (aref (get generic 'eieio-method-tree) i)))
791 cname location)
792 (while gm
793 (setq cname (caar gm))
794 (insert "`")
795 (help-insert-xref-button (symbol-name cname)
796 'help-variable cname)
797 (insert "' " (aref prefix i) " ")
798 ;; argument list
799 (let* ((func (cdr (car gm)))
800 (arglst (help-function-arglist func)))
801 (prin1 arglst (current-buffer)))
802 (insert "\n"
803 (or (documentation (cdr (car gm)))
804 "Undocumented"))
805 ;; Print file location if available
806 (when (and (setq location (get generic 'method-locations))
807 (setq location (assoc cname location)))
808 (setq location (cadr location))
809 (insert "\n\nDefined in `")
810 (help-insert-xref-button
811 (file-name-nondirectory location)
812 'eieio-method-def cname generic location)
813 (insert "'\n"))
814 (setq gm (cdr gm))
815 (insert "\n")))
816 (setq i (1+ i)))))))
818 ;;; Obsolete backward compatibility functions.
819 ;; Needed to run byte-code compiled with the EIEIO of Emacs-23.
821 (defun eieio-defmethod (method args)
822 "Obsolete work part of an old version of the `defmethod' macro."
823 (let ((key nil) (body nil) (firstarg nil) (argfix nil) (argclass nil) loopa)
824 ;; find optional keys
825 (setq key
826 (cond ((memq (car args) '(:BEFORE :before))
827 (setq args (cdr args))
828 eieio--method-before)
829 ((memq (car args) '(:AFTER :after))
830 (setq args (cdr args))
831 eieio--method-after)
832 ((memq (car args) '(:STATIC :static))
833 (setq args (cdr args))
834 eieio--method-static)
835 ((memq (car args) '(:PRIMARY :primary))
836 (setq args (cdr args))
837 eieio--method-primary)
838 ;; Primary key.
839 (t eieio--method-primary)))
840 ;; Get body, and fix contents of args to be the arguments of the fn.
841 (setq body (cdr args)
842 args (car args))
843 (setq loopa args)
844 ;; Create a fixed version of the arguments.
845 (while loopa
846 (setq argfix (cons (if (listp (car loopa)) (car (car loopa)) (car loopa))
847 argfix))
848 (setq loopa (cdr loopa)))
849 ;; Make sure there is a generic.
850 (eieio-defgeneric
851 method
852 (if (stringp (car body))
853 (car body) (format "Generically created method `%s'." method)))
854 ;; create symbol for property to bind to. If the first arg is of
855 ;; the form (varname vartype) and `vartype' is a class, then
856 ;; that class will be the type symbol. If not, then it will fall
857 ;; under the type `primary' which is a non-specific calling of the
858 ;; function.
859 (setq firstarg (car args))
860 (if (listp firstarg)
861 (progn
862 (setq argclass (nth 1 firstarg))
863 (if (not (class-p argclass))
864 (error "Unknown class type %s in method parameters"
865 (nth 1 firstarg))))
866 ;; Generics are higher.
867 (setq key (eieio--specialized-key-to-generic-key key)))
868 ;; Put this lambda into the symbol so we can find it.
869 (if (byte-code-function-p (car-safe body))
870 (eieio--mt-add method (car-safe body) key argclass)
871 (eieio--mt-add method (append (list 'lambda (reverse argfix)) body)
872 key argclass))
875 (eieio--method-optimize-primary method)
877 method)
878 (make-obsolete 'eieio-defmethod 'eieio--defmethod "24.1")
880 (defun eieio-defgeneric (method doc-string)
881 "Obsolete work part of an old version of the `defgeneric' macro."
882 (if (and (fboundp method) (not (generic-p method))
883 (or (byte-code-function-p (symbol-function method))
884 (not (eq 'autoload (car (symbol-function method)))))
886 (error "You cannot create a generic/method over an existing symbol: %s"
887 method))
888 ;; Don't do this over and over.
889 (unless (fboundp 'method)
890 ;; This defun tells emacs where the first definition of this
891 ;; method is defined.
892 `(defun ,method nil)
893 ;; Make sure the method tables are installed.
894 (eieio--mt-install method)
895 ;; Apply the actual body of this function.
896 (put method 'function-documentation doc-string)
897 (fset method (eieio--defgeneric-form method))
898 ;; Return the method
899 'method))
900 (make-obsolete 'eieio-defgeneric nil "24.1")
902 (provide 'eieio-generic)
904 ;;; eieio-generic.el ends here