* eieio-base.el (make-instance) <eieio-named>: New instance.
[emacs.git] / lisp / emacs-lisp / eieio-base.el
blobc2eab202881e1035bd0624c994dd911882bddf1d
1 ;;; eieio-base.el --- Base classes for EIEIO. -*- lexical-binding:t -*-
3 ;;; Copyright (C) 2000-2002, 2004-2005, 2007-2015 Free Software
4 ;;; Foundation, Inc.
6 ;; Author: Eric M. Ludlam <zappo@gnu.org>
7 ;; Keywords: OO, lisp
8 ;; Package: eieio
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Base classes for EIEIO. These classes perform some basic tasks
28 ;; but are generally useless on their own. To use any of these classes,
29 ;; inherit from one or more of them.
31 ;;; Code:
33 (require 'eieio)
34 (eval-when-compile (require 'cl-lib))
36 ;;; eieio-instance-inheritor
38 ;; Enable instance inheritance via the `clone' method.
39 ;; Works by using the `slot-unbound' method which usually throws an
40 ;; error if a slot is unbound.
41 (defclass eieio-instance-inheritor ()
42 ((parent-instance :initarg :parent-instance
43 :type eieio-instance-inheritor
44 :documentation
45 "The parent of this instance.
46 If a slot of this class is referenced, and is unbound, then the parent
47 is checked for a value.")
49 "This special class can enable instance inheritance.
50 Use `clone' to make a new object that does instance inheritance from
51 a parent instance. When a slot in the child is referenced, and has
52 not been set, use values from the parent."
53 :abstract t)
55 (cl-defmethod slot-unbound ((object eieio-instance-inheritor)
56 _class slot-name _fn)
57 "If a slot OBJECT in this CLASS is unbound, try to inherit, or throw a signal.
58 SLOT-NAME is the offending slot. FN is the function signaling the error."
59 (if (slot-boundp object 'parent-instance)
60 ;; It may not look like it, but this line recurses back into this
61 ;; method if the parent instance's slot is unbound.
62 (eieio-oref (oref object parent-instance) slot-name)
63 ;; Throw the regular signal.
64 (cl-call-next-method)))
66 (cl-defmethod clone ((obj eieio-instance-inheritor) &rest _params)
67 "Clone OBJ, initializing `:parent' to OBJ.
68 All slots are unbound, except those initialized with PARAMS."
69 (let ((nobj (cl-call-next-method)))
70 (oset nobj parent-instance obj)
71 nobj))
73 (cl-defmethod eieio-instance-inheritor-slot-boundp ((object eieio-instance-inheritor)
74 slot)
75 "Return non-nil if the instance inheritor OBJECT's SLOT is bound.
76 See `slot-boundp' for details on binding slots.
77 The instance inheritor uses unbound slots as a way of cascading cloned
78 slot values, so testing for a slot being bound requires extra steps
79 for this kind of object."
80 (if (slot-boundp object slot)
81 ;; If it is regularly bound, return t.
83 (if (slot-boundp object 'parent-instance)
84 (eieio-instance-inheritor-slot-boundp (oref object parent-instance)
85 slot)
86 nil)))
89 ;;; eieio-instance-tracker
91 ;; Track all created instances of this class.
92 ;; The class must initialize the `tracking-symbol' slot, and that
93 ;; symbol is then used to contain these objects.
94 (defclass eieio-instance-tracker ()
95 ((tracking-symbol :type symbol
96 :allocation :class
97 :documentation
98 "The symbol used to maintain a list of our instances.
99 The instance list is treated as a variable, with new instances added to it.")
101 "This special class enables instance tracking.
102 Inheritors from this class must overload `tracking-symbol' which is
103 a variable symbol used to store a list of all instances."
104 :abstract t)
106 (cl-defmethod initialize-instance :after ((this eieio-instance-tracker)
107 &rest _slots)
108 "Make sure THIS is in our master list of this class.
109 Optional argument SLOTS are the initialization arguments."
110 ;; Theoretically, this is never called twice for a given instance.
111 (let ((sym (oref this tracking-symbol)))
112 (if (not (memq this (symbol-value sym)))
113 (set sym (append (symbol-value sym) (list this))))))
115 (cl-defmethod delete-instance ((this eieio-instance-tracker))
116 "Remove THIS from the master list of this class."
117 (set (oref this tracking-symbol)
118 (delq this (symbol-value (oref this tracking-symbol)))))
120 ;; In retrospect, this is a silly function.
121 (defun eieio-instance-tracker-find (key slot list-symbol)
122 "Find KEY as an element of SLOT in the objects in LIST-SYMBOL.
123 Returns the first match."
124 (object-assoc key slot (symbol-value list-symbol)))
126 ;;; eieio-singleton
128 ;; The singleton Design Pattern specifies that there is but one object
129 ;; of a given class ever created. The EIEIO singleton base class defines
130 ;; a CLASS allocated slot which contains the instance used. All calls to
131 ;; `make-instance' will either create a new instance and store it in this
132 ;; slot, or it will just return what is there.
133 (defclass eieio-singleton ()
134 ((singleton :type eieio-singleton
135 :allocation :class
136 :documentation
137 "The only instance of this class that will be instantiated.
138 Multiple calls to `make-instance' will return this object."))
139 "This special class causes subclasses to be singletons.
140 A singleton is a class which will only ever have one instance."
141 :abstract t)
143 (cl-defmethod make-instance ((class (subclass eieio-singleton)) &rest _slots)
144 "Constructor for singleton CLASS.
145 NAME and SLOTS initialize the new object.
146 This constructor guarantees that no matter how many you request,
147 only one object ever exists."
148 ;; NOTE TO SELF: In next version, make `slot-boundp' support classes
149 ;; with class allocated slots or default values.
150 (let ((old (oref-default class singleton)))
151 (if (eq old eieio-unbound)
152 (oset-default class singleton (cl-call-next-method))
153 old)))
156 ;;; eieio-persistent
158 ;; For objects which must save themselves to disk. Provides an
159 ;; `object-write' method to save an object to disk, and a
160 ;; `eieio-persistent-read' function to call to read an object
161 ;; from disk.
163 ;; Also provide the method `eieio-persistent-path-relative' to
164 ;; calculate path names relative to a given instance. This will
165 ;; make the saved object location independent by converting all file
166 ;; references to be relative to the directory the object is saved to.
167 ;; You must call `eieio-persistent-path-relative' on each file name
168 ;; saved in your object.
169 (defclass eieio-persistent ()
170 ((file :initarg :file
171 :type string
172 :documentation
173 "The save file for this persistent object.
174 This must be a string, and must be specified when the new object is
175 instantiated.")
176 (extension :type string
177 :allocation :class
178 :initform ".eieio"
179 :documentation
180 "Extension of files saved by this object.
181 Enables auto-choosing nice file names based on name.")
182 (file-header-line :type string
183 :allocation :class
184 :initform ";; EIEIO PERSISTENT OBJECT"
185 :documentation
186 "Header line for the save file.
187 This is used with the `object-write' method.")
188 (do-backups :type boolean
189 :allocation :class
190 :initform t
191 :documentation
192 "Saving this object should make backup files.
193 Setting to nil will mean no backups are made."))
194 "This special class enables persistence through save files
195 Use the `object-save' method to write this object to disk. The save
196 format is Emacs Lisp code which calls the constructor for the saved
197 object. For this reason, only slots which do not have an `:initarg'
198 specified will not be saved."
199 :abstract t)
201 (cl-defmethod eieio-persistent-save-interactive ((this eieio-persistent) prompt
202 &optional name)
203 "Prepare to save THIS. Use in an `interactive' statement.
204 Query user for file name with PROMPT if THIS does not yet specify
205 a file. Optional argument NAME specifies a default file name."
206 (unless (slot-boundp this 'file)
207 (oset this file
208 (read-file-name prompt nil
209 (if name
210 (concat name (oref this extension))
211 ))))
212 (oref this file))
214 (defun eieio-persistent-read (filename &optional class allow-subclass)
215 "Read a persistent object from FILENAME, and return it.
216 Signal an error if the object in FILENAME is not a constructor
217 for CLASS. Optional ALLOW-SUBCLASS says that it is ok for
218 `eieio-persistent-read' to load in subclasses of class instead of
219 being pedantic."
220 (unless class
221 (message "Unsafe call to `eieio-persistent-read'."))
222 (when class (cl-check-type class class))
223 (let ((ret nil)
224 (buffstr nil))
225 (unwind-protect
226 (progn
227 (with-current-buffer (get-buffer-create " *tmp eieio read*")
228 (insert-file-contents filename nil nil nil t)
229 (goto-char (point-min))
230 (setq buffstr (buffer-string)))
231 ;; Do the read in the buffer the read was initialized from
232 ;; so that any initialize-instance calls that depend on
233 ;; the current buffer will work.
234 (setq ret (read buffstr))
235 (when (not (child-of-class-p (car ret) 'eieio-persistent))
236 (error "Corrupt object on disk: Unknown saved object"))
237 (when (and class
238 (not (or (eq (car ret) class ) ; same class
239 (and allow-subclass
240 (child-of-class-p (car ret) class)) ; subclasses
242 (error "Corrupt object on disk: Invalid saved class"))
243 (setq ret (eieio-persistent-convert-list-to-object ret))
244 (oset ret file filename))
245 (kill-buffer " *tmp eieio read*"))
246 ret))
248 (defun eieio-persistent-convert-list-to-object (inputlist)
249 "Convert the INPUTLIST, representing object creation to an object.
250 While it is possible to just `eval' the INPUTLIST, this code instead
251 validates the existing list, and explicitly creates objects instead of
252 calling eval. This avoids the possibility of accidentally running
253 malicious code.
255 Note: This function recurses when a slot of :type of some object is
256 identified, and needing more object creation."
257 (let* ((objclass (nth 0 inputlist))
258 ;; (objname (nth 1 inputlist))
259 (slots (nthcdr 2 inputlist))
260 (createslots nil)
261 (class
262 (progn
263 ;; If OBJCLASS is an eieio autoload object, then we need to
264 ;; load it.
265 (eieio-class-un-autoload objclass)
266 (eieio--class-object objclass))))
268 (while slots
269 (let ((initarg (car slots))
270 (value (car (cdr slots))))
272 ;; Make sure that the value proposed for SLOT is valid.
273 ;; In addition, strip out quotes, list functions, and update
274 ;; object constructors as needed.
275 (setq value (eieio-persistent-validate/fix-slot-value
276 class (eieio--initarg-to-attribute class initarg) value))
278 (push initarg createslots)
279 (push value createslots)
282 (setq slots (cdr (cdr slots))))
284 (apply #'make-instance objclass (nreverse createslots))
286 ;;(eval inputlist)
289 (defun eieio-persistent-validate/fix-slot-value (class slot proposed-value)
290 "Validate that in CLASS, the SLOT with PROPOSED-VALUE is good, then fix.
291 A limited number of functions, such as quote, list, and valid object
292 constructor functions are considered valid.
293 Second, any text properties will be stripped from strings."
294 (cond ((consp proposed-value)
295 ;; Lists with something in them need special treatment.
296 (let* ((slot-idx (- (eieio--slot-name-index class slot)
297 (eval-when-compile eieio--object-num-slots)))
298 (type (cl--slot-descriptor-type (aref (eieio--class-slots class)
299 slot-idx)))
300 (classtype (eieio-persistent-slot-type-is-class-p type)))
302 (cond ((eq (car proposed-value) 'quote)
303 (car (cdr proposed-value)))
305 ;; An empty list sometimes shows up as (list), which is dumb, but
306 ;; we need to support it for backward compat.
307 ((and (eq (car proposed-value) 'list)
308 (= (length proposed-value) 1))
309 nil)
311 ;; We have a slot with a single object that can be
312 ;; saved here. Recurse and evaluate that
313 ;; sub-object.
314 ((and classtype (class-p classtype)
315 (child-of-class-p (car proposed-value) classtype))
316 (eieio-persistent-convert-list-to-object
317 proposed-value))
319 ;; List of object constructors.
320 ((and (eq (car proposed-value) 'list)
321 ;; 2nd item is a list.
322 (consp (car (cdr proposed-value)))
323 ;; 1st elt of 2nd item is a class name.
324 (class-p (car (car (cdr proposed-value))))
327 ;; Check the value against the input class type.
328 ;; If something goes wrong, issue a smart warning
329 ;; about how a :type is needed for this to work.
330 (unless (and
331 ;; Do we have a type?
332 (consp classtype) (class-p (car classtype)))
333 (error "In save file, list of object constructors found, but no :type specified for slot %S of type %S"
334 slot classtype))
336 ;; We have a predicate, but it doesn't satisfy the predicate?
337 (dolist (PV (cdr proposed-value))
338 (unless (child-of-class-p (car PV) (car classtype))
339 (error "Corrupt object on disk")))
341 ;; We have a list of objects here. Lets load them
342 ;; in.
343 (let ((objlist nil))
344 (dolist (subobj (cdr proposed-value))
345 (push (eieio-persistent-convert-list-to-object subobj)
346 objlist))
347 ;; return the list of objects ... reversed.
348 (nreverse objlist)))
350 proposed-value))))
352 ((stringp proposed-value)
353 ;; Else, check for strings, remove properties.
354 (substring-no-properties proposed-value))
357 ;; Else, just return whatever the constant was.
358 proposed-value))
361 (defun eieio-persistent-slot-type-is-class-p (type)
362 "Return the class referred to in TYPE.
363 If no class is referenced there, then return nil."
364 (cond ((class-p type)
365 ;; If the type is a class, then return it.
366 type)
367 ((and (eq 'list-of (car-safe type)) (class-p (cadr type)))
368 ;; If it is the type of a list of a class, then return that class and
369 ;; the type.
370 (cons (cadr type) type))
372 ((and (symbolp type) (get type 'cl-deftype-handler))
373 ;; Macro-expand the type according to cl-deftype definitions.
374 (eieio-persistent-slot-type-is-class-p
375 (funcall (get type 'cl-deftype-handler))))
377 ;; FIXME: foo-child should not be a valid type!
378 ((and (symbolp type) (string-match "-child\\'" (symbol-name type))
379 (class-p (intern-soft (substring (symbol-name type) 0
380 (match-beginning 0)))))
381 (unless eieio-backward-compatibility
382 (error "Use of bogus %S type instead of %S"
383 type (intern-soft (substring (symbol-name type) 0
384 (match-beginning 0)))))
385 ;; If it is the predicate ending with -child, then return
386 ;; that class. Unfortunately, in EIEIO, typep of just the
387 ;; class is the same as if we used -child, so no further work needed.
388 (intern-soft (substring (symbol-name type) 0
389 (match-beginning 0))))
390 ;; FIXME: foo-list should not be a valid type!
391 ((and (symbolp type) (string-match "-list\\'" (symbol-name type))
392 (class-p (intern-soft (substring (symbol-name type) 0
393 (match-beginning 0)))))
394 (unless eieio-backward-compatibility
395 (error "Use of bogus %S type instead of (list-of %S)"
396 type (intern-soft (substring (symbol-name type) 0
397 (match-beginning 0)))))
398 ;; If it is the predicate ending with -list, then return
399 ;; that class and the predicate to use.
400 (cons (intern-soft (substring (symbol-name type) 0
401 (match-beginning 0)))
402 type))
404 ((eq (car-safe type) 'or)
405 ;; If type is a list, and is an or, it is possibly something
406 ;; like (or null myclass), so check for that.
407 (let ((ans nil))
408 (dolist (subtype (cdr type))
409 (setq ans (eieio-persistent-slot-type-is-class-p
410 subtype)))
411 ans))
414 ;; No match, not a class.
415 nil)))
417 (cl-defmethod object-write ((this eieio-persistent) &optional comment)
418 "Write persistent object THIS out to the current stream.
419 Optional argument COMMENT is a header line comment."
420 (cl-call-next-method this (or comment (oref this file-header-line))))
422 (cl-defmethod eieio-persistent-path-relative ((this eieio-persistent) file)
423 "For object THIS, make absolute file name FILE relative."
424 (file-relative-name (expand-file-name file)
425 (file-name-directory (oref this file))))
427 (cl-defmethod eieio-persistent-save ((this eieio-persistent) &optional file)
428 "Save persistent object THIS to disk.
429 Optional argument FILE overrides the file name specified in the object
430 instance."
431 (save-excursion
432 (let ((b (set-buffer (get-buffer-create " *tmp object write*")))
433 (default-directory (file-name-directory (oref this file)))
434 (cfn (oref this file)))
435 (unwind-protect
436 (save-excursion
437 (erase-buffer)
438 (let ((standard-output (current-buffer)))
439 (oset this file
440 (if file
441 (eieio-persistent-path-relative this file)
442 (file-name-nondirectory cfn)))
443 (object-write this (oref this file-header-line)))
444 (let ((backup-inhibited (not (oref this do-backups)))
445 (cs (car (find-coding-systems-region
446 (point-min) (point-max)))))
447 (unless (eq cs 'undecided)
448 (setq buffer-file-coding-system cs))
449 ;; Old way - write file. Leaves message behind.
450 ;;(write-file cfn nil)
452 ;; New way - Avoid the vast quantities of error checking
453 ;; just so I can get at the special flags that disable
454 ;; displaying random messages.
455 (write-region (point-min) (point-max)
456 cfn nil 1)
458 ;; Restore :file, and kill the tmp buffer
459 (oset this file cfn)
460 (setq buffer-file-name nil)
461 (kill-buffer b)))))
463 ;; Notes on the persistent object:
464 ;; It should also set up some hooks to help it keep itself up to date.
467 ;;; Named object
469 (defclass eieio-named ()
470 ((object-name :initarg :object-name :initform nil))
471 "Object with a name."
472 :abstract t)
474 (cl-defmethod eieio-object-name-string ((obj eieio-named))
475 "Return a string which is OBJ's name."
476 (or (slot-value obj 'object-name)
477 (symbol-name (eieio-object-class obj))))
479 (cl-defmethod eieio-object-set-name-string ((obj eieio-named) name)
480 "Set the string which is OBJ's NAME."
481 (cl-check-type name string)
482 (eieio-oset obj 'object-name name))
484 (cl-defmethod clone ((obj eieio-named) &rest params)
485 "Clone OBJ, initializing `:parent' to OBJ.
486 All slots are unbound, except those initialized with PARAMS."
487 (let* ((newname (and (stringp (car params)) (pop params)))
488 (nobj (apply #'cl-call-next-method obj params))
489 (nm (slot-value obj 'object-name)))
490 (eieio-oset obj 'object-name
491 (or newname
492 (save-match-data
493 (if (and nm (string-match "-\\([0-9]+\\)" nm))
494 (let ((num (1+ (string-to-number
495 (match-string 1 nm)))))
496 (concat (substring nm 0 (match-beginning 0))
497 "-" (int-to-string num)))
498 (concat nm "-1")))))
499 nobj))
501 (cl-defmethod make-instance ((class (subclass eieio-named)) &rest args)
502 (if (not (stringp (car args)))
503 (cl-call-next-method)
504 (funcall (if eieio-backward-compatibility #'ignore #'message)
505 "Obsolete: name passed without :object-name to %S constructor"
506 class)
507 (apply #'cl-call-next-method class :object-name args)))
510 (provide 'eieio-base)
512 ;;; eieio-base.el ends here