eieio.el 35.7 KB
Newer Older
Chong Yidong's avatar
Chong Yidong committed
1
;;; eieio.el --- Enhanced Implementation of Emacs Interpreted Objects
Paul Eggert's avatar
Paul Eggert committed
2
;;;              or maybe Eric's Implementation of Emacs Interpreted Objects
Chong Yidong's avatar
Chong Yidong committed
3

4
;; Copyright (C) 1995-1996, 1998-2014 Free Software Foundation, Inc.
Chong Yidong's avatar
Chong Yidong committed
5

Glenn Morris's avatar
Glenn Morris committed
6
;; Author: Eric M. Ludlam <zappo@gnu.org>
7
;; Version: 1.4
Chong Yidong's avatar
Chong Yidong committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
;; Keywords: OO, lisp

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:
;;
;; EIEIO is a series of Lisp routines which implements a subset of
;; CLOS, the Common Lisp Object System.  In addition, EIEIO also adds
;; a few new features which help it integrate more strongly with the
;; Emacs running environment.
;;
;; See eieio.texi for complete documentation on using this package.
33 34 35 36 37
;;
;; Note: the implementation of the c3 algorithm is based on:
;;   Kim Barrett et al.: A Monotonic Superclass Linearization for Dylan
;;   Retrieved from:
;;   http://192.220.96.201/dylan/linearization-oopsla96.html
Chong Yidong's avatar
Chong Yidong committed
38 39 40 41 42 43 44 45 46

;; There is funny stuff going on with typep and deftype.  This
;; is the only way I seem to be able to make this stuff load properly.

;; @TODO - fix :initform to be a form, not a quoted value
;; @TODO - Prefix non-clos functions with `eieio-'.

;;; Code:

47
(eval-when-compile (require 'cl))       ;FIXME: Use cl-lib!
Chong Yidong's avatar
Chong Yidong committed
48

49
(defvar eieio-version "1.4"
Chong Yidong's avatar
Chong Yidong committed
50 51 52 53 54 55 56
  "Current version of EIEIO.")

(defun eieio-version ()
  "Display the current version of EIEIO."
  (interactive)
  (message eieio-version))

57
(require 'eieio-core)
Chong Yidong's avatar
Chong Yidong committed
58 59 60 61 62 63 64 65 66 67 68 69


;;; Defining a new class
;;
(defmacro defclass (name superclass slots &rest options-and-doc)
  "Define NAME as a new class derived from SUPERCLASS with SLOTS.
OPTIONS-AND-DOC is used as the class' options and base documentation.
SUPERCLASS is a list of superclasses to inherit from, with SLOTS
being the slots residing in that class definition.  NOTE: Currently
only one slot may exist in SUPERCLASS as multiple inheritance is not
yet supported.  Supported tags are:

Juanma Barranquero's avatar
Juanma Barranquero committed
70 71 72 73 74 75 76 77
  :initform   - Initializing form.
  :initarg    - Tag used during initialization.
  :accessor   - Tag used to create a function to access this slot.
  :allocation - Specify where the value is stored.
                Defaults to `:instance', but could also be `:class'.
  :writer     - A function symbol which will `write' an object's slot.
  :reader     - A function symbol which will `read' an object.
  :type       - The type of data allowed in this slot (see `typep').
Chong Yidong's avatar
Chong Yidong committed
78 79 80 81 82
  :documentation
              - A string documenting use of this slot.

The following are extensions on CLOS:
  :protection - Specify protection for this slot.
Juanma Barranquero's avatar
Juanma Barranquero committed
83
                Defaults to `:public'.  Also use `:protected', or `:private'.
Chong Yidong's avatar
Chong Yidong committed
84 85 86 87 88 89 90
  :custom     - When customizing an object, the custom :type.  Public only.
  :label      - A text string label used for a slot when customizing.
  :group      - Name of a customization group this slot belongs in.
  :printer    - A function to call to print the value of a slot.
                See `eieio-override-prin1' as an example.

A class can also have optional options.  These options happen in place
Juanma Barranquero's avatar
Juanma Barranquero committed
91
of documentation (including a :documentation tag), in addition to
Chong Yidong's avatar
Chong Yidong committed
92 93 94 95 96 97
documentation, or not at all.  Supported options are:

  :documentation - The doc-string used for this class.

Options added to EIEIO:

Juanma Barranquero's avatar
Juanma Barranquero committed
98
  :allow-nil-initform - Non-nil to skip typechecking of null initforms.
Chong Yidong's avatar
Chong Yidong committed
99 100 101 102 103 104
  :custom-groups      - List of custom group names.  Organizes slots into
                        reasonable groups for customizations.
  :abstract           - Non-nil to prevent instances of this class.
                        If a string, use as an error string if someone does
                        try to make an instance.
  :method-invocation-order
Glenn Morris's avatar
Glenn Morris committed
105
                      - Control the method invocation order if there is
Chong Yidong's avatar
Chong Yidong committed
106 107 108 109 110 111 112 113 114 115
                        multiple inheritance.  Valid values are:
                         :breadth-first - The default.
                         :depth-first

Options in CLOS not supported in EIEIO:

  :metaclass - Class to use in place of `standard-class'
  :default-initargs - Initargs to use when initializing new objects of
                      this class.

Juanma Barranquero's avatar
Juanma Barranquero committed
116 117
Due to the way class options are set up, you can add any tags you wish,
and reference them using the function `class-option'."
118 119 120 121 122 123
  ;; This is eval-and-compile only to silence spurious compiler warnings
  ;; about functions and variables not known to be defined.
  ;; When eieio-defclass code is merged here and this becomes
  ;; transparent to the compiler, the eval-and-compile can be removed.
  `(eval-and-compile
     (eieio-defclass ',name ',superclass ',slots ',options-and-doc)))
Chong Yidong's avatar
Chong Yidong committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138


;;; CLOS style implementation of object creators.
;;
(defun make-instance (class &rest initargs)
  "Make a new instance of CLASS based on INITARGS.
CLASS is a class symbol.  For example:

  (make-instance 'foo)

  INITARGS is a property list with keywords based on the :initarg
for each slot.  For example:

  (make-instance 'foo :slot1 value1 :slotN valueN)

Glenn Morris's avatar
Glenn Morris committed
139
Compatibility note:
Chong Yidong's avatar
Chong Yidong committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

If the first element of INITARGS is a string, it is used as the
name of the class.

In EIEIO, the class' constructor requires a name for use when printing.
`make-instance' in CLOS doesn't use names the way Emacs does, so the
class is used as the name slot instead when INITARGS doesn't start with
a string."
  (if (and (car initargs) (stringp (car initargs)))
      (apply (class-constructor class) initargs)
    (apply  (class-constructor class)
	    (cond ((symbolp class) (symbol-name class))
		  (t (format "%S" class)))
	    initargs)))


;;; CLOS methods and generics
;;
(defmacro defgeneric (method args &optional doc-string)
Juanma Barranquero's avatar
Juanma Barranquero committed
159
  "Create a generic function METHOD.
Chong Yidong's avatar
Chong Yidong committed
160
DOC-STRING is the base documentation for this class.  A generic
Juanma Barranquero's avatar
Juanma Barranquero committed
161 162 163
function has no body, as its purpose is to decide which method body
is appropriate to use.  Uses `defmethod' to create methods, and calls
`defgeneric' for you.  With this implementation the ARGS are
Chong Yidong's avatar
Chong Yidong committed
164 165
currently ignored.  You can use `defgeneric' to apply specialized
top level documentation to a method."
166 167 168
  `(eieio--defalias ',method
                    (eieio--defgeneric-init-form ',method ,doc-string)))

Chong Yidong's avatar
Chong Yidong committed
169 170 171
(defmacro defmethod (method &rest args)
  "Create a new METHOD through `defgeneric' with ARGS.

Juanma Barranquero's avatar
Juanma Barranquero committed
172
The optional second argument KEY is a specifier that
Chong Yidong's avatar
Chong Yidong committed
173
modifies how the method is called, including:
Juanma Barranquero's avatar
Juanma Barranquero committed
174 175 176 177
   :before  - Method will be called before the :primary
   :primary - The default if not specified
   :after   - Method will be called after the :primary
   :static  - First arg could be an object or class
Chong Yidong's avatar
Chong Yidong committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
The next argument is the ARGLIST.  The ARGLIST specifies the arguments
to the method as with `defun'.  The first argument can have a type
specifier, such as:
  ((VARNAME CLASS) ARG2 ...)
where VARNAME is the name of the local variable for the method being
created.  The CLASS is a class symbol for a class made with `defclass'.
A DOCSTRING comes after the ARGLIST, and is optional.
All the rest of the args are the BODY of the method.  A method will
return the value of the last form in the BODY.

Summary:

 (defmethod mymethod [:before | :primary | :after | :static]
                     ((typearg class-name) arg2 &optional opt &rest rest)
    \"doc-string\"
     body)"
194
  (let* ((key (if (keywordp (car args)) (pop args)))
Stefan Monnier's avatar
Stefan Monnier committed
195 196
	 (params (car args))
	 (arg1 (car params))
197
         (fargs (if (consp arg1)
198 199 200
                   (cons (car arg1) (cdr params))
                 params))
	 (class (if (consp arg1) (nth 1 arg1)))
201
         (code `(lambda ,fargs ,@(cdr args))))
202 203 204 205 206
    `(progn
       ;; Make sure there is a generic and the byte-compiler sees it.
       (defgeneric ,method ,args
         ,(or (documentation code)
              (format "Generically created method `%s'." method)))
207
       (eieio--defmethod ',method ',key ',class #',code))))
208

Chong Yidong's avatar
Chong Yidong committed
209 210 211 212 213 214 215 216 217 218 219 220
;;; Get/Set slots in an object.
;;
(defmacro oref (obj slot)
  "Retrieve the value stored in OBJ in the slot named by SLOT.
Slot is the name of the slot when created by `defclass' or the label
created by the :initarg tag."
  `(eieio-oref ,obj (quote ,slot)))

(defalias 'slot-value 'eieio-oref)
(defalias 'set-slot-value 'eieio-oset)

(defmacro oref-default (obj slot)
Juanma Barranquero's avatar
Juanma Barranquero committed
221
  "Get the default value of OBJ (maybe a class) for SLOT.
Chong Yidong's avatar
Chong Yidong committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
The default value is the value installed in a class with the :initform
tag.  SLOT can be the slot name, or the tag specified by the :initarg
tag in the `defclass' call."
  `(eieio-oref-default ,obj (quote ,slot)))

;;; Handy CLOS macros
;;
(defmacro with-slots (spec-list object &rest body)
  "Bind SPEC-LIST lexically to slot values in OBJECT, and execute BODY.
This establishes a lexical environment for referring to the slots in
the instance named by the given slot-names as though they were
variables.  Within such a context the value of the slot can be
specified by using its slot name, as if it were a lexically bound
variable.  Both setf and setq can be used to set the value of the
slot.

SPEC-LIST is of a form similar to `let'.  For example:

  ((VAR1 SLOT1)
    SLOT2
    SLOTN
   (VARN+1 SLOTN+1))

Where each VAR is the local variable given to the associated
Juanma Barranquero's avatar
Juanma Barranquero committed
246
SLOT.  A slot specified without a variable name is given a
Chong Yidong's avatar
Chong Yidong committed
247
variable name of the same name as the slot."
Stefan Monnier's avatar
Stefan Monnier committed
248
  (declare (indent 2))
Chong Yidong's avatar
Chong Yidong committed
249 250 251 252 253 254 255 256 257 258 259 260
  ;; Transform the spec-list into a symbol-macrolet spec-list.
  (let ((mappings (mapcar (lambda (entry)
			    (let ((var  (if (listp entry) (car entry) entry))
				  (slot (if (listp entry) (cadr entry) entry)))
			      (list var `(slot-value ,object ',slot))))
			  spec-list)))
    (append (list 'symbol-macrolet mappings)
	    body)))

;;; Simple generators, and query functions.  None of these would do
;;  well embedded into an object.
;;
261 262
(define-obsolete-function-alias
  'object-class-fast #'eieio--object-class "24.4")
Chong Yidong's avatar
Chong Yidong committed
263

264
(defun eieio-object-name (obj &optional extra)
Chong Yidong's avatar
Chong Yidong committed
265 266
  "Return a Lisp like symbol string for object OBJ.
If EXTRA, include that in the string returned to represent the symbol."
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  (eieio--check-type eieio-object-p obj)
  (format "#<%s %s%s>" (symbol-name (eieio--object-class obj))
	  (eieio--object-name obj) (or extra "")))
(define-obsolete-function-alias 'object-name #'eieio-object-name "24.4")

(defun eieio-object-name-string (obj) "Return a string which is OBJ's name."
  (eieio--check-type eieio-object-p obj)
  (eieio--object-name obj))
(define-obsolete-function-alias
  'object-name-string #'eieio-object-name-string "24.4")

(defun eieio-object-set-name-string (obj name)
  "Set the string which is OBJ's NAME."
  (eieio--check-type eieio-object-p obj)
  (eieio--check-type stringp name)
  (setf (eieio--object-name obj) name))
(define-obsolete-function-alias
  'object-set-name-string 'eieio-object-set-name-string "24.4")

(defun eieio-object-class (obj) "Return the class struct defining OBJ."
  (eieio--check-type eieio-object-p obj)
  (eieio--object-class obj))
(define-obsolete-function-alias 'object-class #'eieio-object-class "24.4")
;; CLOS name, maybe?
(define-obsolete-function-alias 'class-of #'eieio-object-class "24.4")

(defun eieio-object-class-name (obj)
  "Return a Lisp like symbol name for OBJ's class."
  (eieio--check-type eieio-object-p obj)
  (eieio-class-name (eieio--object-class obj)))
(define-obsolete-function-alias
  'object-class-name 'eieio-object-class-name "24.4")

(defun eieio-class-parents (class)
Chong Yidong's avatar
Chong Yidong committed
301 302 303
  "Return parent classes to CLASS.  (overload of variable).

The CLOS function `class-direct-superclasses' is aliased to this function."
304 305 306
  (eieio--check-type class-p class)
  (eieio-class-parents-fast class))
(define-obsolete-function-alias 'class-parents #'eieio-class-parents "24.4")
Chong Yidong's avatar
Chong Yidong committed
307

308 309
(defun eieio-class-children (class)
  "Return child classes to CLASS.
Chong Yidong's avatar
Chong Yidong committed
310
The CLOS function `class-direct-subclasses' is aliased to this function."
311 312 313 314
  (eieio--check-type class-p class)
  (eieio-class-children-fast class))
(define-obsolete-function-alias
  'class-children #'eieio-class-children "24.4")
Chong Yidong's avatar
Chong Yidong committed
315 316

;; Official CLOS functions.
317 318 319 320
(define-obsolete-function-alias
  'class-direct-superclasses #'eieio-class-parents "24.4")
(define-obsolete-function-alias
  'class-direct-subclasses #'eieio-class-children "24.4")
Chong Yidong's avatar
Chong Yidong committed
321

322 323 324
(defmacro eieio-class-parent (class)
  "Return first parent class to CLASS.  (overload of variable)."
  `(car (eieio-class-parents ,class)))
325
(define-obsolete-function-alias 'class-parent 'eieio-class-parent "24.4")
Chong Yidong's avatar
Chong Yidong committed
326 327

(defun same-class-p (obj class) "Return t if OBJ is of class-type CLASS."
328 329
  (eieio--check-type class-p class)
  (eieio--check-type eieio-object-p obj)
Chong Yidong's avatar
Chong Yidong committed
330 331 332 333
  (same-class-fast-p obj class))

(defun object-of-class-p (obj class)
  "Return non-nil if OBJ is an instance of CLASS or CLASS' subclasses."
334
  (eieio--check-type eieio-object-p obj)
Chong Yidong's avatar
Chong Yidong committed
335
  ;; class will be checked one layer down
336
  (child-of-class-p (eieio--object-class obj) class))
Chong Yidong's avatar
Chong Yidong committed
337 338 339 340
;; Backwards compatibility
(defalias 'obj-of-class-p 'object-of-class-p)

(defun child-of-class-p (child class)
Juanma Barranquero's avatar
Juanma Barranquero committed
341
  "Return non-nil if CHILD class is a subclass of CLASS."
342 343
  (eieio--check-type class-p class)
  (eieio--check-type class-p child)
Chong Yidong's avatar
Chong Yidong committed
344 345
  (let ((p nil))
    (while (and child (not (eq child class)))
346
      (setq p (append p (eieio--class-parent (class-v child)))
Chong Yidong's avatar
Chong Yidong committed
347 348 349 350
	    child (car p)
	    p (cdr p)))
    (if child t)))

351 352
(defun object-slots (obj)
  "Return list of slots available in OBJ."
353 354
  (eieio--check-type eieio-object-p obj)
  (eieio--class-public-a (class-v (eieio--object-class obj))))
Chong Yidong's avatar
Chong Yidong committed
355 356

(defun class-slot-initarg (class slot) "Fetch from CLASS, SLOT's :initarg."
357 358
  (eieio--check-type class-p class)
  (let ((ia (eieio--class-initarg-tuples (class-v class)))
Chong Yidong's avatar
Chong Yidong committed
359 360 361 362 363 364 365
	(f nil))
    (while (and ia (not f))
      (if (eq (cdr (car ia)) slot)
	  (setq f (car (car ia))))
      (setq ia (cdr ia)))
    f))

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
;;; Object Set macros
;;
(defmacro oset (obj slot value)
  "Set the value in OBJ for slot SLOT to VALUE.
SLOT is the slot name as specified in `defclass' or the tag created
with in the :initarg slot.  VALUE can be any Lisp object."
  `(eieio-oset ,obj (quote ,slot) ,value))

(defmacro oset-default (class slot value)
  "Set the default slot in CLASS for SLOT to VALUE.
The default value is usually set with the :initform tag during class
creation.  This allows users to change the default behavior of classes
after they are created."
  `(eieio-oset-default ,class (quote ,slot) ,value))

Chong Yidong's avatar
Chong Yidong committed
381 382 383
;;; CLOS queries into classes and slots
;;
(defun slot-boundp (object slot)
Juanma Barranquero's avatar
Juanma Barranquero committed
384
  "Return non-nil if OBJECT's SLOT is bound.
Chong Yidong's avatar
Chong Yidong committed
385 386 387 388 389 390
Setting a slot's value makes it bound.  Calling `slot-makeunbound' will
make a slot unbound.
OBJECT can be an instance or a class."
  ;; Skip typechecking while retrieving this value.
  (let ((eieio-skip-typecheck t))
    ;; Return nil if the magic symbol is in there.
391 392 393 394 395
    (not (eq (cond
	      ((eieio-object-p object) (eieio-oref object slot))
	      ((class-p object)        (eieio-oref-default object slot))
	      (t (signal 'wrong-type-argument (list 'eieio-object-p object))))
	     eieio-unbound))))
Chong Yidong's avatar
Chong Yidong committed
396 397 398 399 400 401

(defun slot-makeunbound (object slot)
  "In OBJECT, make SLOT unbound."
  (eieio-oset object slot eieio-unbound))

(defun slot-exists-p (object-or-class slot)
Juanma Barranquero's avatar
Juanma Barranquero committed
402
  "Return non-nil if OBJECT-OR-CLASS has SLOT."
Chong Yidong's avatar
Chong Yidong committed
403
  (let ((cv (class-v (cond ((eieio-object-p object-or-class)
404
			    (eieio-object-class object-or-class))
Chong Yidong's avatar
Chong Yidong committed
405 406 407
			   ((class-p object-or-class)
			    object-or-class))
		     )))
408 409
    (or (memq slot (eieio--class-public-a cv))
	(memq slot (eieio--class-class-allocation-a cv)))
Chong Yidong's avatar
Chong Yidong committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    ))

(defun find-class (symbol &optional errorp)
  "Return the class that SYMBOL represents.
If there is no class, nil is returned if ERRORP is nil.
If ERRORP is non-nil, `wrong-argument-type' is signaled."
  (if (not (class-p symbol))
      (if errorp (signal 'wrong-type-argument (list 'class-p symbol))
	nil)
    (class-v symbol)))

;;; Slightly more complex utility functions for objects
;;
(defun object-assoc (key slot list)
  "Return an object if KEY is `equal' to SLOT's value of an object in LIST.
Juanma Barranquero's avatar
Juanma Barranquero committed
425
LIST is a list of objects whose slots are searched.
Chong Yidong's avatar
Chong Yidong committed
426 427 428
Objects in LIST do not need to have a slot named SLOT, nor does
SLOT need to be bound.  If these errors occur, those objects will
be ignored."
429
  (eieio--check-type listp list)
Chong Yidong's avatar
Chong Yidong committed
430 431 432 433 434 435 436 437 438 439 440
  (while (and list (not (condition-case nil
			    ;; This prevents errors for missing slots.
			    (equal key (eieio-oref (car list) slot))
			  (error nil))))
    (setq list (cdr list)))
  (car list))

(defun object-assoc-list (slot list)
  "Return an association list with the contents of SLOT as the key element.
LIST must be a list of objects with SLOT in it.
This is useful when you need to do completing read on an object group."
441
  (eieio--check-type listp list)
Chong Yidong's avatar
Chong Yidong committed
442 443 444 445 446 447 448 449 450 451 452 453 454
  (let ((assoclist nil))
    (while list
      (setq assoclist (cons (cons (eieio-oref (car list) slot)
				  (car list))
			    assoclist))
      (setq list (cdr list)))
    (nreverse assoclist)))

(defun object-assoc-list-safe (slot list)
  "Return an association list with the contents of SLOT as the key element.
LIST must be a list of objects, but those objects do not need to have
SLOT in it.  If it does not, then that element is left out of the association
list."
455
  (eieio--check-type listp list)
Chong Yidong's avatar
Chong Yidong committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  (let ((assoclist nil))
    (while list
      (if (slot-exists-p (car list) slot)
	  (setq assoclist (cons (cons (eieio-oref (car list) slot)
				      (car list))
				assoclist)))
      (setq list (cdr list)))
    (nreverse assoclist)))

(defun object-add-to-list (object slot item &optional append)
  "In OBJECT's SLOT, add ITEM to the list of elements.
Optional argument APPEND indicates we need to append to the list.
If ITEM already exists in the list in SLOT, then it is not added.
Comparison is done with `equal' through the `member' function call.
If SLOT is unbound, bind it to the list containing ITEM."
  (let (ov)
    ;; Find the originating list.
    (if (not (slot-boundp object slot))
	(setq ov (list item))
      (setq ov (eieio-oref object slot))
      ;; turn it into a list.
      (unless (listp ov)
	(setq ov (list ov)))
      ;; Do the combination
      (if (not (member item ov))
	  (setq ov
		(if append
		    (append ov (list item))
		  (cons item ov)))))
    ;; Set back into the slot.
    (eieio-oset object slot ov)))

(defun object-remove-from-list (object slot item)
  "In OBJECT's SLOT, remove occurrences of ITEM.
Juanma Barranquero's avatar
Juanma Barranquero committed
490
Deletion is done with `delete', which deletes by side effect,
Chong Yidong's avatar
Chong Yidong committed
491 492 493 494 495 496
and comparisons are done with `equal'.
If SLOT is unbound, do nothing."
  (if (not (slot-boundp object slot))
      nil
    (eieio-oset object slot (delete item (eieio-oref object slot)))))

497 498
;;;
;; Method Calling Functions
Chong Yidong's avatar
Chong Yidong committed
499 500

(defun next-method-p ()
Juanma Barranquero's avatar
Juanma Barranquero committed
501
  "Return non-nil if there is a next method.
Chong Yidong's avatar
Chong Yidong committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515
Returns a list of lambda expressions which is the `next-method'
order."
  eieio-generic-call-next-method-list)

(defun call-next-method (&rest replacement-args)
  "Call the superclass method from a subclass method.
The superclass method is specified in the current method list,
and is called the next method.

If REPLACEMENT-ARGS is non-nil, then use them instead of
`eieio-generic-call-arglst'.  The generic arg list are the
arguments passed in at the top level.

Use `next-method-p' to find out if there is a next method to call."
516
  (if (not (eieio--scoped-class))
Juanma Barranquero's avatar
Juanma Barranquero committed
517
      (error "`call-next-method' not called within a class specific method"))
Chong Yidong's avatar
Chong Yidong committed
518 519 520 521 522 523 524 525 526 527 528
  (if (and (/= eieio-generic-call-key method-primary)
	   (/= eieio-generic-call-key method-static))
      (error "Cannot `call-next-method' except in :primary or :static methods")
    )
  (let ((newargs (or replacement-args eieio-generic-call-arglst))
	(next (car eieio-generic-call-next-method-list))
	)
    (if (or (not next) (not (car next)))
	(apply 'no-next-method (car newargs) (cdr newargs))
      (let* ((eieio-generic-call-next-method-list
	      (cdr eieio-generic-call-next-method-list))
529
	     (eieio-generic-call-arglst newargs)
Chong Yidong's avatar
Chong Yidong committed
530 531
	     (fcn (car next))
	     )
532 533
	(eieio--with-scoped-class (cdr next)
	  (apply fcn newargs)) ))))
534

Chong Yidong's avatar
Chong Yidong committed
535 536 537
;;; Here are some CLOS items that need the CL package
;;

538
(defsetf eieio-oref eieio-oset)
539 540

(if (eval-when-compile (fboundp 'gv-define-expander))
541
    ;; Not needed for Emacs>=24.3 since gv.el's setf expands macros and
542 543
    ;; follows aliases.
    nil
544
(defsetf slot-value eieio-oset)
Chong Yidong's avatar
Chong Yidong committed
545 546 547

;; The below setf method was written by Arnd Kohrs <kohrs@acm.org>
(define-setf-method oref (obj slot)
548 549 550 551 552 553 554 555 556 557
  (with-no-warnings
    (require 'cl)
    (let ((obj-temp (gensym))
	  (slot-temp (gensym))
	  (store-temp (gensym)))
      (list (list obj-temp slot-temp)
	    (list obj `(quote ,slot))
	    (list store-temp)
	    (list 'set-slot-value obj-temp slot-temp
		  store-temp)
558
	    (list 'slot-value obj-temp slot-temp))))))
Chong Yidong's avatar
Chong Yidong committed
559 560 561 562


;;;
;; We want all objects created by EIEIO to have some default set of
Paul Eggert's avatar
Paul Eggert committed
563
;; behaviors so we can create object utilities, and allow various
Chong Yidong's avatar
Chong Yidong committed
564 565 566 567 568 569 570 571 572
;; types of error checking.  To do this, create the default EIEIO
;; class, and when no parent class is specified, use this as the
;; default.  (But don't store it in the other classes as the default,
;; allowing for transparent support.)
;;

(defclass eieio-default-superclass nil
  nil
  "Default parent class for classes with no specified parent class.
Juanma Barranquero's avatar
Juanma Barranquero committed
573 574
Its slots are automatically adopted by classes with no specified parents.
This class is not stored in the `parent' slot of a class vector."
Chong Yidong's avatar
Chong Yidong committed
575 576 577 578 579
  :abstract t)

(defalias 'standard-class 'eieio-default-superclass)

(defgeneric constructor (class newname &rest slots)
Juanma Barranquero's avatar
Juanma Barranquero committed
580
  "Default constructor for CLASS `eieio-default-superclass'.")
Chong Yidong's avatar
Chong Yidong committed
581 582 583

(defmethod constructor :static
  ((class eieio-default-superclass) newname &rest slots)
Juanma Barranquero's avatar
Juanma Barranquero committed
584
  "Default constructor for CLASS `eieio-default-superclass'.
Chong Yidong's avatar
Chong Yidong committed
585 586 587 588 589
NEWNAME is the name to be given to the constructed object.
SLOTS are the initialization slots used by `shared-initialize'.
This static method is called when an object is constructed.
It allocates the vector used to represent an EIEIO object, and then
calls `shared-initialize' on that object."
590
  (let* ((new-object (copy-sequence (eieio--class-default-object-cache (class-v class)))))
Chong Yidong's avatar
Chong Yidong committed
591
    ;; Update the name for the newly created object.
592
    (setf (eieio--object-name new-object) newname)
Chong Yidong's avatar
Chong Yidong committed
593 594 595 596 597 598 599 600 601 602 603 604 605
    ;; Call the initialize method on the new object with the slots
    ;; that were passed down to us.
    (initialize-instance new-object slots)
    ;; Return the created object.
    new-object))

(defgeneric shared-initialize (obj slots)
  "Set slots of OBJ with SLOTS which is a list of name/value pairs.
Called from the constructor routine.")

(defmethod shared-initialize ((obj eieio-default-superclass) slots)
  "Set slots of OBJ with SLOTS which is a list of name/value pairs.
Called from the constructor routine."
606
  (eieio--with-scoped-class (eieio--object-class obj)
Chong Yidong's avatar
Chong Yidong committed
607
    (while slots
608
      (let ((rn (eieio-initarg-to-attribute (eieio--object-class obj)
Chong Yidong's avatar
Chong Yidong committed
609 610 611 612 613 614 615
					    (car slots))))
	(if (not rn)
	    (slot-missing obj (car slots) 'oset (car (cdr slots)))
	  (eieio-oset obj rn (car (cdr slots)))))
      (setq slots (cdr (cdr slots))))))

(defgeneric initialize-instance (this &optional slots)
Juanma Barranquero's avatar
Juanma Barranquero committed
616
  "Construct the new object THIS based on SLOTS.")
Chong Yidong's avatar
Chong Yidong committed
617 618 619

(defmethod initialize-instance ((this eieio-default-superclass)
				&optional slots)
Juanma Barranquero's avatar
Juanma Barranquero committed
620
  "Construct the new object THIS based on SLOTS.
Chong Yidong's avatar
Chong Yidong committed
621
SLOTS is a tagged list where odd numbered elements are tags, and
Juanma Barranquero's avatar
Juanma Barranquero committed
622 623 624 625 626
even numbered elements are the values to store in the tagged slot.
If you overload the `initialize-instance', there you will need to
call `shared-initialize' yourself, or you can call `call-next-method'
to have this constructor called automatically.  If these steps are
not taken, then new objects of your class will not have their values
Chong Yidong's avatar
Chong Yidong committed
627
dynamically set from SLOTS."
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  ;; First, see if any of our defaults are `lambda', and
  ;; re-evaluate them and apply the value to our slots.
  (let* ((this-class (class-v (eieio--object-class this)))
	 (slot (eieio--class-public-a this-class))
	 (defaults (eieio--class-public-d this-class)))
    (while slot
      ;; For each slot, see if we need to evaluate it.
      ;;
      ;; Paul Landes said in an email:
      ;; > CL evaluates it if it can, and otherwise, leaves it as
      ;; > the quoted thing as you already have.  This is by the
      ;; > Sonya E. Keene book and other things I've look at on the
      ;; > web.
      (let ((dflt (eieio-default-eval-maybe (car defaults))))
	(when (not (eq dflt (car defaults)))
	  (eieio-oset this (car slot) dflt) ))
      ;; Next.
      (setq slot (cdr slot)
	    defaults (cdr defaults))))
  ;; Shared initialize will parse our slots for us.
  (shared-initialize this slots))
Chong Yidong's avatar
Chong Yidong committed
649 650 651 652 653 654 655 656 657 658 659 660 661

(defgeneric slot-missing (object slot-name operation &optional new-value)
  "Method invoked when an attempt to access a slot in OBJECT fails.")

(defmethod slot-missing ((object eieio-default-superclass) slot-name
			 operation &optional new-value)
  "Method invoked when an attempt to access a slot in OBJECT fails.
SLOT-NAME is the name of the failed slot, OPERATION is the type of access
that was requested, and optional NEW-VALUE is the value that was desired
to be set.

This method is called from `oref', `oset', and other functions which
directly reference slots in EIEIO objects."
662
  (signal 'invalid-slot-name (list (eieio-object-name object)
Chong Yidong's avatar
Chong Yidong committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
				   slot-name)))

(defgeneric slot-unbound (object class slot-name fn)
  "Slot unbound is invoked during an attempt to reference an unbound slot.")

(defmethod slot-unbound ((object eieio-default-superclass)
			 class slot-name fn)
  "Slot unbound is invoked during an attempt to reference an unbound slot.
OBJECT is the instance of the object being reference.  CLASS is the
class of OBJECT, and SLOT-NAME is the offending slot.  This function
throws the signal `unbound-slot'.  You can overload this function and
return the value to use in place of the unbound value.
Argument FN is the function signaling this error.
Use `slot-boundp' to determine if a slot is bound or not.

In CLOS, the argument list is (CLASS OBJECT SLOT-NAME), but
EIEIO can only dispatch on the first argument, so the first two are swapped."
680
  (signal 'unbound-slot (list (eieio-class-name class) (eieio-object-name object)
Chong Yidong's avatar
Chong Yidong committed
681 682 683 684 685 686 687 688 689 690 691 692 693
			      slot-name fn)))

(defgeneric no-applicable-method (object method &rest args)
  "Called if there are no implementations for OBJECT in METHOD.")

(defmethod no-applicable-method ((object eieio-default-superclass)
				 method &rest args)
  "Called if there are no implementations for OBJECT in METHOD.
OBJECT is the object which has no method implementation.
ARGS are the arguments that were passed to METHOD.

Implement this for a class to block this signal.  The return
value becomes the return value of the original method call."
694
  (signal 'no-method-definition (list method (eieio-object-name object)))
Chong Yidong's avatar
Chong Yidong committed
695 696 697 698 699 700 701 702 703
  )

(defgeneric no-next-method (object &rest args)
"Called from `call-next-method' when no additional methods are available.")

(defmethod no-next-method ((object eieio-default-superclass)
			   &rest args)
  "Called from `call-next-method' when no additional methods are available.
OBJECT is othe object being called on `call-next-method'.
Juanma Barranquero's avatar
Juanma Barranquero committed
704
ARGS are the arguments it is called by.
Chong Yidong's avatar
Chong Yidong committed
705
This method signals `no-next-method' by default.  Override this
Juanma Barranquero's avatar
Juanma Barranquero committed
706
method to not throw an error, and its return value becomes the
Chong Yidong's avatar
Chong Yidong committed
707
return value of `call-next-method'."
708
  (signal 'no-next-method (list (eieio-object-name object) args))
709
  )
Chong Yidong's avatar
Chong Yidong committed
710 711 712 713 714 715 716 717 718 719 720

(defgeneric clone (obj &rest params)
  "Make a copy of OBJ, and then supply PARAMS.
PARAMS is a parameter list of the same form used by `initialize-instance'.

When overloading `clone', be sure to call `call-next-method'
first and modify the returned object.")

(defmethod clone ((obj eieio-default-superclass) &rest params)
  "Make a copy of OBJ, and then apply PARAMS."
  (let ((nobj (copy-sequence obj))
721
	(nm (eieio--object-name obj))
Chong Yidong's avatar
Chong Yidong committed
722 723 724 725 726 727 728 729
	(passname (and params (stringp (car params))))
	(num 1))
    (if params (shared-initialize nobj (if passname (cdr params) params)))
    (if (not passname)
	(save-match-data
	  (if (string-match "-\\([0-9]+\\)" nm)
	      (setq num (1+ (string-to-number (match-string 1 nm)))
		    nm (substring nm 0 (match-beginning 0))))
730 731
	  (setf (eieio--object-name nobj) (concat nm "-" (int-to-string num))))
      (setf (eieio--object-name nobj) (car params)))
Chong Yidong's avatar
Chong Yidong committed
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    nobj))

(defgeneric destructor (this &rest params)
  "Destructor for cleaning up any dynamic links to our object.")

(defmethod destructor ((this eieio-default-superclass) &rest params)
  "Destructor for cleaning up any dynamic links to our object.
Argument THIS is the object being destroyed.  PARAMS are additional
ignored parameters."
  ;; No cleanup... yet.
  )

(defgeneric object-print (this &rest strings)
  "Pretty printer for object THIS.  Call function `object-name' with STRINGS.

It is sometimes useful to put a summary of the object into the
Juanma Barranquero's avatar
Juanma Barranquero committed
748
default #<notation> string when using EIEIO browsing tools.
Chong Yidong's avatar
Chong Yidong committed
749 750 751 752 753 754 755 756
Implement this method to customize the summary.")

(defmethod object-print ((this eieio-default-superclass) &rest strings)
  "Pretty printer for object THIS.  Call function `object-name' with STRINGS.
The default method for printing object THIS is to use the
function `object-name'.

It is sometimes useful to put a summary of the object into the
Juanma Barranquero's avatar
Juanma Barranquero committed
757
default #<notation> string when using EIEIO browsing tools.
Chong Yidong's avatar
Chong Yidong committed
758 759 760 761 762

Implement this function and specify STRINGS in a call to
`call-next-method' to provide additional summary information.
When passing in extra strings from child classes, always remember
to prepend a space."
763
  (eieio-object-name this (apply 'concat strings)))
Chong Yidong's avatar
Chong Yidong committed
764 765 766 767 768 769

(defvar eieio-print-depth 0
  "When printing, keep track of the current indentation depth.")

(defgeneric object-write (this &optional comment)
  "Write out object THIS to the current stream.
Juanma Barranquero's avatar
Juanma Barranquero committed
770
Optional COMMENT will add comments to the beginning of the output.")
Chong Yidong's avatar
Chong Yidong committed
771 772 773 774 775 776 777 778 779

(defmethod object-write ((this eieio-default-superclass) &optional comment)
  "Write object THIS out to the current stream.
This writes out the vector version of this object.  Complex and recursive
object are discouraged from being written.
  If optional COMMENT is non-nil, include comments when outputting
this object."
  (when comment
    (princ ";; Object ")
780
    (princ (eieio-object-name-string this))
Chong Yidong's avatar
Chong Yidong committed
781 782 783
    (princ "\n")
    (princ comment)
    (princ "\n"))
784
  (let* ((cl (eieio-object-class this))
Chong Yidong's avatar
Chong Yidong committed
785 786 787 788 789 790 791
	 (cv (class-v cl)))
    ;; Now output readable lisp to recreate this object
    ;; It should look like this:
    ;; (<constructor> <name> <slot> <slot> ... )
    ;; Each slot's slot is writen using its :writer.
    (princ (make-string (* eieio-print-depth 2) ? ))
    (princ "(")
792
    (princ (symbol-name (class-constructor (eieio-object-class this))))
Chong Yidong's avatar
Chong Yidong committed
793
    (princ " ")
794
    (prin1 (eieio-object-name-string this))
Chong Yidong's avatar
Chong Yidong committed
795
    (princ "\n")
Chong Yidong's avatar
Chong Yidong committed
796
    ;; Loop over all the public slots
797 798 799
    (let ((publa (eieio--class-public-a cv))
	  (publd (eieio--class-public-d cv))
	  (publp (eieio--class-public-printer cv))
Chong Yidong's avatar
Chong Yidong committed
800 801 802 803 804 805 806
	  (eieio-print-depth (1+ eieio-print-depth)))
      (while publa
	(when (slot-boundp this (car publa))
	  (let ((i (class-slot-initarg cl (car publa)))
		(v (eieio-oref this (car publa)))
		)
	    (unless (or (not i) (equal v (car publd)))
807 808
	      (unless (bolp)
		(princ "\n"))
Chong Yidong's avatar
Chong Yidong committed
809 810 811 812
	      (princ (make-string (* eieio-print-depth 2) ? ))
	      (princ (symbol-name i))
	      (if (car publp)
		  ;; Use our public printer
813 814 815
		  (progn
		    (princ " ")
		    (funcall (car publp) v))
Chong Yidong's avatar
Chong Yidong committed
816
		;; Use our generic override prin1 function.
817 818 819 820
		(princ (if (or (eieio-object-p v)
                               (eieio-object-p (car-safe v)))
                           "\n" " "))
		(eieio-override-prin1 v)))))
Chong Yidong's avatar
Chong Yidong committed
821
	(setq publa (cdr publa) publd (cdr publd)
822 823 824 825
	      publp (cdr publp))))
    (princ ")")
    (when (= eieio-print-depth 0)
      (princ "\n"))))
Chong Yidong's avatar
Chong Yidong committed
826 827

(defun eieio-override-prin1 (thing)
Juanma Barranquero's avatar
Juanma Barranquero committed
828
  "Perform a `prin1' on THING taking advantage of object knowledge."
Chong Yidong's avatar
Chong Yidong committed
829 830
  (cond ((eieio-object-p thing)
	 (object-write thing))
831
	((consp thing)
Chong Yidong's avatar
Chong Yidong committed
832 833
	 (eieio-list-prin1 thing))
	((class-p thing)
834
	 (princ (eieio-class-name thing)))
835 836
	((or (keywordp thing) (booleanp thing))
	 (prin1 thing))
Chong Yidong's avatar
Chong Yidong committed
837 838 839 840 841 842 843 844 845 846 847
	((symbolp thing)
	 (princ (concat "'" (symbol-name thing))))
	(t (prin1 thing))))

(defun eieio-list-prin1 (list)
  "Display LIST where list may contain objects."
  (if (not (eieio-object-p (car list)))
      (progn
	(princ "'")
	(prin1 list))
    (princ (make-string (* eieio-print-depth 2) ? ))
848 849 850 851 852 853 854 855 856
    (princ "(list")
    (let ((eieio-print-depth (1+ eieio-print-depth)))
      (while list
	(princ "\n")
	(if (eieio-object-p (car list))
	    (object-write (car list))
	  (princ (make-string (* eieio-print-depth 2) ? ))
	  (eieio-override-prin1 (car list)))
	(setq list (cdr list))))
Chong Yidong's avatar
Chong Yidong committed
857 858 859 860 861 862 863 864 865
    (princ ")")))


;;; Unimplemented functions from CLOS
;;
(defun change-class (obj class)
  "Change the class of OBJ to type CLASS.
This may create or delete slots, but does not affect the return value
of `eq'."
Juanma Barranquero's avatar
Juanma Barranquero committed
866
  (error "EIEIO: `change-class' is unimplemented"))
Chong Yidong's avatar
Chong Yidong committed
867

868 869 870 871
;; Hook ourselves into help system for describing classes and methods.
(add-hook 'help-fns-describe-function-functions 'eieio-help-generic)
(add-hook 'help-fns-describe-function-functions 'eieio-help-constructor)

Chong Yidong's avatar
Chong Yidong committed
872 873 874
;;; Interfacing with edebug
;;
(defun eieio-edebug-prin1-to-string (object &optional noescape)
Juanma Barranquero's avatar
Juanma Barranquero committed
875 876
  "Display EIEIO OBJECT in fancy format.
Overrides the edebug default.
Chong Yidong's avatar
Chong Yidong committed
877
Optional argument NOESCAPE is passed to `prin1-to-string' when appropriate."
878
  (cond ((class-p object) (eieio-class-name object))
Chong Yidong's avatar
Chong Yidong committed
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
	((eieio-object-p object) (object-print object))
	((and (listp object) (or (class-p (car object))
				 (eieio-object-p (car object))))
	 (concat "(" (mapconcat 'eieio-edebug-prin1-to-string object " ") ")"))
	(t (prin1-to-string object noescape))))

(add-hook 'edebug-setup-hook
	  (lambda ()
	    (def-edebug-spec defmethod
	      (&define			; this means we are defining something
	       [&or name ("setf" :name setf name)]
	       ;; ^^ This is the methods symbol
	       [ &optional symbolp ]    ; this is key :before etc
	       list              ; arguments
	       [ &optional stringp ]    ; documentation string
	       def-body	                ; part to be debugged
	       ))
	    ;; The rest of the macros
	    (def-edebug-spec oref (form quote))
	    (def-edebug-spec oref-default (form quote))
	    (def-edebug-spec oset (form quote form))
	    (def-edebug-spec oset-default (form quote form))
	    (def-edebug-spec class-v form)
	    (def-edebug-spec class-p form)
	    (def-edebug-spec eieio-object-p form)
	    (def-edebug-spec class-constructor form)
	    (def-edebug-spec generic-p form)
	    (def-edebug-spec with-slots (list list def-body))
	    ;; I suspect this isn't the best way to do this, but when
	    ;; cust-print was used on my system all my objects
	    ;; appeared as "#1 =" which was not useful.  This allows
	    ;; edebug to print my objects in the nice way they were
	    ;; meant to with `object-print' and `class-name'
	    ;; (defalias 'edebug-prin1-to-string 'eieio-edebug-prin1-to-string)
	    )
	  )

916 917 918

;;; Start of automatically extracted autoloads.

919
;;;### (autoloads nil "eieio-custom" "eieio-custom.el" "5b0e7b1beea11f9e9de6887279f75d61")
920 921 922 923 924 925 926 927 928 929
;;; Generated autoloads from eieio-custom.el

(autoload 'customize-object "eieio-custom" "\
Customize OBJ in a custom buffer.
Optional argument GROUP is the sub-group of slots to display.

\(fn OBJ &optional GROUP)" nil nil)

;;;***

930
;;;### (autoloads nil "eieio-opt" "eieio-opt.el" "c7a7173e78edd280eb4289bd2a0376c5")
931 932 933 934 935 936 937 938 939
;;; Generated autoloads from eieio-opt.el

(autoload 'eieio-browse "eieio-opt" "\
Create an object browser window to show all objects.
If optional ROOT-CLASS, then start with that, otherwise start with
variable `eieio-default-superclass'.

\(fn &optional ROOT-CLASS)" t nil)

940 941
(autoload 'eieio-help-class "eieio-opt" "\
Print help description for CLASS.
942 943
If CLASS is actually an object, then also display current values of that object.

944
\(fn CLASS)" nil nil)
945

946 947
(autoload 'eieio-help-constructor "eieio-opt" "\
Describe CTR if it is a class constructor.
948

949
\(fn CTR)" nil nil)
950

951 952
(autoload 'eieio-help-generic "eieio-opt" "\
Describe GENERIC if it is a generic function.
953

954
\(fn GENERIC)" nil nil)
955 956 957 958

;;;***

;;; End of automatically extracted autoloads.
Chong Yidong's avatar
Chong Yidong committed
959 960 961 962

(provide 'eieio)

;;; eieio ends here