c07a4eefc1e1bbf5c161ceca8253fcadff3741b5
[sbcl.git] / src / pcl / defclass.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26 ;;;; DEFCLASS macro and close personal friends
27
28 ;;; state for the current DEFCLASS expansion
29 (defvar *initfunctions-for-this-defclass*)
30 (defvar *readers-for-this-defclass*)
31 (defvar *writers-for-this-defclass*)
32 (defvar *slot-names-for-this-defclass*)
33
34 ;;; Like the DEFMETHOD macro, the expansion of the DEFCLASS macro is
35 ;;; fixed. DEFCLASS always expands into a call to LOAD-DEFCLASS. Until
36 ;;; the meta-braid is set up, LOAD-DEFCLASS has a special definition
37 ;;; which simply collects all class definitions up, when the metabraid
38 ;;; is initialized it is done from those class definitions.
39 ;;;
40 ;;; After the metabraid has been setup, and the protocol for defining
41 ;;; classes has been defined, the real definition of LOAD-DEFCLASS is
42 ;;; installed by the file std-class.lisp
43 (defmacro defclass (&environment env name direct-superclasses direct-slots &rest options)
44   (let (*initfunctions-for-this-defclass*
45         *readers-for-this-defclass* ;Truly a crock, but we got
46         *writers-for-this-defclass* ;to have it to live nicely.
47         *slot-names-for-this-defclass*)
48     ;; FIXME: It would be nice to collect all errors from the
49     ;; expansion of a defclass and signal them in a single go.
50     (multiple-value-bind (metaclass canonical-options)
51         (canonize-defclass-options name options)
52     (let ((canonical-slots (canonize-defclass-slots name direct-slots env))
53           ;; DEFSTRUCT-P should be true if the class is defined
54           ;; with a metaclass STRUCTURE-CLASS, so that a DEFSTRUCT
55           ;; is compiled for the class.
56           (defstruct-p (and (eq *boot-state* 'complete)
57                             (let ((mclass (find-class metaclass nil)))
58                               (and mclass
59                                    (*subtypep
60                                     mclass
61                                     *the-class-structure-class*))))))
62       (let* ((defclass-form
63               `(let ,(mapcar #'cdr *initfunctions-for-this-defclass*)
64                  (load-defclass ',name
65                                 ',metaclass
66                                 ',direct-superclasses
67                                 (list ,@canonical-slots)
68                                 (list ,@(apply #'append
69                                                (when defstruct-p
70                                                  '(:from-defclass-p t))
71                                                 canonical-options))
72                                 ',*readers-for-this-defclass*
73                                 ',*writers-for-this-defclass*
74                                 ',*slot-names-for-this-defclass*))))
75         (if defstruct-p
76             (progn
77               ;; FIXME: (YUK!) Why do we do this? Because in order
78               ;; to make the defstruct form, we need to know what
79               ;; the accessors for the slots are, so we need already
80               ;; to have hooked into the CLOS machinery.
81               ;;
82               ;; There may be a better way to do this: it would
83               ;; involve knowing enough about PCL to ask "what will
84               ;; my slot names and accessors be"; failing this, we
85               ;; currently just evaluate the whole kaboodle, and
86               ;; then use CLASS-DIRECT-SLOTS. -- CSR, 2002-06-07
87               (eval defclass-form)
88               (let* ((include (or (and direct-superclasses
89                                        (fix-super (car direct-superclasses)))
90                                   (and (not (eq name 'structure-object))
91                                        *the-class-structure-object*)))
92                      (defstruct-form (make-structure-class-defstruct-form
93                                       name (class-direct-slots (find-class name))
94                                       include)))
95                 `(progn
96                    (eval-when (:compile-toplevel :load-toplevel :execute)
97                      ,defstruct-form) ; really compile the defstruct-form
98                    (eval-when (:compile-toplevel :load-toplevel :execute)
99                      ,defclass-form))))
100             `(progn
101                ;; By telling the type system at compile time about
102                ;; the existence of a class named NAME, we can avoid
103                ;; various bogus warnings about "type isn't defined yet"
104                ;; for code elsewhere in the same file which uses
105                ;; the name of the type.
106                ;;
107                ;; We only need to do this at compile time, because
108                ;; at load and execute time we write the actual
109                ;; full-blown class, so the "a class of this name is
110                ;; coming" note we write here would be irrelevant.
111                (eval-when (:compile-toplevel)
112                  (%compiler-defclass ',name
113                                      ',*readers-for-this-defclass*
114                                      ',*writers-for-this-defclass*
115                                      ',*slot-names-for-this-defclass*))
116                (eval-when (:load-toplevel :execute)
117                  ,defclass-form))))))))
118
119 (defun canonize-defclass-options (class-name options)
120   (maplist (lambda (sublist)
121              (let ((option-name (first (pop sublist))))
122                (when (member option-name sublist :key #'first)
123                  (error "Multiple ~S options in DEFCLASS ~S."
124                         option-name class-name))))
125            options)
126   (let (metaclass
127         default-initargs
128         documentation
129         canonized-options)
130       (dolist (option options)
131         (unless (listp option)
132           (error "~S is not a legal defclass option." option))
133         (case (first option)
134           (:metaclass
135            (let ((maybe-metaclass (second option)))
136              (unless (and maybe-metaclass (legal-class-name-p maybe-metaclass))
137                (error "~@<The value of the :metaclass option (~S) ~
138                          is not a legal class name.~:@>"
139                       maybe-metaclass))
140              (setf metaclass maybe-metaclass)))
141           (:default-initargs
142            (let (initargs arg-names)
143              (doplist (key val) (cdr option)
144                (when (member key arg-names)
145                  (error 'simple-program-error
146                         :format-control "~@<Duplicate initialization argument ~
147                                            name ~S in :DEFAULT-INITARGS of ~
148                                            DEFCLASS ~S.~:>"
149                         :format-arguments (list key class-name)))
150                (push key arg-names)
151                (push ``(,',key ,',val ,,(make-initfunction val)) initargs))
152              (setf default-initargs t)
153              (push `(:direct-default-initargs (list ,@(nreverse initargs)))
154                    canonized-options)))
155           (:documentation
156            (unless (stringp (second option))
157              (error "~S is not a legal :documentation value" (second option)))
158            (setf documentation t)
159            (push `(:documentation ,(second option)) canonized-options))
160           (otherwise
161            (push `(',(car option) ',(cdr option)) canonized-options))))
162       (values (or metaclass 'standard-class) (nreverse canonized-options))))
163
164 (defun canonize-defclass-slots (class-name slots env)
165   (let (canonized-specs)
166     (dolist (spec slots)
167       (when (atom spec)
168         (setf spec (list spec)))
169       (when (and (cdr spec) (null (cddr spec)))
170         (error 'simple-program-error
171                :format-control "~@<in DEFCLASS ~S, the slot specification ~S ~
172                                 is invalid; the probable intended meaning may ~
173                                 be achieved by specifiying ~S instead.~:>"
174                :format-arguments (list class-name spec
175                                        `(,(car spec) :initform ,(cadr spec)))))
176       (let* ((name (car spec))
177              (plist (cdr spec))
178              (readers ())
179              (writers ())
180              (initargs ())
181              (others ())
182              (unsupplied (list nil))
183              (initform unsupplied))
184         (check-slot-name-for-defclass name class-name env)
185         (push name *slot-names-for-this-defclass*)
186         (flet ((note-reader (x)
187                  (unless (symbolp x)
188                    (error 'simple-program-error
189                           :format-control "Slot reader name ~S for slot ~S in ~
190                                            DEFCLASS ~S is not a symbol."
191                           :format-arguments (list x name class-name)))
192                  (push x readers)
193                  (push x *readers-for-this-defclass*))
194                (note-writer (x)
195                  (push x writers)
196                  (push x *writers-for-this-defclass*)))
197           (doplist (key val) plist
198             (case key
199               (:accessor (note-reader val) (note-writer `(setf ,val)))
200               (:reader   (note-reader val))
201               (:writer   (note-writer val))
202               (:initarg
203                (unless (symbolp val)
204                  (error 'simple-program-error
205                         :format-control "Slot initarg name ~S for slot ~S in ~
206                                          DEFCLASS ~S is not a symbol."
207                         :format-arguments (list val name class-name)))
208                (push val initargs))
209               (otherwise
210                (when (member key '(:initform :allocation :type :documentation))
211                  (when (eq key :initform)
212                    (setf initform val))
213                  (when (get-properties others (list key))
214                    (error 'simple-program-error
215                           :format-control "Duplicate slot option ~S for slot ~
216                                            ~S in DEFCLASS ~S."
217                           :format-arguments (list key name class-name))))
218                ;; For non-standard options multiple entries go in a list
219                (push val (getf others key))))))
220         ;; Unwrap singleton lists (AMOP 5.4.2)
221         (do ((head others (cddr head)))
222             ((null head))
223           (unless (cdr (second head))
224             (setf (second head) (car (second head)))))
225         (let ((canon `(:name ',name :readers ',readers :writers ',writers
226                              :initargs ',initargs ',others)))
227           (push (if (eq initform unsupplied)
228                     `(list* ,@canon)
229                     `(list* :initfunction ,(make-initfunction initform)
230                             ,@canon))
231                 canonized-specs))))
232     (nreverse canonized-specs)))
233
234
235 (defun check-slot-name-for-defclass (name class-name env)
236   (flet ((slot-name-illegal (reason)
237            (error 'simple-program-error
238                   :format-control
239                   (format nil "~~@<In DEFCLASS ~~S, the slot name ~~S ~
240                                is ~A.~~@:>" reason)
241                   :format-arguments (list class-name name))))
242     (cond ((not (symbolp name))
243            (slot-name-illegal "not a symbol"))
244           ((keywordp name)
245            (slot-name-illegal "a keyword"))
246           ((constantp name env)
247            (slot-name-illegal "a constant"))
248           ((member name *slot-names-for-this-defclass*)
249            (error 'simple-program-error
250                   :format-control "Multiple slots named ~S in DEFCLASS ~S."
251                   :format-arguments (list name class-name))))))
252
253 (defun make-initfunction (initform)
254   (cond ((or (eq initform t)
255              (equal initform ''t))
256          '(function constantly-t))
257         ((or (eq initform nil)
258              (equal initform ''nil))
259          '(function constantly-nil))
260         ((or (eql initform 0)
261              (equal initform ''0))
262          '(function constantly-0))
263         (t
264          (let ((entry (assoc initform *initfunctions-for-this-defclass*
265                              :test #'equal)))
266            (unless entry
267              (setq entry (list initform
268                                (gensym)
269                                `(function (lambda () ,initform))))
270              (push entry *initfunctions-for-this-defclass*))
271            (cadr entry)))))
272
273 (defun %compiler-defclass (name readers writers slots)
274   ;; ANSI says (Macro DEFCLASS, section 7.7) that DEFCLASS, if it
275   ;; "appears as a top level form, the compiler must make the class
276   ;; name be recognized as a valid type name in subsequent
277   ;; declarations (as for deftype) and be recognized as a valid class
278   ;; name for defmethod parameter specializers and for use as the
279   ;; :metaclass option of a subsequent defclass."
280   (preinform-compiler-about-class-type name)
281   (preinform-compiler-about-accessors readers writers slots))
282
283 (defun preinform-compiler-about-class-type (name)
284   ;; Unless the type system already has an actual type attached to
285   ;; NAME (in which case (1) writing a placeholder value over that
286   ;; actual type as a compile-time side-effect would probably be a bad
287   ;; idea and (2) anyway we don't need to modify it in order to make
288   ;; NAME be recognized as a valid type name)
289   (unless (info :type :kind name)
290     ;; Tell the compiler to expect a class with the given NAME, by
291     ;; writing a kind of minimal placeholder type information. This
292     ;; placeholder will be overwritten later when the class is defined.
293     (setf (info :type :kind name) :forthcoming-defclass-type))
294   (values))
295
296 (defun preinform-compiler-about-accessors (readers writers slots)
297   (flet ((inform (name type)
298            ;; FIXME: This matches what PROCLAIM FTYPE does, except
299            ;; that :WHERE-FROM is :DEFINED, not :DECLARED, and should
300            ;; probably be factored into a common function -- eg.
301            ;; (%proclaim-ftype name declared-or-defined).
302            (when (eq (info :function :where-from name) :assumed)
303              (proclaim-as-fun-name name)
304              (note-name-defined name :function)
305              (setf (info :function :where-from name) :defined
306                    (info :function :type name) type))))
307     (let ((rtype (specifier-type '(function (t) t)))
308           (wtype (specifier-type '(function (t t) t))))
309       (dolist (reader readers)
310         (inform reader rtype))
311       (dolist (writer writers)
312         (inform writer wtype))
313       (dolist (slot slots)
314         (inform (slot-reader-name slot) rtype)
315         (inform (slot-boundp-name slot) rtype)
316         (inform (slot-writer-name slot) wtype)))))
317 \f
318 ;;; This is the early definition of LOAD-DEFCLASS. It just collects up
319 ;;; all the class definitions in a list. Later, in braid1.lisp, these
320 ;;; are actually defined.
321
322 ;;; Each entry in *EARLY-CLASS-DEFINITIONS* is an EARLY-CLASS-DEFINITION.
323 (defparameter *early-class-definitions* ())
324
325 (defun early-class-definition (class-name)
326   (or (find class-name *early-class-definitions* :key #'ecd-class-name)
327       (error "~S is not a class in *early-class-definitions*." class-name)))
328
329 (defun make-early-class-definition
330        (name source metaclass
331         superclass-names canonical-slots other-initargs)
332   (list 'early-class-definition
333         name source metaclass
334         superclass-names canonical-slots other-initargs))
335
336 (defun ecd-class-name        (ecd) (nth 1 ecd))
337 (defun ecd-source            (ecd) (nth 2 ecd))
338 (defun ecd-metaclass         (ecd) (nth 3 ecd))
339 (defun ecd-superclass-names  (ecd) (nth 4 ecd))
340 (defun ecd-canonical-slots   (ecd) (nth 5 ecd))
341 (defun ecd-other-initargs    (ecd) (nth 6 ecd))
342
343 (defvar *early-class-slots* nil)
344
345 (defun canonical-slot-name (canonical-slot)
346   (getf canonical-slot :name))
347
348 (defun early-class-slots (class-name)
349   (cdr (or (assoc class-name *early-class-slots*)
350            (let ((a (cons class-name
351                           (mapcar #'canonical-slot-name
352                                   (early-collect-inheritance class-name)))))
353              (push a *early-class-slots*)
354              a))))
355
356 (defun early-class-size (class-name)
357   (length (early-class-slots class-name)))
358
359 (defun early-collect-inheritance (class-name)
360   ;;(declare (values slots cpl default-initargs direct-subclasses))
361   (let ((cpl (early-collect-cpl class-name)))
362     (values (early-collect-slots cpl)
363             cpl
364             (early-collect-default-initargs cpl)
365             (let (collect)
366               (dolist (definition *early-class-definitions*)
367                 (when (memq class-name (ecd-superclass-names definition))
368                   (push (ecd-class-name definition) collect)))
369               (nreverse collect)))))
370
371 (defun early-collect-slots (cpl)
372   (let* ((definitions (mapcar #'early-class-definition cpl))
373          (super-slots (mapcar #'ecd-canonical-slots definitions))
374          (slots (apply #'append (reverse super-slots))))
375     (dolist (s1 slots)
376       (let ((name1 (canonical-slot-name s1)))
377         (dolist (s2 (cdr (memq s1 slots)))
378           (when (eq name1 (canonical-slot-name s2))
379             (error "More than one early class defines a slot with the~%~
380                     name ~S. This can't work because the bootstrap~%~
381                     object system doesn't know how to compute effective~%~
382                     slots."
383                    name1)))))
384     slots))
385
386 (defun early-collect-cpl (class-name)
387   (labels ((walk (c)
388              (let* ((definition (early-class-definition c))
389                     (supers (ecd-superclass-names definition)))
390                (cons c
391                      (apply #'append (mapcar #'early-collect-cpl supers))))))
392     (remove-duplicates (walk class-name) :from-end nil :test #'eq)))
393
394 (defun early-collect-default-initargs (cpl)
395   (let ((default-initargs ()))
396     (dolist (class-name cpl)
397       (let* ((definition (early-class-definition class-name))
398              (others (ecd-other-initargs definition)))
399         (loop (when (null others) (return nil))
400               (let ((initarg (pop others)))
401                 (unless (eq initarg :direct-default-initargs)
402                  (error "~@<The defclass option ~S is not supported by ~
403                         the bootstrap object system.~:@>"
404                         initarg)))
405               (setq default-initargs
406                     (nconc default-initargs (reverse (pop others)))))))
407     (reverse default-initargs)))
408
409 (defun !bootstrap-slot-index (class-name slot-name)
410   (or (position slot-name (early-class-slots class-name))
411       (error "~S not found" slot-name)))
412
413 ;;; !BOOTSTRAP-GET-SLOT and !BOOTSTRAP-SET-SLOT are used to access and
414 ;;; change the values of slots during bootstrapping. During
415 ;;; bootstrapping, there are only two kinds of objects whose slots we
416 ;;; need to access, CLASSes and SLOT-DEFINITIONs. The first argument
417 ;;; to these functions tells whether the object is a CLASS or a
418 ;;; SLOT-DEFINITION.
419 ;;;
420 ;;; Note that the way this works it stores the slot in the same place
421 ;;; in memory that the full object system will expect to find it
422 ;;; later. This is critical to the bootstrapping process, the whole
423 ;;; changeover to the full object system is predicated on this.
424 ;;;
425 ;;; One important point is that the layout of standard classes and
426 ;;; standard slots must be computed the same way in this file as it is
427 ;;; by the full object system later.
428 (defmacro !bootstrap-get-slot (type object slot-name)
429   `(clos-slots-ref (get-slots ,object)
430                    (!bootstrap-slot-index ,type ,slot-name)))
431 (defun !bootstrap-set-slot (type object slot-name new-value)
432   (setf (!bootstrap-get-slot type object slot-name) new-value))
433
434 (defun early-class-name (class)
435   (!bootstrap-get-slot 'class class 'name))
436
437 (defun early-class-precedence-list (class)
438   (!bootstrap-get-slot 'pcl-class class 'class-precedence-list))
439
440 (defun early-class-name-of (instance)
441   (early-class-name (class-of instance)))
442
443 (defun early-class-slotds (class)
444   (!bootstrap-get-slot 'slot-class class 'slots))
445
446 (defun early-slot-definition-name (slotd)
447   (!bootstrap-get-slot 'standard-effective-slot-definition slotd 'name))
448
449 (defun early-slot-definition-location (slotd)
450   (!bootstrap-get-slot 'standard-effective-slot-definition slotd 'location))
451
452 (defun early-accessor-method-slot-name (method)
453   (!bootstrap-get-slot 'standard-accessor-method method 'slot-name))
454
455 (unless (fboundp 'class-name-of)
456   (setf (symbol-function 'class-name-of)
457         (symbol-function 'early-class-name-of)))
458 (unintern 'early-class-name-of)
459
460 (defun early-class-direct-subclasses (class)
461   (!bootstrap-get-slot 'class class 'direct-subclasses))
462
463 (declaim (notinline load-defclass))
464 (defun load-defclass (name metaclass supers canonical-slots canonical-options
465                       readers writers slot-names)
466   (%compiler-defclass name readers writers slot-names)
467   (setq supers  (copy-tree supers)
468         canonical-slots   (copy-tree canonical-slots)
469         canonical-options (copy-tree canonical-options))
470   (let ((ecd
471           (make-early-class-definition name
472                                        *load-pathname*
473                                        metaclass
474                                        supers
475                                        canonical-slots
476                                        canonical-options))
477         (existing
478           (find name *early-class-definitions* :key #'ecd-class-name)))
479     (setq *early-class-definitions*
480           (cons ecd (remove existing *early-class-definitions*)))
481     ecd))