tramp.texi: Revert last change due to backward compatibility
[emacs.git] / lisp / emacs-lisp / eieio-base.el
blobb99905cf1982722354f86a224ed11c7454df12b7
1 ;;; eieio-base.el --- Base classes for EIEIO. -*- lexical-binding:t -*-
3 ;;; Copyright (C) 2000-2002, 2004-2005, 2007-2016 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
298 (length (cl-struct-slot-info 'eieio--object)))))
299 (type (cl--slot-descriptor-type (aref (eieio--class-slots class)
300 slot-idx)))
301 (classtype (eieio-persistent-slot-type-is-class-p type)))
303 (cond ((eq (car proposed-value) 'quote)
304 (car (cdr proposed-value)))
306 ;; An empty list sometimes shows up as (list), which is dumb, but
307 ;; we need to support it for backward compat.
308 ((and (eq (car proposed-value) 'list)
309 (= (length proposed-value) 1))
310 nil)
312 ;; We have a slot with a single object that can be
313 ;; saved here. Recurse and evaluate that
314 ;; sub-object.
315 ((and classtype (class-p classtype)
316 (child-of-class-p (car proposed-value) classtype))
317 (eieio-persistent-convert-list-to-object
318 proposed-value))
320 ;; List of object constructors.
321 ((and (eq (car proposed-value) 'list)
322 ;; 2nd item is a list.
323 (consp (car (cdr proposed-value)))
324 ;; 1st elt of 2nd item is a class name.
325 (class-p (car (car (cdr proposed-value))))
328 ;; Check the value against the input class type.
329 ;; If something goes wrong, issue a smart warning
330 ;; about how a :type is needed for this to work.
331 (unless (and
332 ;; Do we have a type?
333 (consp classtype) (class-p (car classtype)))
334 (error "In save file, list of object constructors found, but no :type specified for slot %S of type %S"
335 slot classtype))
337 ;; We have a predicate, but it doesn't satisfy the predicate?
338 (dolist (PV (cdr proposed-value))
339 (unless (child-of-class-p (car PV) (car classtype))
340 (error "Corrupt object on disk")))
342 ;; We have a list of objects here. Lets load them
343 ;; in.
344 (let ((objlist nil))
345 (dolist (subobj (cdr proposed-value))
346 (push (eieio-persistent-convert-list-to-object subobj)
347 objlist))
348 ;; return the list of objects ... reversed.
349 (nreverse objlist)))
351 proposed-value))))
353 ((stringp proposed-value)
354 ;; Else, check for strings, remove properties.
355 (substring-no-properties proposed-value))
358 ;; Else, just return whatever the constant was.
359 proposed-value))
362 (defun eieio-persistent-slot-type-is-class-p (type)
363 "Return the class referred to in TYPE.
364 If no class is referenced there, then return nil."
365 (cond ((class-p type)
366 ;; If the type is a class, then return it.
367 type)
368 ((and (eq 'list-of (car-safe type)) (class-p (cadr type)))
369 ;; If it is the type of a list of a class, then return that class and
370 ;; the type.
371 (cons (cadr type) type))
373 ((and (symbolp type) (get type 'cl-deftype-handler))
374 ;; Macro-expand the type according to cl-deftype definitions.
375 (eieio-persistent-slot-type-is-class-p
376 (funcall (get type 'cl-deftype-handler))))
378 ;; FIXME: foo-child should not be a valid type!
379 ((and (symbolp type) (string-match "-child\\'" (symbol-name type))
380 (class-p (intern-soft (substring (symbol-name type) 0
381 (match-beginning 0)))))
382 (unless eieio-backward-compatibility
383 (error "Use of bogus %S type instead of %S"
384 type (intern-soft (substring (symbol-name type) 0
385 (match-beginning 0)))))
386 ;; If it is the predicate ending with -child, then return
387 ;; that class. Unfortunately, in EIEIO, typep of just the
388 ;; class is the same as if we used -child, so no further work needed.
389 (intern-soft (substring (symbol-name type) 0
390 (match-beginning 0))))
391 ;; FIXME: foo-list should not be a valid type!
392 ((and (symbolp type) (string-match "-list\\'" (symbol-name type))
393 (class-p (intern-soft (substring (symbol-name type) 0
394 (match-beginning 0)))))
395 (unless eieio-backward-compatibility
396 (error "Use of bogus %S type instead of (list-of %S)"
397 type (intern-soft (substring (symbol-name type) 0
398 (match-beginning 0)))))
399 ;; If it is the predicate ending with -list, then return
400 ;; that class and the predicate to use.
401 (cons (intern-soft (substring (symbol-name type) 0
402 (match-beginning 0)))
403 type))
405 ((eq (car-safe type) 'or)
406 ;; If type is a list, and is an or, it is possibly something
407 ;; like (or null myclass), so check for that.
408 (let ((ans nil))
409 (dolist (subtype (cdr type))
410 (setq ans (eieio-persistent-slot-type-is-class-p
411 subtype)))
412 ans))
415 ;; No match, not a class.
416 nil)))
418 (cl-defmethod object-write ((this eieio-persistent) &optional comment)
419 "Write persistent object THIS out to the current stream.
420 Optional argument COMMENT is a header line comment."
421 (cl-call-next-method this (or comment (oref this file-header-line))))
423 (cl-defmethod eieio-persistent-path-relative ((this eieio-persistent) file)
424 "For object THIS, make absolute file name FILE relative."
425 (file-relative-name (expand-file-name file)
426 (file-name-directory (oref this file))))
428 (cl-defmethod eieio-persistent-save ((this eieio-persistent) &optional file)
429 "Save persistent object THIS to disk.
430 Optional argument FILE overrides the file name specified in the object
431 instance."
432 (when file (setq file (expand-file-name file)))
433 (with-temp-buffer
434 (let* ((cfn (or file (oref this file)))
435 (default-directory (file-name-directory cfn)))
436 (cl-letf ((standard-output (current-buffer))
437 ((oref this file) ;FIXME: Why change it?
438 (if file
439 ;; FIXME: Makes a name relative to (oref this file),
440 ;; whereas I think it should be relative to cfn.
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 (coding-system-for-write 'utf-8-emacs))
446 ;; Old way - write file. Leaves message behind.
447 ;;(write-file cfn nil)
449 ;; New way - Avoid the vast quantities of error checking
450 ;; just so I can get at the special flags that disable
451 ;; displaying random messages.
452 (write-region (point-min) (point-max) cfn nil 1)
453 ))))
455 ;; Notes on the persistent object:
456 ;; It should also set up some hooks to help it keep itself up to date.
459 ;;; Named object
461 (defclass eieio-named ()
462 ((object-name :initarg :object-name :initform nil))
463 "Object with a name."
464 :abstract t)
466 (cl-defmethod eieio-object-name-string ((obj eieio-named))
467 "Return a string which is OBJ's name."
468 (or (slot-value obj 'object-name)
469 (symbol-name (eieio-object-class obj))))
471 (cl-defmethod eieio-object-set-name-string ((obj eieio-named) name)
472 "Set the string which is OBJ's NAME."
473 (cl-check-type name string)
474 (eieio-oset obj 'object-name name))
476 (cl-defmethod clone ((obj eieio-named) &rest params)
477 "Clone OBJ, initializing `:parent' to OBJ.
478 All slots are unbound, except those initialized with PARAMS."
479 (let* ((newname (and (stringp (car params)) (pop params)))
480 (nobj (apply #'cl-call-next-method obj params))
481 (nm (slot-value obj 'object-name)))
482 (eieio-oset obj 'object-name
483 (or newname
484 (save-match-data
485 (if (and nm (string-match "-\\([0-9]+\\)" nm))
486 (let ((num (1+ (string-to-number
487 (match-string 1 nm)))))
488 (concat (substring nm 0 (match-beginning 0))
489 "-" (int-to-string num)))
490 (concat nm "-1")))))
491 nobj))
493 (cl-defmethod make-instance ((class (subclass eieio-named)) &rest args)
494 (if (not (stringp (car args)))
495 (cl-call-next-method)
496 (funcall (if eieio-backward-compatibility #'ignore #'message)
497 "Obsolete: name passed without :object-name to %S constructor"
498 class)
499 (apply #'cl-call-next-method class :object-name args)))
502 (provide 'eieio-base)
504 ;;; eieio-base.el ends here