eieio.el 118 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-2011  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.3
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
Stefan Monnier's avatar
Stefan Monnier committed
48
  (require 'cl))
Chong Yidong's avatar
Chong Yidong committed
49

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

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

(eval-and-compile
Juanma Barranquero's avatar
Juanma Barranquero committed
59
;; About the above.  EIEIO must process its own code when it compiles
Chong Yidong's avatar
Chong Yidong committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
;; itself, thus, by eval-and-compiling outselves, we solve the problem.

;; Compatibility
(if (fboundp 'compiled-function-arglist)

    ;; XEmacs can only access a compiled functions arglist like this:
    (defalias 'eieio-compiled-function-arglist 'compiled-function-arglist)

  ;; Emacs doesn't have this function, but since FUNC is a vector, we can just
  ;; grab the appropriate element.
  (defun eieio-compiled-function-arglist (func)
    "Return the argument list for the compiled function FUNC."
    (aref func 0))

  )


;;;
;; Variable declarations.
;;

(defvar eieio-hook nil
  "*This hook is executed, then cleared each time `defclass' is called.")

(defvar eieio-error-unsupported-class-tags nil
85
  "Non-nil to throw an error if an encountered tag is unsupported.
Chong Yidong's avatar
Chong Yidong committed
86 87 88 89 90 91 92 93 94 95 96 97 98
This may prevent classes from CLOS applications from being used with EIEIO
since EIEIO does not support all CLOS tags.")

(defvar eieio-skip-typecheck nil
  "*If non-nil, skip all slot typechecking.
Set this to t permanently if a program is functioning well to get a
small speed increase.  This variable is also used internally to handle
default setting for optimization purposes.")

(defvar eieio-optimize-primary-methods-flag t
  "Non-nil means to optimize the method dispatch on primary methods.")

;; State Variables
99
;; FIXME: These two constants below should have an `eieio-' prefix added!!
Chong Yidong's avatar
Chong Yidong committed
100 101 102 103 104 105
(defvar this nil
  "Inside a method, this variable is the object in question.
DO NOT SET THIS YOURSELF unless you are trying to simulate friendly slots.

Note: Embedded methods are no longer supported.  The variable THIS is
still set for CLOS methods for the sake of routines like
Juanma Barranquero's avatar
Juanma Barranquero committed
106
`call-next-method'.")
Chong Yidong's avatar
Chong Yidong committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

(defvar scoped-class nil
  "This is set to a class when a method is running.
This is so we know we are allowed to check private parts or how to
execute a `call-next-method'.  DO NOT SET THIS YOURSELF!")

(defvar eieio-initializing-object  nil
  "Set to non-nil while initializing an object.")

(defconst eieio-unbound
  (if (and (boundp 'eieio-unbound) (symbolp eieio-unbound))
      eieio-unbound
    (make-symbol "unbound"))
  "Uninterned symbol representing an unbound slot in an object.")

;; This is a bootstrap for eieio-default-superclass so it has a value
;; while it is being built itself.
(defvar eieio-default-superclass nil)

126
;; FIXME: The constants below should have an `eieio-' prefix added!!
Chong Yidong's avatar
Chong Yidong committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
(defconst class-symbol 1 "Class's symbol (self-referencing.).")
(defconst class-parent 2 "Class parent slot.")
(defconst class-children 3 "Class children class slot.")
(defconst class-symbol-obarray 4 "Obarray permitting fast access to variable position indexes.")
;; @todo
;; the word "public" here is leftovers from the very first version.
;; Get rid of it!
(defconst class-public-a 5 "Class attribute index.")
(defconst class-public-d 6 "Class attribute defaults index.")
(defconst class-public-doc 7 "Class documentation strings for attributes.")
(defconst class-public-type 8 "Class type for a slot.")
(defconst class-public-custom 9 "Class custom type for a slot.")
(defconst class-public-custom-label 10 "Class custom group for a slot.")
(defconst class-public-custom-group 11 "Class custom group for a slot.")
(defconst class-public-printer 12 "Printer for a slot.")
(defconst class-protection 13 "Class protection for a slot.")
(defconst class-initarg-tuples 14 "Class initarg tuples list.")
(defconst class-class-allocation-a 15 "Class allocated attributes.")
(defconst class-class-allocation-doc 16 "Class allocated documentation.")
(defconst class-class-allocation-type 17 "Class allocated value type.")
(defconst class-class-allocation-custom 18 "Class allocated custom descriptor.")
(defconst class-class-allocation-custom-label 19 "Class allocated custom descriptor.")
(defconst class-class-allocation-custom-group 20 "Class allocated custom group.")
(defconst class-class-allocation-printer 21 "Class allocated printer for a slot.")
(defconst class-class-allocation-protection 22 "Class allocated protection list.")
(defconst class-class-allocation-values 23 "Class allocated value vector.")
(defconst class-default-object-cache 24
  "Cache index of what a newly created object would look like.
This will speed up instantiation time as only a `copy-sequence' will
be needed, instead of looping over all the values and setting them
from the default.")
(defconst class-options 25
  "Storage location of tagged class options.
Stored outright without modifications or stripping.")

(defconst class-num-slots 26
  "Number of slots in the class definition object.")

(defconst object-class 1 "Index in an object vector where the class is stored.")
(defconst object-name 2 "Index in an object where the name is stored.")

(defconst method-static 0 "Index into :static tag on a method.")
(defconst method-before 1 "Index into :before tag on a method.")
(defconst method-primary 2 "Index into :primary tag on a method.")
(defconst method-after 3 "Index into :after tag on a method.")
(defconst method-num-lists 4 "Number of indexes into methods vector in which groups of functions are kept.")
(defconst method-generic-before 4 "Index into generic :before tag on a method.")
(defconst method-generic-primary 5 "Index into generic :primary tag on a method.")
(defconst method-generic-after 6 "Index into generic :after tag on a method.")
(defconst method-num-slots 7 "Number of indexes into a method's vector.")

178 179 180 181 182 183 184
(defsubst eieio-specialized-key-to-generic-key (key)
  "Convert a specialized KEY into a generic method key."
  (cond ((eq key method-static) 0) ;; don't convert
	((< key method-num-lists) (+ key 3)) ;; The conversion
	(t key) ;; already generic.. maybe.
	))

Chong Yidong's avatar
Chong Yidong committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

;;; Important macros used in eieio.
;;
(defmacro class-v (class)
  "Internal: Return the class vector from the CLASS symbol."
  ;; No check: If eieio gets this far, it's probably been checked already.
  `(get ,class 'eieio-class-definition))

(defmacro class-p (class)
  "Return t if CLASS is a valid class vector.
CLASS is a symbol."
  ;; this new method is faster since it doesn't waste time checking lots of
  ;; things.
  `(condition-case nil
       (eq (aref (class-v ,class) 0) 'defclass)
     (error nil)))

(defmacro eieio-object-p (obj)
  "Return non-nil if OBJ is an EIEIO object."
  `(condition-case nil
       (let ((tobj ,obj))
	 (and (eq (aref tobj 0) 'object)
	      (class-p (aref tobj object-class))))
     (error nil)))
(defalias 'object-p 'eieio-object-p)

(defmacro class-constructor (class)
  "Return the symbol representing the constructor of CLASS."
  `(aref (class-v ,class) class-symbol))

(defmacro generic-p (method)
  "Return t if symbol METHOD is a generic function.
Juanma Barranquero's avatar
Juanma Barranquero committed
217 218
Only methods have the symbol `eieio-method-obarray' as a property
\(which contains a list of all bindings to that method type.)"
Chong Yidong's avatar
Chong Yidong committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
  `(and (fboundp ,method) (get ,method 'eieio-method-obarray)))

(defun generic-primary-only-p (method)
  "Return t if symbol METHOD is a generic function with only primary methods.
Only methods have the symbol `eieio-method-obarray' as a property (which
contains a list of all bindings to that method type.)
Methods with only primary implementations are executed in an optimized way."
  (and (generic-p method)
       (let ((M (get method 'eieio-method-tree)))
	 (and (< 0 (length (aref M method-primary)))
	      (not (aref M method-static))
	      (not (aref M method-before))
	      (not (aref M method-after))
	      (not (aref M method-generic-before))
	      (not (aref M method-generic-primary))
	      (not (aref M method-generic-after))))
       ))

(defun generic-primary-only-one-p (method)
  "Return t if symbol METHOD is a generic function with only primary methods.
Only methods have the symbol `eieio-method-obarray' as a property (which
contains a list of all bindings to that method type.)
Methods with only primary implementations are executed in an optimized way."
  (and (generic-p method)
       (let ((M (get method 'eieio-method-tree)))
	 (and (= 1 (length (aref M method-primary)))
	      (not (aref M method-static))
	      (not (aref M method-before))
	      (not (aref M method-after))
	      (not (aref M method-generic-before))
	      (not (aref M method-generic-primary))
	      (not (aref M method-generic-after))))
       ))

(defmacro class-option-assoc (list option)
254
  "Return from LIST the found OPTION, or nil if it doesn't exist."
Chong Yidong's avatar
Chong Yidong committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  `(car-safe (cdr (memq ,option ,list))))

(defmacro class-option (class option)
  "Return the value stored for CLASS' OPTION.
Return nil if that option doesn't exist."
  `(class-option-assoc (aref (class-v ,class) class-options) ',option))

(defmacro class-abstract-p (class)
  "Return non-nil if CLASS is abstract.
Abstract classes cannot be instantiated."
  `(class-option ,class :abstract))

(defmacro class-method-invocation-order (class)
  "Return the invocation order of CLASS.
Abstract classes cannot be instantiated."
  `(or (class-option ,class :method-invocation-order)
       :breadth-first))


;;; 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
284 285 286 287 288 289 290 291
  :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
292 293 294 295 296
  :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
297
                Defaults to `:public'.  Also use `:protected', or `:private'.
Chong Yidong's avatar
Chong Yidong committed
298 299 300 301 302 303 304
  :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
305
of documentation (including a :documentation tag), in addition to
Chong Yidong's avatar
Chong Yidong committed
306 307 308 309 310 311
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
312
  :allow-nil-initform - Non-nil to skip typechecking of null initforms.
Chong Yidong's avatar
Chong Yidong committed
313 314 315 316 317 318
  :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
319
                      - Control the method invocation order if there is
Chong Yidong's avatar
Chong Yidong committed
320 321 322 323 324 325 326 327 328 329
                        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
330 331
Due to the way class options are set up, you can add any tags you wish,
and reference them using the function `class-option'."
Chong Yidong's avatar
Chong Yidong committed
332 333 334 335 336 337 338 339 340 341 342 343 344
  ;; We must `eval-and-compile' this so that when we byte compile
  ;; an eieio program, there is no need to load it ahead of time.
  ;; It also provides lots of nice debugging errors at compile time.
  `(eval-and-compile
     (eieio-defclass ',name ',superclass ',slots ',options-and-doc)))

(defvar eieio-defclass-autoload-map (make-vector 7 nil)
  "Symbol map of superclasses we find in autoloads.")

;; We autoload this because it's used in `make-autoload'.
;;;###autoload
(defun eieio-defclass-autoload (cname superclasses filename doc)
  "Create autoload symbols for the EIEIO class CNAME.
Glenn Morris's avatar
Glenn Morris committed
345
SUPERCLASSES are the superclasses that CNAME inherits from.
Chong Yidong's avatar
Chong Yidong committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
DOC is the docstring for CNAME.
This function creates a mock-class for CNAME and adds it into
SUPERCLASSES as children.
It creates an autoload function for CNAME's constructor."
  ;; Assume we've already debugged inputs.

  (let* ((oldc (when (class-p cname) (class-v cname)))
	 (newc (make-vector class-num-slots nil))
	 )
    (if oldc
	nil ;; Do nothing if we already have this class.

      ;; Create the class in NEWC, but don't fill anything else in.
      (aset newc 0 'defclass)
      (aset newc class-symbol cname)

      (let ((clear-parent nil))
	;; No parents?
	(when (not superclasses)
	  (setq superclasses '(eieio-default-superclass)
		clear-parent t)
	  )

	;; Hook our new class into the existing structures so we can
	;; autoload it later.
	(dolist (SC superclasses)


	  ;; TODO - If we create an autoload that is in the map, that
	  ;;        map needs to be cleared!


	  ;; Does our parent exist?
	  (if (not (class-p SC))

	      ;; Create a symbol for this parent, and then store this
	      ;; parent on that symbol.
	      (let ((sym (intern (symbol-name SC) eieio-defclass-autoload-map)))
		(if (not (boundp sym))
		    (set sym (list cname))
		  (add-to-list sym cname))
		)

	    ;; We have a parent, save the child in there.
	    (when (not (member cname (aref (class-v SC) class-children)))
	      (aset (class-v SC) class-children
		    (cons cname (aref (class-v SC) class-children)))))

	  ;; save parent in child
	  (aset newc class-parent (cons SC (aref newc class-parent)))
	  )

Paul Eggert's avatar
Paul Eggert committed
398
	;; turn this into a usable self-pointing symbol
Chong Yidong's avatar
Chong Yidong committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
	(set cname cname)

	;; Store the new class vector definition into the symbol.  We need to
	;; do this first so that we can call defmethod for the accessor.
	;; The vector will be updated by the following while loop and will not
	;; need to be stored a second time.
	(put cname 'eieio-class-definition newc)

	;; Clear the parent
	(if clear-parent (aset newc class-parent nil))

	;; Create an autoload on top of our constructor function.
	(autoload cname filename doc nil nil)
	(autoload (intern (concat (symbol-name cname) "-p")) filename "" nil nil)
	(autoload (intern (concat (symbol-name cname) "-child-p")) filename "" nil nil)

	))))

(defsubst eieio-class-un-autoload (cname)
Juanma Barranquero's avatar
Juanma Barranquero committed
418
  "If class CNAME is in an autoload state, load its file."
Chong Yidong's avatar
Chong Yidong committed
419 420 421 422
  (when (eq (car-safe (symbol-function cname)) 'autoload)
    (load-library (car (cdr (symbol-function cname))))))

(defun eieio-defclass (cname superclasses slots options-and-doc)
423
  ;; FIXME: Most of this should be moved to the `defclass' macro.
Juanma Barranquero's avatar
Juanma Barranquero committed
424 425 426 427
  "Define CNAME as a new subclass of SUPERCLASSES.
SLOTS are the slots residing in that class definition, and options or
documentation OPTIONS-AND-DOC is the toplevel documentation for this class.
See `defclass' for more information."
Chong Yidong's avatar
Chong Yidong committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  ;; Run our eieio-hook each time, and clear it when we are done.
  ;; This way people can add hooks safely if they want to modify eieio
  ;; or add definitions when eieio is loaded or something like that.
  (run-hooks 'eieio-hook)
  (setq eieio-hook nil)

  (if (not (symbolp cname)) (signal 'wrong-type-argument '(symbolp cname)))
  (if (not (listp superclasses)) (signal 'wrong-type-argument '(listp superclasses)))

  (let* ((pname (if superclasses superclasses nil))
	 (newc (make-vector class-num-slots nil))
	 (oldc (when (class-p cname) (class-v cname)))
	 (groups nil) ;; list of groups id'd from slots
	 (options nil)
	 (clearparent nil))

    (aset newc 0 'defclass)
    (aset newc class-symbol cname)

Juanma Barranquero's avatar
Juanma Barranquero committed
447
    ;; If this class already existed, and we are updating its structure,
Chong Yidong's avatar
Chong Yidong committed
448 449 450 451 452 453 454 455 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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    ;; make sure we keep the old child list.  This can cause bugs, but
    ;; if no new slots are created, it also saves time, and prevents
    ;; method table breakage, particularly when the users is only
    ;; byte compiling an EIEIO file.
    (if oldc
	(aset newc class-children (aref oldc class-children))
      ;; If the old class did not exist, but did exist in the autoload map, then adopt those children.
      ;; This is like the above, but deals with autoloads nicely.
      (let ((sym (intern-soft (symbol-name cname) eieio-defclass-autoload-map)))
	(when sym
	  (condition-case nil
	      (aset newc class-children (symbol-value sym))
	    (error nil))
	  (unintern (symbol-name cname) eieio-defclass-autoload-map)
	  ))
      )

    (cond ((and (stringp (car options-and-doc))
		(/= 1 (% (length options-and-doc) 2)))
	   (error "Too many arguments to `defclass'"))
	  ((and (symbolp (car options-and-doc))
		(/= 0 (% (length options-and-doc) 2)))
	   (error "Too many arguments to `defclass'"))
	  )

    (setq options
	  (if (stringp (car options-and-doc))
	      (cons :documentation options-and-doc)
	    options-and-doc))

    (if pname
	(progn
	  (while pname
	    (if (and (car pname) (symbolp (car pname)))
		(if (not (class-p (car pname)))
		    ;; bad class
		    (error "Given parent class %s is not a class" (car pname))
		  ;; good parent class...
		  ;; save new child in parent
		  (when (not (member cname (aref (class-v (car pname)) class-children)))
		    (aset (class-v (car pname)) class-children
			  (cons cname (aref (class-v (car pname)) class-children))))
		  ;; Get custom groups, and store them into our local copy.
		  (mapc (lambda (g) (add-to-list 'groups g))
			(class-option (car pname) :custom-groups))
		  ;; save parent in child
		  (aset newc class-parent (cons (car pname) (aref newc class-parent))))
	      (error "Invalid parent class %s" pname))
	    (setq pname (cdr pname)))
	  ;; Reverse the list of our parents so that they are prioritized in
	  ;; the same order as specified in the code.
	  (aset newc class-parent (nreverse (aref newc class-parent))) )
      ;; If there is nothing to loop over, then inherit from the
      ;; default superclass.
      (unless (eq cname 'eieio-default-superclass)
	;; adopt the default parent here, but clear it later...
	(setq clearparent t)
	;; save new child in parent
	(if (not (member cname (aref (class-v 'eieio-default-superclass) class-children)))
	    (aset (class-v 'eieio-default-superclass) class-children
		  (cons cname (aref (class-v 'eieio-default-superclass) class-children))))
	;; save parent in child
	(aset newc class-parent (list eieio-default-superclass))))

Paul Eggert's avatar
Paul Eggert committed
512
    ;; turn this into a usable self-pointing symbol
Chong Yidong's avatar
Chong Yidong committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    (set cname cname)

    ;; These two tests must be created right away so we can have self-
    ;; referencing classes.  ei, a class whose slot can contain only
    ;; pointers to itself.

    ;; Create the test function
    (let ((csym (intern (concat (symbol-name cname) "-p"))))
      (fset csym
	    (list 'lambda (list 'obj)
		  (format "Test OBJ to see if it an object of type %s" cname)
		  (list 'and '(eieio-object-p obj)
			(list 'same-class-p 'obj cname)))))

    ;; Make sure the method invocation order  is a valid value.
    (let ((io (class-option-assoc options :method-invocation-order)))
529
      (when (and io (not (member io '(:depth-first :breadth-first :c3))))
Chong Yidong's avatar
Chong Yidong committed
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
	(error "Method invocation order %s is not allowed" io)
	))

    ;; Create a handy child test too
    (let ((csym (intern (concat (symbol-name cname) "-child-p"))))
      (fset csym
	    `(lambda (obj)
	       ,(format
		  "Test OBJ to see if it an object is a child of type %s"
		  cname)
	       (and (eieio-object-p obj)
		    (object-of-class-p obj ,cname))))

      ;; When using typep, (typep OBJ 'myclass) returns t for objects which
      ;; are subclasses of myclass.  For our predicates, however, it is
      ;; important for EIEIO to be backwards compatible, where
      ;; myobject-p, and myobject-child-p are different.
      ;; "cl" uses this technique to specify symbols with specific typep
      ;; test, so we can let typep have the CLOS documented behavior
      ;; while keeping our above predicate clean.

551 552 553 554
      ;; It would be cleaner to use `defsetf' here, but that requires cl
      ;; at runtime.
      (put cname 'cl-deftype-handler
	   (list 'lambda () `(list 'satisfies (quote ,csym)))))
Chong Yidong's avatar
Chong Yidong committed
555

Juanma Barranquero's avatar
Juanma Barranquero committed
556
    ;; before adding new slots, let's add all the methods and classes
Chong Yidong's avatar
Chong Yidong committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    ;; in from the parent class
    (eieio-copy-parents-into-subclass newc superclasses)

    ;; Store the new class vector definition into the symbol.  We need to
    ;; do this first so that we can call defmethod for the accessor.
    ;; The vector will be updated by the following while loop and will not
    ;; need to be stored a second time.
    (put cname 'eieio-class-definition newc)

    ;; Query each slot in the declaration list and mangle into the
    ;; class structure I have defined.
    (while slots
      (let* ((slot1  (car slots))
	     (name    (car slot1))
	     (slot   (cdr slot1))
	     (acces   (plist-get slot ':accessor))
	     (init    (or (plist-get slot ':initform)
			  (if (member ':initform slot) nil
			    eieio-unbound)))
	     (initarg (plist-get slot ':initarg))
	     (docstr  (plist-get slot ':documentation))
	     (prot    (plist-get slot ':protection))
	     (reader  (plist-get slot ':reader))
	     (writer  (plist-get slot ':writer))
	     (alloc   (plist-get slot ':allocation))
	     (type    (plist-get slot ':type))
	     (custom  (plist-get slot ':custom))
	     (label   (plist-get slot ':label))
	     (customg (plist-get slot ':group))
	     (printer (plist-get slot ':printer))

	     (skip-nil (class-option-assoc options :allow-nil-initform))
	     )

	(if eieio-error-unsupported-class-tags
	    (let ((tmp slot))
	      (while tmp
		(if (not (member (car tmp) '(:accessor
					     :initform
					     :initarg
					     :documentation
					     :protection
					     :reader
					     :writer
					     :allocation
					     :type
					     :custom
					     :label
					     :group
					     :printer
					     :allow-nil-initform
					     :custom-groups)))
		    (signal 'invalid-slot-type (list (car tmp))))
		(setq tmp (cdr (cdr tmp))))))

	;; Clean up the meaning of protection.
	(cond ((or (eq prot 'public) (eq prot :public)) (setq prot nil))
	      ((or (eq prot 'protected) (eq prot :protected)) (setq prot 'protected))
	      ((or (eq prot 'private) (eq prot :private)) (setq prot 'private))
	      ((eq prot nil) nil)
	      (t (signal 'invalid-slot-type (list ':protection prot))))

	;; Make sure the :allocation parameter has a valid value.
	(if (not (or (not alloc) (eq alloc :class) (eq alloc :instance)))
	    (signal 'invalid-slot-type (list ':allocation alloc)))

	;; The default type specifier is supposed to be t, meaning anything.
	(if (not type) (setq type t))

	;; Label is nil, or a string
	(if (not (or (null label) (stringp label)))
	    (signal 'invalid-slot-type (list ':label label)))

	;; Is there an initarg, but allocation of class?
	(if (and initarg (eq alloc :class))
	    (message "Class allocated slots do not need :initarg"))

	;; intern the symbol so we can use it blankly
	(if initarg (set initarg initarg))

	;; The customgroup should be a list of symbols
	(cond ((null customg)
	       (setq customg '(default)))
	      ((not (listp customg))
	       (setq customg (list customg))))
	;; The customgroup better be a symbol, or list of symbols.
	(mapc (lambda (cg)
		(if (not (symbolp cg))
		    (signal 'invalid-slot-type (list ':group cg))))
		customg)

	;; First up, add this slot into our new class.
	(eieio-add-new-slot newc name init docstr type custom label customg printer
			     prot initarg alloc 'defaultoverride skip-nil)

	;; We need to id the group, and store them in a group list attribute.
	(mapc (lambda (cg) (add-to-list 'groups cg)) customg)

	;; anyone can have an accessor function.  This creates a function
	;; of the specified name, and also performs a `defsetf' if applicable
	;; so that users can `setf' the space returned by this function
	(if acces
	    (progn
660 661 662 663
	      (eieio--defmethod
               acces (if (eq alloc :class) :static :primary) cname
               `(lambda (this)
                  ,(format
Chong Yidong's avatar
Chong Yidong committed
664 665
		       "Retrieves the slot `%s' from an object of class `%s'"
		       name cname)
666 667
                  (if (slot-boundp this ',name)
                      (eieio-oref this ',name)
Chong Yidong's avatar
Chong Yidong committed
668
			    ;; Else - Some error?  nil?
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
			    nil)))

	      ;; Provide a setf method.  It would be cleaner to use
	      ;; defsetf, but that would require CL at runtime.
	      (put acces 'setf-method
		   `(lambda (widget)
		      (let* ((--widget-sym-- (make-symbol "--widget--"))
			     (--store-sym-- (make-symbol "--store--")))
			(list
			 (list --widget-sym--)
			 (list widget)
			 (list --store-sym--)
			 (list 'eieio-oset --widget-sym-- '',name --store-sym--)
			 (list 'getfoo --widget-sym--)))))))

Chong Yidong's avatar
Chong Yidong committed
684 685 686
	;; If a writer is defined, then create a generic method of that
	;; name whose purpose is to set the value of the slot.
	(if writer
687 688 689 690
            (eieio--defmethod
             writer nil cname
             `(lambda (this value)
                ,(format "Set the slot `%s' of an object of class `%s'"
Chong Yidong's avatar
Chong Yidong committed
691
			      name cname)
692
                (setf (slot-value this ',name) value))))
Chong Yidong's avatar
Chong Yidong committed
693 694 695
	;; If a reader is defined, then create a generic method
	;; of that name whose purpose is to access this slot value.
	(if reader
696 697 698 699
            (eieio--defmethod
             reader nil cname
             `(lambda (this)
                ,(format "Access the slot `%s' from object of class `%s'"
Chong Yidong's avatar
Chong Yidong committed
700
			      name cname)
701
                (slot-value this ',name))))
Chong Yidong's avatar
Chong Yidong committed
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
	)
      (setq slots (cdr slots)))

    ;; Now that everything has been loaded up, all our lists are backwards!  Fix that up now.
    (aset newc class-public-a (nreverse (aref newc class-public-a)))
    (aset newc class-public-d (nreverse (aref newc class-public-d)))
    (aset newc class-public-doc (nreverse (aref newc class-public-doc)))
    (aset newc class-public-type
	  (apply 'vector (nreverse (aref newc class-public-type))))
    (aset newc class-public-custom (nreverse (aref newc class-public-custom)))
    (aset newc class-public-custom-label (nreverse (aref newc class-public-custom-label)))
    (aset newc class-public-custom-group (nreverse (aref newc class-public-custom-group)))
    (aset newc class-public-printer (nreverse (aref newc class-public-printer)))
    (aset newc class-protection (nreverse (aref newc class-protection)))
    (aset newc class-initarg-tuples (nreverse (aref newc class-initarg-tuples)))

    ;; The storage for class-class-allocation-type needs to be turned into
    ;; a vector now.
    (aset newc class-class-allocation-type
	  (apply 'vector (aref newc class-class-allocation-type)))

    ;; Also, take class allocated values, and vectorize them for speed.
    (aset newc class-class-allocation-values
	  (apply 'vector (aref newc class-class-allocation-values)))

    ;; Attach slot symbols into an obarray, and store the index of
    ;; this slot as the variable slot in this new symbol.  We need to
    ;; know about primes, because obarrays are best set in vectors of
    ;; prime number length, and we also need to make our vector small
    ;; to save space, and also optimal for the number of items we have.
    (let* ((cnt 0)
	   (pubsyms (aref newc class-public-a))
	   (prots (aref newc class-protection))
	   (l (length pubsyms))
	   (vl (let ((primes '( 3 5 7 11 13 17 19 23 29 31 37 41 43 47
				  53 59 61 67 71 73 79 83 89 97 101 )))
		 (while (and primes (< (car primes) l))
		   (setq primes (cdr primes)))
		 (car primes)))
	   (oa (make-vector vl 0))
	   (newsym))
      (while pubsyms
	(setq newsym (intern (symbol-name (car pubsyms)) oa))
	(set newsym cnt)
	(setq cnt (1+ cnt))
	(if (car prots) (put newsym 'protection (car prots)))
	(setq pubsyms (cdr pubsyms)
	      prots (cdr prots)))
      (aset newc class-symbol-obarray oa)
      )

    ;; Create the constructor function
    (if (class-option-assoc options :abstract)
	;; Abstract classes cannot be instantiated.  Say so.
	(let ((abs (class-option-assoc options :abstract)))
	  (if (not (stringp abs))
	      (setq abs (format "Class %s is abstract" cname)))
	  (fset cname
		`(lambda (&rest stuff)
		   ,(format "You cannot create a new object of type %s" cname)
		   (error ,abs))))

      ;; Non-abstract classes need a constructor.
      (fset cname
	    `(lambda (newname &rest slots)
	       ,(format "Create a new object with name NAME of class type %s" cname)
	       (apply 'constructor ,cname newname slots)))
      )

    ;; Set up a specialized doc string.
    ;; Use stored value since it is calculated in a non-trivial way
    (put cname 'variable-documentation
	 (class-option-assoc options :documentation))

    ;; We have a list of custom groups.  Store them into the options.
    (let ((g (class-option-assoc options :custom-groups)))
      (mapc (lambda (cg) (add-to-list 'g cg)) groups)
      (if (memq :custom-groups options)
	  (setcar (cdr (memq :custom-groups options)) g)
	(setq options (cons :custom-groups (cons g options)))))

    ;; Set up the options we have collected.
    (aset newc class-options options)

    ;; if this is a superclass, clear out parent (which was set to the
    ;; default superclass eieio-default-superclass)
    (if clearparent (aset newc class-parent nil))

    ;; Create the cached default object.
    (let ((cache (make-vector (+ (length (aref newc class-public-a))
				 3) nil)))
      (aset cache 0 'object)
      (aset cache object-class cname)
      (aset cache object-name 'default-cache-object)
      (let ((eieio-skip-typecheck t))
	;; All type-checking has been done to our satisfaction
	;; before this call.  Don't waste our time in this call..
	(eieio-set-defaults cache t))
      (aset newc class-default-object-cache cache))

    ;; Return our new class object
    ;; newc
    cname
    ))

(defun eieio-perform-slot-validation-for-default (slot spec value skipnil)
  "For SLOT, signal if SPEC does not match VALUE.
Juanma Barranquero's avatar
Juanma Barranquero committed
809
If SKIPNIL is non-nil, then if VALUE is nil return t instead."
810 811 812 813 814
  (if (and (not (eieio-eval-default-p value))
	   (not eieio-skip-typecheck)
	   (not (and skipnil (null value)))
	   (not (eieio-perform-slot-validation spec value)))
      (signal 'invalid-slot-type (list slot spec value))))
Chong Yidong's avatar
Chong Yidong committed
815 816 817 818 819

(defun eieio-add-new-slot (newc a d doc type cust label custg print prot init alloc
				 &optional defaultoverride skipnil)
  "Add into NEWC attribute A.
If A already exists in NEWC, then do nothing.  If it doesn't exist,
Juanma Barranquero's avatar
Juanma Barranquero committed
820
then also add in D (default), DOC, TYPE, CUST, LABEL, CUSTG, PRINT, PROT, and INIT arg.
Chong Yidong's avatar
Chong Yidong committed
821 822
Argument ALLOC specifies if the slot is allocated per instance, or per class.
If optional DEFAULTOVERRIDE is non-nil, then if A exists in NEWC,
Juanma Barranquero's avatar
Juanma Barranquero committed
823
we must override its value for a default.
Chong Yidong's avatar
Chong Yidong committed
824 825 826 827 828
Optional argument SKIPNIL indicates if type checking should be skipped
if default value is nil."
  ;; Make sure we duplicate those items that are sequences.
  (condition-case nil
      (if (sequencep d) (setq d (copy-sequence d)))
Juanma Barranquero's avatar
Juanma Barranquero committed
829
    ;; This copy can fail on a cons cell with a non-cons in the cdr.  Let's skip it if it doesn't work.
Chong Yidong's avatar
Chong Yidong committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
    (error nil))
  (if (sequencep type) (setq type (copy-sequence type)))
  (if (sequencep cust) (setq cust (copy-sequence cust)))
  (if (sequencep custg) (setq custg (copy-sequence custg)))

  ;; To prevent override information w/out specification of storage,
  ;; we need to do this little hack.
  (if (member a (aref newc class-class-allocation-a)) (setq alloc ':class))

  (if (or (not alloc) (and (symbolp alloc) (eq alloc ':instance)))
      ;; In this case, we modify the INSTANCE version of a given slot.

      (progn

	;; Only add this element if it is so-far unique
	(if (not (member a (aref newc class-public-a)))
	    (progn
	      (eieio-perform-slot-validation-for-default a type d skipnil)
	      (aset newc class-public-a (cons a (aref newc class-public-a)))
	      (aset newc class-public-d (cons d (aref newc class-public-d)))
	      (aset newc class-public-doc (cons doc (aref newc class-public-doc)))
	      (aset newc class-public-type (cons type (aref newc class-public-type)))
	      (aset newc class-public-custom (cons cust (aref newc class-public-custom)))
	      (aset newc class-public-custom-label (cons label (aref newc class-public-custom-label)))
	      (aset newc class-public-custom-group (cons custg (aref newc class-public-custom-group)))
	      (aset newc class-public-printer (cons print (aref newc class-public-printer)))
	      (aset newc class-protection (cons prot (aref newc class-protection)))
	      (aset newc class-initarg-tuples (cons (cons init a) (aref newc class-initarg-tuples)))
	      )
	  ;; When defaultoverride is true, we are usually adding new local
	  ;; attributes which must override the default value of any slot
	  ;; passed in by one of the parent classes.
	  (when defaultoverride
	    ;; There is a match, and we must override the old value.
	    (let* ((ca (aref newc class-public-a))
		   (np (member a ca))
		   (num (- (length ca) (length np)))
		   (dp (if np (nthcdr num (aref newc class-public-d))
			 nil))
		   (tp (if np (nth num (aref newc class-public-type))))
		   )
	      (if (not np)
Juanma Barranquero's avatar
Juanma Barranquero committed
872
		  (error "EIEIO internal error overriding default value for %s"
Chong Yidong's avatar
Chong Yidong committed
873 874 875 876 877 878 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
			 a)
		;; If type is passed in, is it the same?
		(if (not (eq type t))
		    (if (not (equal type tp))
			(error
			 "Child slot type `%s' does not match inherited type `%s' for `%s'"
			 type tp a)))
		;; If we have a repeat, only update the initarg...
		(unless (eq d eieio-unbound)
		  (eieio-perform-slot-validation-for-default a tp d skipnil)
		  (setcar dp d))
		;; If we have a new initarg, check for it.
		(when init
		  (let* ((inits (aref newc class-initarg-tuples))
			 (inita (rassq a inits)))
		    ;; Replace the CAR of the associate INITA.
		    ;;(message "Initarg: %S replace %s" inita init)
		    (setcar inita init)
		    ))

		;; PLN Tue Jun 26 11:57:06 2007 : The protection is
		;; checked and SHOULD match the superclass
		;; protection. Otherwise an error is thrown. However
		;; I wonder if a more flexible schedule might be
		;; implemented.
		;;
		;; EML - We used to have (if prot... here,
		;;       but a prot of 'nil means public.
		;;
		(let ((super-prot (nth num (aref newc class-protection)))
		      )
		  (if (not (eq prot super-prot))
		      (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
			     prot super-prot a)))
		;; End original PLN

		;; PLN Tue Jun 26 11:57:06 2007 :
910 911
		;; Do a non redundant combination of ancient custom
		;; groups and new ones.
Chong Yidong's avatar
Chong Yidong committed
912
		(when custg
913 914 915 916 917 918 919 920 921 922
		  (let* ((groups
			  (nthcdr num (aref newc class-public-custom-group)))
			 (list1 (car groups))
			 (list2 (if (listp custg) custg (list custg))))
		    (if (< (length list1) (length list2))
			(setq list1 (prog1 list2 (setq list2 list1))))
		    (dolist (elt list2)
		      (unless (memq elt list1)
			(push elt list1)))
		    (setcar groups list1)))
Chong Yidong's avatar
Chong Yidong committed
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
		;;  End PLN

		;;  PLN Mon Jun 25 22:44:34 2007 : If a new cust is
		;;  set, simply replaces the old one.
		(when cust
		  ;; (message "Custom type redefined to %s" cust)
		  (setcar (nthcdr num (aref newc class-public-custom)) cust))

		;; If a new label is specified, it simply replaces
		;; the old one.
		(when label
		  ;; (message "Custom label redefined to %s" label)
		  (setcar (nthcdr num (aref newc class-public-custom-label)) label))
		;;  End PLN

		;; PLN Sat Jun 30 17:24:42 2007 : when a new
		;; doc is specified, simply replaces the old one.
		(when doc
		  ;;(message "Documentation redefined to %s" doc)
		  (setcar (nthcdr num (aref newc class-public-doc))
			  doc))
		;; End PLN

		;; If a new printer is specified, it simply replaces
		;; the old one.
		(when print
		  ;; (message "printer redefined to %s" print)
		  (setcar (nthcdr num (aref newc class-public-printer)) print))

		)))
	  ))

    ;; CLASS ALLOCATED SLOTS
    (let ((value (eieio-default-eval-maybe d)))
      (if (not (member a (aref newc class-class-allocation-a)))
	  (progn
	    (eieio-perform-slot-validation-for-default a type value skipnil)
	    ;; Here we have found a :class version of a slot.  This
Paul Eggert's avatar
Paul Eggert committed
961
	    ;; requires a very different approach.
Chong Yidong's avatar
Chong Yidong committed
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	    (aset newc class-class-allocation-a (cons a (aref newc class-class-allocation-a)))
	    (aset newc class-class-allocation-doc (cons doc (aref newc class-class-allocation-doc)))
	    (aset newc class-class-allocation-type (cons type (aref newc class-class-allocation-type)))
	    (aset newc class-class-allocation-custom (cons cust (aref newc class-class-allocation-custom)))
	    (aset newc class-class-allocation-custom-label (cons label (aref newc class-class-allocation-custom-label)))
	    (aset newc class-class-allocation-custom-group (cons custg (aref newc class-class-allocation-custom-group)))
	    (aset newc class-class-allocation-protection (cons prot (aref newc class-class-allocation-protection)))
	    ;; Default value is stored in the 'values section, since new objects
	    ;; can't initialize from this element.
	    (aset newc class-class-allocation-values (cons value (aref newc class-class-allocation-values))))
	(when defaultoverride
	  ;; There is a match, and we must override the old value.
	  (let* ((ca (aref newc class-class-allocation-a))
		 (np (member a ca))
		 (num (- (length ca) (length np)))
		 (dp (if np
			 (nthcdr num
				 (aref newc class-class-allocation-values))
		       nil))
		 (tp (if np (nth num (aref newc class-class-allocation-type))
		       nil)))
	    (if (not np)
Juanma Barranquero's avatar
Juanma Barranquero committed
984
		(error "EIEIO internal error overriding default value for %s"
Chong Yidong's avatar
Chong Yidong committed
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
		       a)
	      ;; If type is passed in, is it the same?
	      (if (not (eq type t))
		  (if (not (equal type tp))
		      (error
		       "Child slot type `%s' does not match inherited type `%s' for `%s'"
		       type tp a)))
	      ;; EML - Note: the only reason to override a class bound slot
	      ;;       is to change the default, so allow unbound in.

	      ;; If we have a repeat, only update the vlaue...
	      (eieio-perform-slot-validation-for-default a tp value skipnil)
	      (setcar dp value))

	    ;; PLN Tue Jun 26 11:57:06 2007 : The protection is
	    ;; checked and SHOULD match the superclass
	    ;; protection. Otherwise an error is thrown. However
	    ;; I wonder if a more flexible schedule might be
	    ;; implemented.
	    (let ((super-prot
		   (car (nthcdr num (aref newc class-class-allocation-protection)))))
	      (if (not (eq prot super-prot))
		  (error "Child slot protection `%s' does not match inherited protection `%s' for `%s'"
			 prot super-prot a)))
1009 1010
	    ;; Do a non redundant combination of ancient custom groups
	    ;; and new ones.
Chong Yidong's avatar
Chong Yidong committed
1011
	    (when custg
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
	      (let* ((groups
		      (nthcdr num (aref newc class-class-allocation-custom-group)))
		     (list1 (car groups))
		     (list2 (if (listp custg) custg (list custg))))
		(if (< (length list1) (length list2))
		    (setq list1 (prog1 list2 (setq list2 list1))))
		(dolist (elt list2)
		  (unless (memq elt list1)
		    (push elt list1)))
		(setcar groups list1)))
Chong Yidong's avatar
Chong Yidong committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

	    ;; PLN Sat Jun 30 17:24:42 2007 : when a new
	    ;; doc is specified, simply replaces the old one.
	    (when doc
	      ;;(message "Documentation redefined to %s" doc)
	      (setcar (nthcdr num (aref newc class-class-allocation-doc))
		      doc))
	    ;; End PLN

	    ;; If a new printer is specified, it simply replaces
	    ;; the old one.
	    (when print
	      ;; (message "printer redefined to %s" print)
	      (setcar (nthcdr num (aref newc class-class-allocation-printer)) print))

	    ))
	))
    ))

(defun eieio-copy-parents-into-subclass (newc parents)
  "Copy into NEWC the slots of PARENTS.
Glenn Morris's avatar
Glenn Morris committed
1043
Follow the rules of not overwriting early parents when applying to
Chong Yidong's avatar
Chong Yidong committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
the new child class."
  (let ((ps (aref newc class-parent))
	(sn (class-option-assoc (aref newc class-options)
				':allow-nil-initform)))
    (while ps
      ;; First, duplicate all the slots of the parent.
      (let ((pcv (class-v (car ps))))
	(let ((pa (aref pcv class-public-a))
	      (pd (aref pcv class-public-d))
	      (pdoc (aref pcv class-public-doc))
	      (ptype (aref pcv class-public-type))
	      (pcust (aref pcv class-public-custom))
	      (plabel (aref pcv class-public-custom-label))
	      (pcustg (aref pcv class-public-custom-group))
	      (printer (aref pcv class-public-printer))
	      (pprot (aref pcv class-protection))
	      (pinit (aref pcv class-initarg-tuples))
	      (i 0))
	  (while pa
	    (eieio-add-new-slot newc
				 (car pa) (car pd) (car pdoc) (aref ptype i)
				 (car pcust) (car plabel) (car pcustg)
				 (car printer)
				 (car pprot) (car-safe (car pinit)) nil nil sn)
	    ;; Increment each value.
	    (setq pa (cdr pa)
		  pd (cdr pd)
		  pdoc (cdr pdoc)
		  i (1+ i)
		  pcust (cdr pcust)
		  plabel (cdr plabel)
		  pcustg (cdr pcustg)
		  printer (cdr printer)
		  pprot (cdr pprot)
		  pinit (cdr pinit))
	    )) ;; while/let
	;; Now duplicate all the class alloc slots.
	(let ((pa (aref pcv class-class-allocation-a))
	      (pdoc (aref pcv class-class-allocation-doc))
	      (ptype (aref pcv class-class-allocation-type))
	      (pcust (aref pcv class-class-allocation-custom))
	      (plabel (aref pcv class-class-allocation-custom-label))
	      (pcustg (aref pcv class-class-allocation-custom-group))
	      (printer (aref pcv class-class-allocation-printer))
	      (pprot (aref pcv class-class-allocation-protection))
	      (pval (aref pcv class-class-allocation-values))
	      (i 0))
	  (while pa
	    (eieio-add-new-slot newc
				 (car pa) (aref pval i) (car pdoc) (aref ptype i)
				 (car pcust) (car plabel) (car pcustg)
				 (car printer)
				 (car pprot) nil ':class sn)
	    ;; Increment each value.
	    (setq pa (cdr pa)
		  pdoc (cdr pdoc)
		  pcust (cdr pcust)
		  plabel (cdr plabel)
		  pcustg (cdr pcustg)
		  printer (cdr printer)
		  pprot (cdr pprot)
		  i (1+ i))
	    ))) ;; while/let
      ;; Loop over each parent class
      (setq ps (cdr ps)))
    ))

;;; 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
1124
Compatibility note:
Chong Yidong's avatar
Chong Yidong committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

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
;;
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

(put 'eieio--defalias 'byte-hunk-handler
     #'byte-compile-file-form-defalias) ;;(get 'defalias 'byte-hunk-handler)
(defun eieio--defalias (name body)
  "Like `defalias', but with less side-effects.
More specifically, it has no side-effects at all when the new function
definition is the same (`eq') as the old one."
  (unless (and (fboundp name)
               (eq (symbol-function name) body))
    (defalias name body)))

Chong Yidong's avatar
Chong Yidong committed
1154
(defmacro defgeneric (method args &optional doc-string)
Juanma Barranquero's avatar
Juanma Barranquero committed
1155
  "Create a generic function METHOD.
Chong Yidong's avatar
Chong Yidong committed
1156
DOC-STRING is the base documentation for this class.  A generic
Juanma Barranquero's avatar
Juanma Barranquero committed
1157 1158 1159
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
1160 1161
currently ignored.  You can use `defgeneric' to apply specialized
top level documentation to a method."
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
  `(eieio--defalias ',method
                    (eieio--defgeneric-init-form ',method ,doc-string)))

(defun eieio--defgeneric-init-form (method doc-string)
  "Form to use for the initial definition of a generic."
  (cond
   ((or (not (fboundp method))
        (eq 'autoload (car-safe (symbol-function method))))
    ;; Make sure the method tables are installed.
    (eieiomt-install method)
    ;; Construct the actual body of this function.
    (eieio-defgeneric-form method doc-string))
   ((generic-p method) (symbol-function method))           ;Leave it as-is.
   (t (error "You cannot create a generic/method over an existing symbol: %s"
             method))))
Chong Yidong's avatar
Chong Yidong committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216

(defun eieio-defgeneric-form (method doc-string)
  "The lambda form that would be used as the function defined on METHOD.
All methods should call the same EIEIO function for dispatch.
DOC-STRING is the documentation attached to METHOD."
  `(lambda (&rest local-args)
     ,doc-string
     (eieio-generic-call (quote ,method) local-args)))

(defsubst eieio-defgeneric-reset-generic-form (method)
  "Setup METHOD to call the generic form."
  (let ((doc-string (documentation method)))
    (fset method (eieio-defgeneric-form method doc-string))))

(defun eieio-defgeneric-form-primary-only (method doc-string)
  "The lambda form that would be used as the function defined on METHOD.
All methods should call the same EIEIO function for dispatch.
DOC-STRING is the documentation attached to METHOD."
  `(lambda (&rest local-args)
     ,doc-string
     (eieio-generic-call-primary-only (quote ,method) local-args)))

(defsubst eieio-defgeneric-reset-generic-form-primary-only (method)
  "Setup METHOD to call the generic form."
  (let ((doc-string (documentation method)))
    (fset method (eieio-defgeneric-form-primary-only method doc-string))))

(defun eieio-defgeneric-form-primary-only-one (method doc-string
						      class
						      impl
						      )
  "The lambda form that would be used as the function defined on METHOD.
All methods should call the same EIEIO function for dispatch.
DOC-STRING is the documentation attached to METHOD.
CLASS is the class symbol needed for private method access.
IMPL is the symbol holding the method implementation."
  ;; NOTE: I tried out byte compiling this little fcn.  Turns out it
  ;; is faster to execute this for not byte-compiled.  ie, install this,
  ;; then measure calls going through here.  I wonder why.
  (require 'bytecomp)
1217 1218
  (let ((byte-compile-warnings nil))
    (byte-compile
Chong Yidong's avatar
Chong Yidong committed
1219 1220 1221 1222 1223 1224 1225 1226 1227
     `(lambda (&rest local-args)
	,doc-string
	;; This is a cool cheat.  Usually we need to look up in the
	;; method table to find out if there is a method or not.  We can
	;; instead make that determination at load time when there is
	;; only one method.  If the first arg is not a child of the class
	;; of that one implementation, then clearly, there is no method def.
	(if (not (eieio-object-p (car local-args)))
	    ;; Not an object.  Just signal.
1228
	    (signal 'no-method-definition
1229
                    (list ',method local-args))
Chong Yidong's avatar
Chong Yidong committed
1230 1231 1232

	  ;; We do have an object.  Make sure it is the right type.
	  (if ,(if (eq class eieio-default-superclass)
1233
		   nil  ; default superclass means just an obj.  Already asked.
Chong Yidong's avatar
Chong Yidong committed
1234
		 `(not (child-of-class-p (aref (car local-args) object-class)
1235
					 ',class)))
Chong Yidong's avatar
Chong Yidong committed
1236 1237 1238

	      ;; If not the right kind of object, call no applicable
	      (apply 'no-applicable-method (car local-args)
1239
		     ',method local-args)
Chong Yidong's avatar
Chong Yidong committed
1240 1241 1242

	    ;; It is ok, do the call.
	    ;; Fill in inter-call variables then evaluate the method.
1243
	    (let ((scoped-class ',class)
Chong Yidong's avatar
Chong Yidong committed
1244 1245
		  (eieio-generic-call-next-method-list nil)
		  (eieio-generic-call-key method-primary)
1246
		  (eieio-generic-call-methodname ',method)
Chong Yidong's avatar
Chong Yidong committed
1247 1248
		  (eieio-generic-call-arglst local-args)
		  )
1249 1250
	      (apply #',impl local-args)
              ;;(,impl local-args)
1251
	      )))))))
Chong Yidong's avatar
Chong Yidong committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

(defsubst eieio-defgeneric-reset-generic-form-primary-only-one (method)
  "Setup METHOD to call the generic form."
  (let* ((doc-string (documentation method))
	 (M (get method 'eieio-method-tree))
	 (entry (car (aref M method-primary)))
	 )
    (fset method (eieio-defgeneric-form-primary-only-one
		  method doc-string
		  (car entry)
		  (cdr entry)
		  ))))

(defun eieio-unbind-method-implementations (method)
Juanma Barranquero's avatar
Juanma Barranquero committed
1266 1267 1268
  "Make the generic method METHOD have no implementations.
It will leave the original generic function in place,
but remove reference to all implementations of METHOD."
Chong Yidong's avatar
Chong Yidong committed
1269 1270 1271 1272 1273 1274
  (put method 'eieio-method-tree nil)
  (put method 'eieio-method-obarray nil))

(defmacro defmethod (method &rest args)
  "Create a new METHOD through `defgeneric' with ARGS.

Juanma Barranquero's avatar
Juanma Barranquero committed
1275
The optional second argument KEY is a specifier that
Chong Yidong's avatar
Chong Yidong committed
1276
modifies how the method is called, including:
Juanma Barranquero's avatar
Juanma Barranquero committed
1277 1278 1279 1280
   :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
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
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)"
1297
  (let* ((key (if (keywordp (car args)) (pop args)))
Stefan Monnier's avatar
Stefan Monnier committed
1298 1299
	 (params (car args))
	 (arg1 (car params))
1300
         (fargs (if (consp arg1)
1301 1302 1303
                   (cons (car arg1) (cdr params))
                 params))
	 (class (if (consp arg1) (nth 1 arg1)))
1304
         (code `(lambda ,fargs ,@(cdr args))))
1305 1306 1307 1308 1309
    `(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)))
1310
       (eieio--defmethod ',method ',key ',class #',code))))
1311 1312

(defun eieio--defmethod (method kind argclass code)
Chong Yidong's avatar
Chong Yidong committed
1313
  "Work part of the `defmethod' macro defining METHOD with ARGS."
1314
  (let ((key
1315
         ;; find optional keys
1316 1317
         (cond ((or (eq ':BEFORE kind)
                    (eq ':before kind))
1318
                method-before)
1319 1320
               ((or (eq ':AFTER kind)
                    (eq ':after kind))
1321
                method-after)
1322 1323
               ((or (eq ':PRIMARY kind)
                    (eq ':primary kind))
1324
                method-primary)
1325 1326
               ((or (eq ':STATIC kind)
                    (eq ':static kind))
1327 1328
                method-static)
               ;; Primary key
1329
               (t method-primary))))
1330 1331 1332 1333 1334
    ;; Make sure there is a generic (when called from defclass).
    (eieio--defalias
     method (eieio--defgeneric-init-form
             method (or (documentation code)
                        (format "Generically created method `%s'." method))))
Chong Yidong's avatar
Chong Yidong committed
1335 1336 1337 1338 1339
    ;; create symbol for property to bind to.  If the first arg is of
    ;; the form (varname vartype) and `vartype' is a class, then
    ;; that class will be the type symbol.  If not, then it will fall
    ;; under the type `primary' which is a non-specific calling of the
    ;; function.
1340
    (if argclass
1341 1342
        (if (not (class-p argclass))
            (error "Unknown class type %s in method parameters"
1343
                   argclass))
Chong Yidong's avatar
Chong Yidong committed
1344 1345 1346
      (if (= key -1)
	  (signal 'wrong-type-argument (list :static 'non-class-arg)))
      ;; generics are higher
1347
      (setq key (eieio-specialized-key-to-generic-key key)))
Chong Yidong's avatar
Chong Yidong committed
1348
    ;; Put this lambda into the symbol so we can find it
Stefan Monnier's avatar
Stefan Monnier committed
1349
    (eieiomt-add method code key argclass)
Chong Yidong's avatar
Chong Yidong committed
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    )

  (when eieio-optimize-primary-methods-flag
    ;; Optimizing step:
    ;;
    ;; If this method, after this setup, only has primary methods, then
    ;; we can setup the generic that way.
    (if (generic-primary-only-p method)
	;; If there is only one primary method, then we can go one more
	;; optimization step.
	(if (generic-primary-only-one-p method)
	    (eieio-defgeneric-reset-generic-form-primary-only-one method)
	  (eieio-defgeneric-reset-generic-form-primary-only method))
      (eieio-defgeneric-reset-generic-form method)))

  method)

;;; Slot type validation
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413

;; This is a hideous hack for replacing `typep' from cl-macs, to avoid
;; requiring the CL library at run-time.  It can be eliminated if/when
;; `typep' is merged into Emacs core.
(defun eieio--typep (val type)
  (if (symbolp type)
      (cond ((get type 'cl-deftype-handler)
	     (eieio--typep val (funcall (get type 'cl-deftype-handler))))
	    ((eq type t) t)
	    ((eq type 'null)   (null val))
	    ((eq type 'atom)   (atom val))
	    ((eq type 'float)  (and (numberp val) (not (integerp val))))
	    ((eq type 'real)   (numberp val))
	    ((eq type 'fixnum) (integerp val))
	    ((memq type '(character string-char)) (characterp val))
	    (t
	     (let* ((name (symbol-name type))
		    (namep (intern (concat name "p"))))
	       (if (fboundp namep)
		   (funcall `(lambda () (,namep val)))
		 (funcall `(lambda ()
			     (,(intern (concat name "-p")) val)))))))
    (cond ((get (car type) 'cl-deftype-handler)
	   (eieio--typep val (apply (get (car type) 'cl-deftype-handler)
				    (cdr type))))
	  ((memq (car type) '(integer float real number))
	   (and (eieio--typep val (car type))
		(or (memq (cadr type) '(* nil))
		    (if (consp (cadr type))
			(> val (car (cadr type)))
		      (>= val (cadr type))))
		(or (memq (caddr type) '(* nil))
		    (if (consp (car (cddr type)))
			(< val (caar (cddr type)))
		      (<= val (car (cddr type)))))))
	  ((memq (car type) '(and or not))
	   (eval (cons (car type)
		       (mapcar (lambda (x)
				 `(eieio--typep (quote ,val) (quote ,x)))
			       (cdr type)))))
	  ((memq (car type) '(member member*))
	   (memql val (cdr type)))
	  ((eq (car type) 'satisfies)
	   (funcall `(lambda () (,(cadr type) val))))
	  (t (error "Bad type spec: %s" type)))))

Chong Yidong's avatar
Chong Yidong committed
1414 1415 1416 1417
(defun eieio-perform-slot-validation (spec value)
  "Return non-nil if SPEC does not match VALUE."
  (or (eq spec t)			; t always passes
      (eq value eieio-unbound)		; unbound always passes
1418
      (eieio--typep value spec)))
Chong Yidong's avatar
Chong Yidong committed
1419 1420

(defun eieio-validate-slot-value (class slot-idx value slot)
Juanma Barranquero's avatar
Juanma Barranquero committed
1421
  "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
Chong Yidong's avatar
Chong Yidong committed
1422 1423
Checks the :type specifier.
SLOT is the slot that is being checked, and is only used when throwing
Juanma Barranquero's avatar
Juanma Barranquero committed
1424
an error."
Chong Yidong's avatar
Chong Yidong committed
1425 1426 1427 1428 1429 1430 1431 1432 1433
  (if eieio-skip-typecheck
      nil
    ;; Trim off object IDX junk added in for the object index.
    (setq slot-idx (- slot-idx 3))
    (let ((st (aref (aref (class-v class) class-public-type) slot-idx)))
      (if (not (eieio-perform-slot-validation st value))
	  (signal 'invalid-slot-type (list class slot st value))))))

(defun eieio-validate-class-slot-value (class slot-idx value slot)
Juanma Barranquero's avatar
Juanma Barranquero committed
1434
  "Make sure that for CLASS referencing SLOT-IDX, VALUE is valid.
Chong Yidong's avatar
Chong Yidong committed
1435 1436
Checks the :type specifier.
SLOT is the slot that is being checked, and is only used when throwing
Juanma Barranquero's avatar
Juanma Barranquero committed
1437
an error."
Chong Yidong's avatar
Chong Yidong committed
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
  (if eieio-skip-typecheck
      nil
    (let ((st (aref (aref (class-v class) class-class-allocation-type)
		    slot-idx)))
      (if (not (eieio-perform-slot-validation st value))
	  (signal 'invalid-slot-type (list class slot st value))))))

(defun eieio-barf-if-slot-unbound (value instance slotname fn)
  "Throw a signal if VALUE is a representation of an UNBOUND slot.
INSTANCE is the object being referenced.  SLOTNAME is the offending
slot.  If the slot is ok, return VALUE.
Argument FN is the function calling this verifier."
  (if (and (eq value eieio-unbound) (not eieio-skip-typecheck))
      (slot-unbound instance (object-class instance) slotname fn)
    value))

;;; 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)))

(defun eieio-oref (obj slot)
  "Return the value in OBJ at SLOT in the object vector."
  (if (not (or (eieio-object-p obj) (class-p obj)))
      (signal 'wrong-type-argument (list '(or eieio-object-p class-p) obj)))
  (if (not (symbolp slot))
      (signal 'wrong-type-argument (list 'symbolp slot)))
  (if (class-p obj) (eieio-class-un-autoload obj))
  (let* ((class (if (class-p obj) obj (aref obj object-class)))
	 (c (eieio-slot-name-index class obj slot)))
    (if (not c)
	;; It might be missing because it is a :class allocated slot.
Juanma Barranquero's avatar
Juanma Barranquero committed
1473
	;; Let's check that info out.
Chong Yidong's avatar
Chong Yidong committed
1474 1475 1476 1477 1478
	(if (setq c (eieio-class-slot-name-index class slot))
	    ;; Oref that slot.
	    (aref (aref (class-v class) class-class-allocation-values) c)
	  ;; The slot-missing method is a cool way of allowing an object author
	  ;; to intercept missing slot definitions.  Since it is also the LAST
Juanma Barranquero's avatar
Juanma Barranquero committed
1479
	  ;; thing called in this fn, its return value would be retrieved.
Chong Yidong's avatar
Chong Yidong committed
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
	  (slot-missing obj slot 'oref)
	  ;;(signal 'invalid-slot-name (list (object-name obj) slot))
	  )
      (if (not (eieio-object-p obj))
	  (signal 'wrong-type-argument (list 'eieio-object-p obj)))
      (eieio-barf-if-slot-unbound (aref obj c) obj slot 'oref))))

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

(defmacro oref-default (obj slot)
Juanma Barranquero's avatar
Juanma Barranquero committed
1491
  "Get the default value of OBJ (maybe a class) for SLOT.
Chong Yidong's avatar
Chong Yidong committed
1492 1493 1494 1495 1496 1497
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)))

(defun eieio-oref-default (obj slot)
Juanma Barranquero's avatar