0.8.20.6:
[sbcl.git] / src / pcl / ctor.lisp
1 ;;;; This file contains the optimization machinery for make-instance.
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5
6 ;;;; This software is derived from software originally released by
7 ;;;; Gerd Moellmann.  Copyright and release statements follow.  Later
8 ;;;; modifications to the software are in the public domain and are
9 ;;;; provided with absolutely no warranty.  See the COPYING and
10 ;;;; CREDITS files for more information.
11
12 ;;; Copyright (C) 2002 Gerd Moellmann <gerd.moellmann@t-online.de>
13 ;;; All rights reserved.
14 ;;;
15 ;;; Redistribution and use in source and binary forms, with or without
16 ;;; modification, are permitted provided that the following conditions
17 ;;; are met:
18 ;;;
19 ;;; 1. Redistributions of source code must retain the above copyright
20 ;;;    notice, this list of conditions and the following disclaimer.
21 ;;; 2. Redistributions in binary form must reproduce the above copyright
22 ;;;    notice, this list of conditions and the following disclaimer in the
23 ;;;    documentation and/or other materials provided with the distribution.
24 ;;; 3. The name of the author may not be used to endorse or promote
25 ;;;    products derived from this software without specific prior written
26 ;;;    permission.
27 ;;;
28 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
29 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
30 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 ;;; ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
32 ;;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34 ;;; OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 ;;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38 ;;; USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
39 ;;; DAMAGE.
40
41 ;;; ***************
42 ;;; Overview  *****
43 ;;; ***************
44 ;;;
45 ;;; Compiler macro for MAKE-INSTANCE, and load-time generation of
46 ;;; optimized instance constructor functions.
47 ;;;
48 ;;; ********************
49 ;;; Entry Points  ******
50 ;;; ********************
51 ;;;
52 ;;; UPDATE-CTORS must be called when methods are added/removed,
53 ;;; classes are changed, etc., which affect instance creation.
54 ;;;
55 ;;; PRECOMPILE-CTORS can be called to precompile constructor functions
56 ;;; for classes whose definitions are known at the time the function
57 ;;; is called.
58
59 (in-package "SB-PCL")
60
61 ;;; ******************
62 ;;; Utilities  *******
63 ;;; ******************
64
65 (defun quote-plist-keys (plist)
66   (loop for (key . more) on plist by #'cddr
67         if (null more) do
68           (error "Not a property list: ~S" plist)
69         else
70           collect `(quote ,key)
71           and collect (car more)))
72
73 (defun plist-keys (plist &key test)
74   (loop for (key . more) on plist by #'cddr
75         if (null more) do
76           (error "Not a property list: ~S" plist)
77         else if (or (null test) (funcall test key))
78           collect key))
79
80 (defun plist-values (plist &key test)
81   (loop for (key . more) on plist by #'cddr
82         if (null more) do
83           (error "Not a property list: ~S" plist)
84         else if (or (null test) (funcall test (car more)))
85           collect (car more)))
86
87 (defun constant-symbol-p (form)
88   (and (constantp form)
89        (let ((constant (eval form)))
90          (and (symbolp constant)
91               (not (null (symbol-package constant)))))))
92
93 ;;; somewhat akin to DEFAULT-INITARGS (SLOT-CLASS T T), but just
94 ;;; collecting the defaulted initargs for the call.
95 (defun ctor-default-initkeys (supplied-initargs class-default-initargs)
96   (loop for (key nil) in class-default-initargs
97         when (eq (getf supplied-initargs key '.not-there.) '.not-there.)
98         collect key))
99 \f
100 ;;; *****************
101 ;;; CTORS   *********
102 ;;; *****************
103 ;;;
104 ;;; Ctors are funcallable instances whose initial function is a
105 ;;; function computing an optimized constructor function when called.
106 ;;; When the optimized function is computed, the function of the
107 ;;; funcallable instance is set to it.
108 ;;;
109 (!defstruct-with-alternate-metaclass ctor
110   :slot-names (function-name class-name class initargs)
111   :boa-constructor %make-ctor
112   :superclass-name pcl-funcallable-instance
113   :metaclass-name random-pcl-classoid
114   :metaclass-constructor make-random-pcl-classoid
115   :dd-type funcallable-structure
116   :runtime-type-checks-p nil)
117
118 ;;; List of all defined ctors.
119
120 (defvar *all-ctors* ())
121
122 (defun make-ctor-parameter-list (ctor)
123   (plist-values (ctor-initargs ctor) :test (complement #'constantp)))
124
125 ;;; Reset CTOR to use a default function that will compute an
126 ;;; optimized constructor function when called.
127 (defun install-initial-constructor (ctor &key force-p)
128   (when (or force-p (ctor-class ctor))
129     (setf (ctor-class ctor) nil)
130     (setf (funcallable-instance-fun ctor)
131           #'(instance-lambda (&rest args)
132               (install-optimized-constructor ctor)
133               (apply ctor args)))
134     (setf (%funcallable-instance-info ctor 1)
135           (ctor-function-name ctor))))
136
137 ;;; Keep this a separate function for testing.
138 (defun make-ctor-function-name (class-name initargs)
139   (let ((*package* *pcl-package*)
140         (*print-case* :upcase)
141         (*print-pretty* nil)
142         (*print-gensym* t))
143     (format-symbol *pcl-package* "CTOR ~S::~S ~S ~S"
144                    (package-name (symbol-package class-name))
145                    (symbol-name class-name)
146                    (plist-keys initargs)
147                    (plist-values initargs :test #'constantp))))
148
149 ;;; Keep this a separate function for testing.
150 (defun ensure-ctor (function-name class-name initargs)
151   (unless (fboundp function-name)
152     (make-ctor function-name class-name initargs)))
153
154 ;;; Keep this a separate function for testing.
155 (defun make-ctor (function-name class-name initargs)
156   (without-package-locks ; for (setf symbol-function)
157    (let ((ctor (%make-ctor function-name class-name nil initargs)))
158      (push ctor *all-ctors*)
159      (setf (symbol-function function-name) ctor)
160      (install-initial-constructor ctor :force-p t)
161      ctor)))
162
163 \f
164 ;;; ***********************************************
165 ;;; Compile-Time Expansion of MAKE-INSTANCE *******
166 ;;; ***********************************************
167
168 (define-compiler-macro make-instance (&whole form &rest args)
169   (declare (ignore args))
170   (or (make-instance->constructor-call form)
171       form))
172
173 (defun make-instance->constructor-call (form)
174   (destructuring-bind (fn class-name &rest args) form
175     (declare (ignore fn))
176     (flet (;;
177            ;; Return the name of parameter number I of a constructor
178            ;; function.
179            (parameter-name (i)
180              (let ((ps #(.p0. .p1. .p2. .p3. .p4. .p5.)))
181                (if (array-in-bounds-p ps i)
182                    (aref ps i)
183                    (format-symbol *pcl-package* ".P~D." i))))
184            ;; Check if CLASS-NAME is a constant symbol.  Give up if
185            ;; not.
186            (check-class ()
187              (unless (and class-name (constant-symbol-p class-name))
188                (return-from make-instance->constructor-call nil)))
189            ;; Check if ARGS are suitable for an optimized constructor.
190            ;; Return NIL from the outer function if not.
191            (check-args ()
192              (loop for (key . more) on args by #'cddr do
193                      (when (or (null more)
194                                (not (constant-symbol-p key))
195                                (eq :allow-other-keys (eval key)))
196                        (return-from make-instance->constructor-call nil)))))
197       (check-class)
198       (check-args)
199       ;; Collect a plist of initargs and constant values/parameter names
200       ;; in INITARGS.  Collect non-constant initialization forms in
201       ;; VALUE-FORMS.
202       (multiple-value-bind (initargs value-forms)
203           (loop for (key value) on args by #'cddr and i from 0
204                 collect (eval key) into initargs
205                 if (constantp value)
206                   collect value into initargs
207                 else
208                   collect (parameter-name i) into initargs
209                   and collect value into value-forms
210                 finally
211                   (return (values initargs value-forms)))
212         (let* ((class-name (eval class-name))
213                (function-name (make-ctor-function-name class-name initargs)))
214           ;; Prevent compiler warnings for calling the ctor.
215           (proclaim-as-fun-name function-name)
216           (note-name-defined function-name :function)
217           (when (eq (info :function :where-from function-name) :assumed)
218             (setf (info :function :where-from function-name) :defined)
219             (when (info :function :assumed-type function-name)
220               (setf (info :function :assumed-type function-name) nil)))
221           ;; Return code constructing a ctor at load time, which, when
222           ;; called, will set its funcallable instance function to an
223           ;; optimized constructor function.
224           `(locally 
225                (declare (disable-package-locks ,function-name))
226             (let ((.x. (load-time-value
227                         (ensure-ctor ',function-name ',class-name ',initargs))))
228               (declare (ignore .x.))
229               ;; ??? check if this is worth it.
230               (declare
231                (ftype (or (function ,(make-list (length value-forms)
232                                                 :initial-element t)
233                                     t)
234                           (function (&rest t) t))
235                       ,function-name))
236               (,function-name ,@value-forms))))))))
237
238 \f
239 ;;; **************************************************
240 ;;; Load-Time Constructor Function Generation  *******
241 ;;; **************************************************
242
243 ;;; The system-supplied primary INITIALIZE-INSTANCE and
244 ;;; SHARED-INITIALIZE methods.  One cannot initialize these variables
245 ;;; to the right values here because said functions don't exist yet
246 ;;; when this file is first loaded.
247 (defvar *the-system-ii-method* nil)
248 (defvar *the-system-si-method* nil)
249
250 (defun install-optimized-constructor (ctor)
251   (let ((class (find-class (ctor-class-name ctor))))
252     (unless (class-finalized-p class)
253       (finalize-inheritance class))
254     (setf (ctor-class ctor) class)
255     (pushnew ctor (plist-value class 'ctors))
256     (setf (funcallable-instance-fun ctor)
257           ;; KLUDGE: Gerd here has the equivalent of (COMPILE NIL
258           ;; (CONSTRUCTOR-FUNCTION-FORM)), but SBCL's COMPILE doesn't
259           ;; deal with INSTANCE-LAMBDA expressions, only with LAMBDA
260           ;; expressions.  The below should be equivalent, since we
261           ;; have a compiler-only implementation.
262           ;;
263           ;; (except maybe for optimization qualities? -- CSR,
264           ;; 2004-07-12)
265           (eval `(function ,(constructor-function-form ctor))))))
266               
267 (defun constructor-function-form (ctor)
268   (let* ((class (ctor-class ctor))
269          (proto (class-prototype class))
270          (make-instance-methods
271           (compute-applicable-methods #'make-instance (list class)))
272          (allocate-instance-methods
273           (compute-applicable-methods #'allocate-instance (list class)))
274          ;; I stared at this in confusion for a while, thinking
275          ;; carefully about the possibility of the class prototype not
276          ;; being of sufficient discrimiating power, given the
277          ;; possibility of EQL-specialized methods on
278          ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE.  However, given
279          ;; that this is a constructor optimization, the user doesn't
280          ;; yet have the instance to create a method with such an EQL
281          ;; specializer.
282          ;;
283          ;; There remains the (theoretical) possibility of someone
284          ;; coming along with code of the form
285          ;;
286          ;; (defmethod initialize-instance :before ((o foo) ...)
287          ;;   (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
288          ;;
289          ;; but probably we can afford not to worry about this too
290          ;; much for now.  -- CSR, 2004-07-12
291          (ii-methods
292           (compute-applicable-methods #'initialize-instance (list proto)))
293          (si-methods
294           (compute-applicable-methods #'shared-initialize (list proto t)))
295          (setf-svuc-slots-methods
296           (loop for slot in (class-slots class)
297                 collect (compute-applicable-methods
298                          #'(setf slot-value-using-class)
299                          (list nil class proto slot))))
300          (sbuc-slots-methods
301           (loop for slot in (class-slots class)
302                 collect (compute-applicable-methods
303                          #'slot-boundp-using-class
304                          (list class proto slot)))))
305     ;; Cannot initialize these variables earlier because the generic
306     ;; functions don't exist when PCL is built.
307     (when (null *the-system-si-method*)
308       (setq *the-system-si-method*
309             (find-method #'shared-initialize
310                          () (list *the-class-slot-object* *the-class-t*)))
311       (setq *the-system-ii-method*
312             (find-method #'initialize-instance
313                          () (list *the-class-slot-object*))))
314     ;; Note that when there are user-defined applicable methods on
315     ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
316     ;; together with the system-defined ones in what
317     ;; COMPUTE-APPLICABLE-METHODS returns.
318     (or (and (not (structure-class-p class))
319              (not (condition-class-p class))
320              (null (cdr make-instance-methods))
321              (null (cdr allocate-instance-methods))
322              (every (lambda (x)
323                       (member (slot-definition-allocation x)
324                               '(:instance :class)))
325                     (class-slots class))
326              (null (check-initargs-1
327                     class
328                     (append
329                      (ctor-default-initkeys
330                       (ctor-initargs ctor) (class-default-initargs class))
331                      (plist-keys (ctor-initargs ctor)))
332                     (append ii-methods si-methods) nil nil))
333              (not (around-or-nonstandard-primary-method-p
334                    ii-methods *the-system-ii-method*))
335              (not (around-or-nonstandard-primary-method-p
336                    si-methods *the-system-si-method*))
337              ;; the instance structure protocol goes through
338              ;; slot-value(-using-class) and friends (actually just
339              ;; (SETF SLOT-VALUE-USING-CLASS) and
340              ;; SLOT-BOUNDP-USING-CLASS), so if there are non-standard
341              ;; applicable methods we can't shortcircuit them.
342              (every (lambda (x) (= (length x) 1)) setf-svuc-slots-methods)
343              (every (lambda (x) (= (length x) 1)) sbuc-slots-methods)
344              (optimizing-generator ctor ii-methods si-methods))
345         (fallback-generator ctor ii-methods si-methods))))
346
347 (defun around-or-nonstandard-primary-method-p
348     (methods &optional standard-method)
349   (loop with primary-checked-p = nil
350         for method in methods
351         as qualifiers = (method-qualifiers method)
352         when (or (eq :around (car qualifiers))
353                  (and (null qualifiers)
354                       (not primary-checked-p)
355                       (not (null standard-method))
356                       (not (eq standard-method method))))
357           return t
358         when (null qualifiers) do
359           (setq primary-checked-p t)))
360
361 (defun fallback-generator (ctor ii-methods si-methods)
362   (declare (ignore ii-methods si-methods))
363   `(instance-lambda ,(make-ctor-parameter-list ctor)
364      ;; The CTOR MAKE-INSTANCE optimization only kicks in when the
365      ;; first argument to MAKE-INSTANCE is a constant symbol: by
366      ;; calling it with a class, as here, we inhibit the optimization,
367      ;; so removing the possibility of endless recursion.  -- CSR,
368      ;; 2004-07-12
369      (make-instance ,(ctor-class ctor) ,@(ctor-initargs ctor))))
370
371 (defun optimizing-generator (ctor ii-methods si-methods)
372   (multiple-value-bind (body before-method-p)
373       (fake-initialization-emf ctor ii-methods si-methods)
374     `(instance-lambda ,(make-ctor-parameter-list ctor)
375        (declare #.*optimize-speed*)
376        ,(wrap-in-allocate-forms ctor body before-method-p))))
377
378 ;;; Return a form wrapped around BODY that allocates an instance
379 ;;; constructed by CTOR.  BEFORE-METHOD-P set means we have to run
380 ;;; before-methods, in which case we initialize instance slots to
381 ;;; +SLOT-UNBOUND+.  The resulting form binds the local variables
382 ;;; .INSTANCE. to the instance, and .SLOTS. to the instance's slot
383 ;;; vector around BODY.
384 (defun wrap-in-allocate-forms (ctor body before-method-p)
385   (let* ((class (ctor-class ctor))
386          (wrapper (class-wrapper class))
387          (allocation-function (raw-instance-allocator class))
388          (slots-fetcher (slots-fetcher class)))
389     (if (eq allocation-function 'allocate-standard-instance)
390         `(let ((.instance. (%make-standard-instance nil
391                                                     (get-instance-hash-code)))
392                (.slots. (make-array
393                          ,(layout-length wrapper)
394                          ,@(when before-method-p
395                              '(:initial-element +slot-unbound+)))))
396            (setf (std-instance-wrapper .instance.) ,wrapper)
397            (setf (std-instance-slots .instance.) .slots.)
398            ,body
399            .instance.)
400         `(let* ((.instance. (,allocation-function ,wrapper))
401                 (.slots. (,slots-fetcher .instance.)))
402            ,body
403            .instance.))))
404
405 ;;; Return a form for invoking METHOD with arguments from ARGS.  As
406 ;;; can be seen in METHOD-FUNCTION-FROM-FAST-FUNCTION, method
407 ;;; functions look like (LAMBDA (ARGS NEXT-METHODS) ...).  We could
408 ;;; call fast method functions directly here, but benchmarks show that
409 ;;; there's no speed to gain, so lets avoid the hair here.
410 (defmacro invoke-method (method args)
411   `(funcall ,(method-function method) ,args ()))
412
413 ;;; Return a form that is sort of an effective method comprising all
414 ;;; calls to INITIALIZE-INSTANCE and SHARED-INITIALIZE that would
415 ;;; normally have taken place when calling MAKE-INSTANCE.
416 (defun fake-initialization-emf (ctor ii-methods si-methods)
417   (multiple-value-bind (ii-around ii-before ii-primary ii-after)
418       (standard-sort-methods ii-methods)
419     (declare (ignore ii-primary))
420     (multiple-value-bind (si-around si-before si-primary si-after)
421         (standard-sort-methods si-methods)
422       (declare (ignore si-primary))
423       (aver (and (null ii-around) (null si-around)))
424       (let ((initargs (ctor-initargs ctor)))
425         (multiple-value-bind (bindings vars defaulting-initargs body)
426             (slot-init-forms ctor (or ii-before si-before))
427         (values
428          `(let ,bindings
429            (declare (ignorable ,@vars))
430            (let (,@(when (or ii-before ii-after)
431                      `((.ii-args.
432                         (list .instance. ,@(quote-plist-keys initargs) ,@defaulting-initargs))))
433                  ,@(when (or si-before si-after)
434                      `((.si-args.
435                         (list .instance. t ,@(quote-plist-keys initargs) ,@defaulting-initargs)))))
436             ,@(loop for method in ii-before
437                     collect `(invoke-method ,method .ii-args.))
438             ,@(loop for method in si-before
439                     collect `(invoke-method ,method .si-args.))
440             ,@body
441             ,@(loop for method in si-after
442                     collect `(invoke-method ,method .si-args.))
443             ,@(loop for method in ii-after
444                     collect `(invoke-method ,method .ii-args.))))
445          (or ii-before si-before)))))))
446
447 ;;; Return four values from APPLICABLE-METHODS: around methods, before
448 ;;; methods, the applicable primary method, and applicable after
449 ;;; methods.  Before and after methods are sorted in the order they
450 ;;; must be called.
451 (defun standard-sort-methods (applicable-methods)
452   (loop for method in applicable-methods
453         as qualifiers = (method-qualifiers method)
454         if (null qualifiers)
455           collect method into primary
456         else if (eq :around (car qualifiers))
457           collect method into around
458         else if (eq :after (car qualifiers))
459           collect method into after
460         else if (eq :before (car qualifiers))
461           collect method into before
462         finally
463           (return (values around before (first primary) (reverse after)))))
464
465 ;;; Return as multiple values bindings for default initialization
466 ;;; arguments, variable names, defaulting initargs and a body for
467 ;;; initializing instance and class slots of an object costructed by
468 ;;; CTOR.  The variable .SLOTS. is assumed to bound to the instance's
469 ;;; slot vector.  BEFORE-METHOD-P T means before-methods will be
470 ;;; called, which means that 1) other code will initialize instance
471 ;;; slots to +SLOT-UNBOUND+ before the before-methods are run, and
472 ;;; that we have to check if these before-methods have set slots.
473 (defun slot-init-forms (ctor before-method-p)
474   (let* ((class (ctor-class ctor))
475          (initargs (ctor-initargs ctor))
476          (initkeys (plist-keys initargs))
477          (slot-vector
478           (make-array (layout-length (class-wrapper class))
479                       :initial-element nil))
480          (class-inits ())
481          (default-inits ())
482          (defaulting-initargs ())
483          (default-initargs (class-default-initargs class))
484          (initarg-locations
485           (compute-initarg-locations
486            class (append initkeys (mapcar #'car default-initargs)))))
487     (labels ((initarg-locations (initarg)
488                (cdr (assoc initarg initarg-locations :test #'eq)))
489              (initializedp (location)
490                (cond
491                  ((consp location)
492                   (assoc location class-inits :test #'eq))
493                  ((integerp location)
494                   (not (null (aref slot-vector location))))
495                  (t (bug "Weird location in ~S" 'slot-init-forms))))
496              (class-init (location type val)
497                (aver (consp location))
498                (unless (initializedp location)
499                  (push (list location type val) class-inits)))
500              (instance-init (location type val)
501                (aver (integerp location))
502                (unless (initializedp location)
503                  (setf (aref slot-vector location) (list type val))))
504              (default-init-var-name (i)
505                (let ((ps #(.d0. .d1. .d2. .d3. .d4. .d5.)))
506                  (if (array-in-bounds-p ps i)
507                      (aref ps i)
508                      (format-symbol *pcl-package* ".D~D." i)))))
509       ;; Loop over supplied initargs and values and record which
510       ;; instance and class slots they initialize.
511       (loop for (key value) on initargs by #'cddr
512             as locations = (initarg-locations key) do
513               (if (constantp value)
514                   (dolist (location locations)
515                     (if (consp location)
516                         (class-init location 'constant value)
517                         (instance-init location 'constant value)))
518                   (dolist (location locations)
519                       (if (consp location)
520                           (class-init location 'param value)
521                           (instance-init location 'param value)))))
522       ;; Loop over default initargs of the class, recording
523       ;; initializations of slots that have not been initialized
524       ;; above.  Default initargs which are not in the supplied
525       ;; initargs are treated as if they were appended to supplied
526       ;; initargs, that is, their values must be evaluated even
527       ;; if not actually used for initializing a slot.
528       (loop for (key initfn initform) in default-initargs and i from 0
529             unless (member key initkeys :test #'eq) do
530             (let* ((type (if (constantp initform) 'constant 'var))
531                    (init (if (eq type 'var) initfn initform)))
532               (ecase type
533                 (constant
534                  (push key defaulting-initargs)
535                  (push initform defaulting-initargs))
536                 (var
537                  (push key defaulting-initargs)
538                  (push (default-init-var-name i) defaulting-initargs)))
539               (when (eq type 'var)
540                 (let ((init-var (default-init-var-name i)))
541                   (setq init init-var)
542                   (push (cons init-var initfn) default-inits)))
543               (dolist (location (initarg-locations key))
544                 (if (consp location)
545                     (class-init location type init)
546                     (instance-init location type init)))))
547       ;; Loop over all slots of the class, filling in the rest from
548       ;; slot initforms.
549       (loop for slotd in (class-slots class)
550             as location = (slot-definition-location slotd)
551             as allocation = (slot-definition-allocation slotd)
552             as initfn = (slot-definition-initfunction slotd)
553             as initform = (slot-definition-initform slotd) do
554               (unless (or (eq allocation :class)
555                           (null initfn)
556                           (initializedp location))
557                 (if (constantp initform)
558                     (instance-init location 'initform initform)
559                     (instance-init location 'initform/initfn initfn))))
560       ;; Generate the forms for initializing instance and class slots.
561       (let ((instance-init-forms
562              (loop for slot-entry across slot-vector and i from 0
563                    as (type value) = slot-entry collect
564                      (ecase type
565                        ((nil)
566                         (unless before-method-p
567                           `(setf (clos-slots-ref .slots. ,i) +slot-unbound+)))
568                        ((param var)
569                         `(setf (clos-slots-ref .slots. ,i) ,value))
570                        (initfn
571                         `(setf (clos-slots-ref .slots. ,i) (funcall ,value)))
572                        (initform/initfn
573                         (if before-method-p
574                             `(when (eq (clos-slots-ref .slots. ,i)
575                                        +slot-unbound+)
576                                (setf (clos-slots-ref .slots. ,i)
577                                      (funcall ,value)))
578                             `(setf (clos-slots-ref .slots. ,i)
579                                    (funcall ,value))))
580                        (initform
581                         (if before-method-p
582                             `(when (eq (clos-slots-ref .slots. ,i)
583                                        +slot-unbound+)
584                                (setf (clos-slots-ref .slots. ,i)
585                                      ',(eval value)))
586                             `(setf (clos-slots-ref .slots. ,i)
587                                    ',(eval value))))
588                        (constant
589                         `(setf (clos-slots-ref .slots. ,i) ',(eval value))))))
590             (class-init-forms
591              (loop for (location type value) in class-inits collect
592                      `(setf (cdr ',location)
593                             ,(ecase type
594                                (constant `',(eval value))
595                                ((param var) `,value)
596                                (initfn `(funcall ,value)))))))
597         (multiple-value-bind (vars bindings)
598             (loop for (var . initfn) in (nreverse default-inits)
599                   collect var into vars
600                   collect `(,var (funcall ,initfn)) into bindings
601                   finally (return (values vars bindings)))
602           (values bindings vars (nreverse defaulting-initargs)
603                   `(,@(delete nil instance-init-forms)
604                     ,@class-init-forms)))))))
605
606 ;;; Return an alist of lists (KEY LOCATION ...) telling, for each
607 ;;; key in INITKEYS, which locations the initarg initializes.
608 ;;; CLASS is the class of the instance being initialized.
609 (defun compute-initarg-locations (class initkeys)
610   (loop with slots = (class-slots class)
611         for key in initkeys collect
612           (loop for slot in slots
613                 if (memq key (slot-definition-initargs slot))
614                   collect (slot-definition-location slot) into locations
615                 else
616                   collect slot into remaining-slots
617                 finally
618                   (setq slots remaining-slots)
619                   (return (cons key locations)))))
620
621 \f
622 ;;; *******************************
623 ;;; External Entry Points  ********
624 ;;; *******************************
625
626 (defun update-ctors (reason &key class name generic-function method)
627   (labels ((reset (class &optional ri-cache-p (ctorsp t))
628              (when ctorsp
629                (dolist (ctor (plist-value class 'ctors))
630                  (install-initial-constructor ctor)))
631              (when ri-cache-p
632                (setf (plist-value class 'ri-initargs) ()))
633              (dolist (subclass (class-direct-subclasses class))
634                (reset subclass ri-cache-p ctorsp))))
635     (ecase reason
636       ;; CLASS must have been specified.
637       (finalize-inheritance
638        (reset class t))
639       ;; NAME must have been specified.
640       (setf-find-class
641        (loop for ctor in *all-ctors*
642              when (eq (ctor-class-name ctor) name) do
643              (when (ctor-class ctor)
644                (reset (ctor-class ctor)))
645              (loop-finish)))
646       ;; GENERIC-FUNCTION and METHOD must have been specified.
647       ((add-method remove-method)
648        (flet ((class-of-1st-method-param (method)
649                 (type-class (first (method-specializers method)))))
650          (case (generic-function-name generic-function)
651            ((make-instance allocate-instance
652              initialize-instance shared-initialize)
653             (reset (class-of-1st-method-param method) t t))
654            ((reinitialize-instance)
655             (reset (class-of-1st-method-param method) t nil))
656            (t (when (or (eq (generic-function-name generic-function)
657                             'slot-boundp-using-class)
658                         (equal (generic-function-name generic-function)
659                                '(setf slot-value-using-class)))
660                 ;; this looks awfully expensive, but given that one
661                 ;; can specialize on the SLOTD argument, nothing is
662                 ;; safe.  -- CSR, 2004-07-12
663                 (reset (find-class 'standard-object))))))))))
664
665 (defun precompile-ctors ()
666   (dolist (ctor *all-ctors*)
667     (when (null (ctor-class ctor))
668       (let ((class (find-class (ctor-class-name ctor) nil)))
669         (when (and class (class-finalized-p class))
670           (install-optimized-constructor ctor))))))
671
672 (defun check-ri-initargs (instance initargs)
673   (let* ((class (class-of instance))
674          (keys (plist-keys initargs))
675          (cached (assoc keys (plist-value class 'ri-initargs)
676                         :test #'equal))
677          (invalid-keys
678           (if (consp cached)
679               (cdr cached)
680               (let ((invalid
681                      ;; FIXME: give CHECK-INITARGS-1 and friends a
682                      ;; more mnemonic name and (possibly) a nicer,
683                      ;; more orthogonal interface.
684                      (check-initargs-1
685                       class initargs
686                       (list (list* 'reinitialize-instance instance initargs)
687                             (list* 'shared-initialize instance nil initargs))
688                       t nil)))
689                 (setf (plist-value class 'ri-initargs)
690                       (acons keys invalid cached))
691                 invalid))))
692     (when invalid-keys
693       (error 'initarg-error :class class :initargs invalid-keys))))
694
695 ;;; end of ctor.lisp