92965bfdb89d2fdcadf900a1ead217d54c40ec63
[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) 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 (defun make-ctor-function-name (class-name initargs)
138   (list* 'ctor class-name initargs))
139
140 ;;; Keep this a separate function for testing.
141 (defun ensure-ctor (function-name class-name initargs)
142   (unless (fboundp function-name)
143     (make-ctor function-name class-name initargs)))
144
145 ;;; Keep this a separate function for testing.
146 (defun make-ctor (function-name class-name initargs)
147   (without-package-locks ; for (setf symbol-function)
148    (let ((ctor (%make-ctor function-name class-name nil initargs)))
149      (push ctor *all-ctors*)
150      (setf (fdefinition function-name) ctor)
151      (install-initial-constructor ctor :force-p t)
152      ctor)))
153
154 \f
155 ;;; ***********************************************
156 ;;; Compile-Time Expansion of MAKE-INSTANCE *******
157 ;;; ***********************************************
158
159 (define-compiler-macro make-instance (&whole form &rest args)
160   (declare (ignore args))
161   (or (make-instance->constructor-call form)
162       form))
163
164 (defun make-instance->constructor-call (form)
165   (destructuring-bind (fn class-name &rest args) form
166     (declare (ignore fn))
167     (flet (;;
168            ;; Return the name of parameter number I of a constructor
169            ;; function.
170            (parameter-name (i)
171              (let ((ps #(.p0. .p1. .p2. .p3. .p4. .p5.)))
172                (if (array-in-bounds-p ps i)
173                    (aref ps i)
174                    (format-symbol *pcl-package* ".P~D." i))))
175            ;; Check if CLASS-NAME is a constant symbol.  Give up if
176            ;; not.
177            (check-class ()
178              (unless (and class-name (constant-symbol-p class-name))
179                (return-from make-instance->constructor-call nil)))
180            ;; Check if ARGS are suitable for an optimized constructor.
181            ;; Return NIL from the outer function if not.
182            (check-args ()
183              (loop for (key . more) on args by #'cddr do
184                      (when (or (null more)
185                                (not (constant-symbol-p key))
186                                (eq :allow-other-keys (eval key)))
187                        (return-from make-instance->constructor-call nil)))))
188       (check-class)
189       (check-args)
190       ;; Collect a plist of initargs and constant values/parameter names
191       ;; in INITARGS.  Collect non-constant initialization forms in
192       ;; VALUE-FORMS.
193       (multiple-value-bind (initargs value-forms)
194           (loop for (key value) on args by #'cddr and i from 0
195                 collect (eval key) into initargs
196                 if (constantp value)
197                   collect value into initargs
198                 else
199                   collect (parameter-name i) into initargs
200                   and collect value into value-forms
201                 finally
202                   (return (values initargs value-forms)))
203         (let* ((class-name (eval class-name))
204                (function-name (make-ctor-function-name class-name initargs)))
205           ;; Prevent compiler warnings for calling the ctor.
206           (proclaim-as-fun-name function-name)
207           (note-name-defined function-name :function)
208           (when (eq (info :function :where-from function-name) :assumed)
209             (setf (info :function :where-from function-name) :defined)
210             (when (info :function :assumed-type function-name)
211               (setf (info :function :assumed-type function-name) nil)))
212           ;; Return code constructing a ctor at load time, which, when
213           ;; called, will set its funcallable instance function to an
214           ;; optimized constructor function.
215           `(locally
216                (declare (disable-package-locks ,function-name))
217             (let ((.x. (load-time-value
218                         (ensure-ctor ',function-name ',class-name ',initargs))))
219               (declare (ignore .x.))
220               ;; ??? check if this is worth it.
221               (declare
222                (ftype (or (function ,(make-list (length value-forms)
223                                                 :initial-element t)
224                                     t)
225                           (function (&rest t) t))
226                       ,function-name))
227               (funcall (function ,function-name) ,@value-forms))))))))
228
229 \f
230 ;;; **************************************************
231 ;;; Load-Time Constructor Function Generation  *******
232 ;;; **************************************************
233
234 ;;; The system-supplied primary INITIALIZE-INSTANCE and
235 ;;; SHARED-INITIALIZE methods.  One cannot initialize these variables
236 ;;; to the right values here because said functions don't exist yet
237 ;;; when this file is first loaded.
238 (defvar *the-system-ii-method* nil)
239 (defvar *the-system-si-method* nil)
240
241 (defun install-optimized-constructor (ctor)
242   (let ((class (find-class (ctor-class-name ctor))))
243     (unless (class-finalized-p class)
244       (finalize-inheritance class))
245     (setf (ctor-class ctor) class)
246     (pushnew ctor (plist-value class 'ctors))
247     (setf (funcallable-instance-fun ctor)
248           ;; KLUDGE: Gerd here has the equivalent of (COMPILE NIL
249           ;; (CONSTRUCTOR-FUNCTION-FORM)), but SBCL's COMPILE doesn't
250           ;; deal with INSTANCE-LAMBDA expressions, only with LAMBDA
251           ;; expressions.  The below should be equivalent, since we
252           ;; have a compiler-only implementation.
253           ;;
254           ;; (except maybe for optimization qualities? -- CSR,
255           ;; 2004-07-12)
256           (eval `(function ,(constructor-function-form ctor))))))
257
258 (defun constructor-function-form (ctor)
259   (let* ((class (ctor-class ctor))
260          (proto (class-prototype class))
261          (make-instance-methods
262           (compute-applicable-methods #'make-instance (list class)))
263          (allocate-instance-methods
264           (compute-applicable-methods #'allocate-instance (list class)))
265          ;; I stared at this in confusion for a while, thinking
266          ;; carefully about the possibility of the class prototype not
267          ;; being of sufficient discrimiating power, given the
268          ;; possibility of EQL-specialized methods on
269          ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE.  However, given
270          ;; that this is a constructor optimization, the user doesn't
271          ;; yet have the instance to create a method with such an EQL
272          ;; specializer.
273          ;;
274          ;; There remains the (theoretical) possibility of someone
275          ;; coming along with code of the form
276          ;;
277          ;; (defmethod initialize-instance :before ((o foo) ...)
278          ;;   (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
279          ;;
280          ;; but probably we can afford not to worry about this too
281          ;; much for now.  -- CSR, 2004-07-12
282          (ii-methods
283           (compute-applicable-methods #'initialize-instance (list proto)))
284          (si-methods
285           (compute-applicable-methods #'shared-initialize (list proto t)))
286          (setf-svuc-slots-methods
287           (loop for slot in (class-slots class)
288                 collect (compute-applicable-methods
289                          #'(setf slot-value-using-class)
290                          (list nil class proto slot))))
291          (sbuc-slots-methods
292           (loop for slot in (class-slots class)
293                 collect (compute-applicable-methods
294                          #'slot-boundp-using-class
295                          (list class proto slot)))))
296     ;; Cannot initialize these variables earlier because the generic
297     ;; functions don't exist when PCL is built.
298     (when (null *the-system-si-method*)
299       (setq *the-system-si-method*
300             (find-method #'shared-initialize
301                          () (list *the-class-slot-object* *the-class-t*)))
302       (setq *the-system-ii-method*
303             (find-method #'initialize-instance
304                          () (list *the-class-slot-object*))))
305     ;; Note that when there are user-defined applicable methods on
306     ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
307     ;; together with the system-defined ones in what
308     ;; COMPUTE-APPLICABLE-METHODS returns.
309     (or (and (not (structure-class-p class))
310              (not (condition-class-p class))
311              (null (cdr make-instance-methods))
312              (null (cdr allocate-instance-methods))
313              (every (lambda (x)
314                       (member (slot-definition-allocation x)
315                               '(:instance :class)))
316                     (class-slots class))
317              (null (check-initargs-1
318                     class
319                     (append
320                      (ctor-default-initkeys
321                       (ctor-initargs ctor) (class-default-initargs class))
322                      (plist-keys (ctor-initargs ctor)))
323                     (append ii-methods si-methods) nil nil))
324              (not (around-or-nonstandard-primary-method-p
325                    ii-methods *the-system-ii-method*))
326              (not (around-or-nonstandard-primary-method-p
327                    si-methods *the-system-si-method*))
328              ;; the instance structure protocol goes through
329              ;; slot-value(-using-class) and friends (actually just
330              ;; (SETF SLOT-VALUE-USING-CLASS) and
331              ;; SLOT-BOUNDP-USING-CLASS), so if there are non-standard
332              ;; applicable methods we can't shortcircuit them.
333              (every (lambda (x) (= (length x) 1)) setf-svuc-slots-methods)
334              (every (lambda (x) (= (length x) 1)) sbuc-slots-methods)
335              (optimizing-generator ctor ii-methods si-methods))
336         (fallback-generator ctor ii-methods si-methods))))
337
338 (defun around-or-nonstandard-primary-method-p
339     (methods &optional standard-method)
340   (loop with primary-checked-p = nil
341         for method in methods
342         as qualifiers = (method-qualifiers method)
343         when (or (eq :around (car qualifiers))
344                  (and (null qualifiers)
345                       (not primary-checked-p)
346                       (not (null standard-method))
347                       (not (eq standard-method method))))
348           return t
349         when (null qualifiers) do
350           (setq primary-checked-p t)))
351
352 (defun fallback-generator (ctor ii-methods si-methods)
353   (declare (ignore ii-methods si-methods))
354   `(instance-lambda ,(make-ctor-parameter-list ctor)
355      ;; The CTOR MAKE-INSTANCE optimization only kicks in when the
356      ;; first argument to MAKE-INSTANCE is a constant symbol: by
357      ;; calling it with a class, as here, we inhibit the optimization,
358      ;; so removing the possibility of endless recursion.  -- CSR,
359      ;; 2004-07-12
360      (make-instance ,(ctor-class ctor) ,@(ctor-initargs ctor))))
361
362 (defun optimizing-generator (ctor ii-methods si-methods)
363   (multiple-value-bind (body before-method-p)
364       (fake-initialization-emf ctor ii-methods si-methods)
365     `(instance-lambda ,(make-ctor-parameter-list ctor)
366        (declare #.*optimize-speed*)
367        ,(wrap-in-allocate-forms ctor body before-method-p))))
368
369 ;;; Return a form wrapped around BODY that allocates an instance
370 ;;; constructed by CTOR.  BEFORE-METHOD-P set means we have to run
371 ;;; before-methods, in which case we initialize instance slots to
372 ;;; +SLOT-UNBOUND+.  The resulting form binds the local variables
373 ;;; .INSTANCE. to the instance, and .SLOTS. to the instance's slot
374 ;;; vector around BODY.
375 (defun wrap-in-allocate-forms (ctor body before-method-p)
376   (let* ((class (ctor-class ctor))
377          (wrapper (class-wrapper class))
378          (allocation-function (raw-instance-allocator class))
379          (slots-fetcher (slots-fetcher class)))
380     (if (eq allocation-function 'allocate-standard-instance)
381         `(let ((.instance. (%make-standard-instance nil
382                                                     (get-instance-hash-code)))
383                (.slots. (make-array
384                          ,(layout-length wrapper)
385                          ,@(when before-method-p
386                              '(:initial-element +slot-unbound+)))))
387            (setf (std-instance-wrapper .instance.) ,wrapper)
388            (setf (std-instance-slots .instance.) .slots.)
389            ,body
390            .instance.)
391         `(let* ((.instance. (,allocation-function ,wrapper))
392                 (.slots. (,slots-fetcher .instance.)))
393            ,body
394            .instance.))))
395
396 ;;; Return a form for invoking METHOD with arguments from ARGS.  As
397 ;;; can be seen in METHOD-FUNCTION-FROM-FAST-FUNCTION, method
398 ;;; functions look like (LAMBDA (ARGS NEXT-METHODS) ...).  We could
399 ;;; call fast method functions directly here, but benchmarks show that
400 ;;; there's no speed to gain, so lets avoid the hair here.
401 (defmacro invoke-method (method args)
402   `(funcall ,(method-function method) ,args ()))
403
404 ;;; Return a form that is sort of an effective method comprising all
405 ;;; calls to INITIALIZE-INSTANCE and SHARED-INITIALIZE that would
406 ;;; normally have taken place when calling MAKE-INSTANCE.
407 (defun fake-initialization-emf (ctor ii-methods si-methods)
408   (multiple-value-bind (ii-around ii-before ii-primary ii-after)
409       (standard-sort-methods ii-methods)
410     (declare (ignore ii-primary))
411     (multiple-value-bind (si-around si-before si-primary si-after)
412         (standard-sort-methods si-methods)
413       (declare (ignore si-primary))
414       (aver (and (null ii-around) (null si-around)))
415       (let ((initargs (ctor-initargs ctor)))
416         (multiple-value-bind (bindings vars defaulting-initargs body)
417             (slot-init-forms ctor (or ii-before si-before))
418         (values
419          `(let ,bindings
420            (declare (ignorable ,@vars))
421            (let (,@(when (or ii-before ii-after)
422                      `((.ii-args.
423                         (list .instance. ,@(quote-plist-keys initargs) ,@defaulting-initargs))))
424                  ,@(when (or si-before si-after)
425                      `((.si-args.
426                         (list .instance. t ,@(quote-plist-keys initargs) ,@defaulting-initargs)))))
427             ,@(loop for method in ii-before
428                     collect `(invoke-method ,method .ii-args.))
429             ,@(loop for method in si-before
430                     collect `(invoke-method ,method .si-args.))
431             ,@body
432             ,@(loop for method in si-after
433                     collect `(invoke-method ,method .si-args.))
434             ,@(loop for method in ii-after
435                     collect `(invoke-method ,method .ii-args.))))
436          (or ii-before si-before)))))))
437
438 ;;; Return four values from APPLICABLE-METHODS: around methods, before
439 ;;; methods, the applicable primary method, and applicable after
440 ;;; methods.  Before and after methods are sorted in the order they
441 ;;; must be called.
442 (defun standard-sort-methods (applicable-methods)
443   (loop for method in applicable-methods
444         as qualifiers = (method-qualifiers method)
445         if (null qualifiers)
446           collect method into primary
447         else if (eq :around (car qualifiers))
448           collect method into around
449         else if (eq :after (car qualifiers))
450           collect method into after
451         else if (eq :before (car qualifiers))
452           collect method into before
453         finally
454           (return (values around before (first primary) (reverse after)))))
455
456 ;;; Return as multiple values bindings for default initialization
457 ;;; arguments, variable names, defaulting initargs and a body for
458 ;;; initializing instance and class slots of an object costructed by
459 ;;; CTOR.  The variable .SLOTS. is assumed to bound to the instance's
460 ;;; slot vector.  BEFORE-METHOD-P T means before-methods will be
461 ;;; called, which means that 1) other code will initialize instance
462 ;;; slots to +SLOT-UNBOUND+ before the before-methods are run, and
463 ;;; that we have to check if these before-methods have set slots.
464 (defun slot-init-forms (ctor before-method-p)
465   (let* ((class (ctor-class ctor))
466          (initargs (ctor-initargs ctor))
467          (initkeys (plist-keys initargs))
468          (slot-vector
469           (make-array (layout-length (class-wrapper class))
470                       :initial-element nil))
471          (class-inits ())
472          (default-inits ())
473          (defaulting-initargs ())
474          (default-initargs (class-default-initargs class))
475          (initarg-locations
476           (compute-initarg-locations
477            class (append initkeys (mapcar #'car default-initargs)))))
478     (labels ((initarg-locations (initarg)
479                (cdr (assoc initarg initarg-locations :test #'eq)))
480              (initializedp (location)
481                (cond
482                  ((consp location)
483                   (assoc location class-inits :test #'eq))
484                  ((integerp location)
485                   (not (null (aref slot-vector location))))
486                  (t (bug "Weird location in ~S" 'slot-init-forms))))
487              (class-init (location type val)
488                (aver (consp location))
489                (unless (initializedp location)
490                  (push (list location type val) class-inits)))
491              (instance-init (location type val)
492                (aver (integerp location))
493                (unless (initializedp location)
494                  (setf (aref slot-vector location) (list type val))))
495              (default-init-var-name (i)
496                (let ((ps #(.d0. .d1. .d2. .d3. .d4. .d5.)))
497                  (if (array-in-bounds-p ps i)
498                      (aref ps i)
499                      (format-symbol *pcl-package* ".D~D." i)))))
500       ;; Loop over supplied initargs and values and record which
501       ;; instance and class slots they initialize.
502       (loop for (key value) on initargs by #'cddr
503             as locations = (initarg-locations key) do
504               (if (constantp value)
505                   (dolist (location locations)
506                     (if (consp location)
507                         (class-init location 'constant value)
508                         (instance-init location 'constant value)))
509                   (dolist (location locations)
510                       (if (consp location)
511                           (class-init location 'param value)
512                           (instance-init location 'param value)))))
513       ;; Loop over default initargs of the class, recording
514       ;; initializations of slots that have not been initialized
515       ;; above.  Default initargs which are not in the supplied
516       ;; initargs are treated as if they were appended to supplied
517       ;; initargs, that is, their values must be evaluated even
518       ;; if not actually used for initializing a slot.
519       (loop for (key initform initfn) in default-initargs and i from 0
520             unless (member key initkeys :test #'eq) do
521             (let* ((type (if (constantp initform) 'constant 'var))
522                    (init (if (eq type 'var) initfn initform)))
523               (ecase type
524                 (constant
525                  (push key defaulting-initargs)
526                  (push initform defaulting-initargs))
527                 (var
528                  (push key defaulting-initargs)
529                  (push (default-init-var-name i) defaulting-initargs)))
530               (when (eq type 'var)
531                 (let ((init-var (default-init-var-name i)))
532                   (setq init init-var)
533                   (push (cons init-var initfn) default-inits)))
534               (dolist (location (initarg-locations key))
535                 (if (consp location)
536                     (class-init location type init)
537                     (instance-init location type init)))))
538       ;; Loop over all slots of the class, filling in the rest from
539       ;; slot initforms.
540       (loop for slotd in (class-slots class)
541             as location = (slot-definition-location slotd)
542             as allocation = (slot-definition-allocation slotd)
543             as initfn = (slot-definition-initfunction slotd)
544             as initform = (slot-definition-initform slotd) do
545               (unless (or (eq allocation :class)
546                           (null initfn)
547                           (initializedp location))
548                 (if (constantp initform)
549                     (instance-init location 'initform initform)
550                     (instance-init location 'initform/initfn initfn))))
551       ;; Generate the forms for initializing instance and class slots.
552       (let ((instance-init-forms
553              (loop for slot-entry across slot-vector and i from 0
554                    as (type value) = slot-entry collect
555                      (ecase type
556                        ((nil)
557                         (unless before-method-p
558                           `(setf (clos-slots-ref .slots. ,i) +slot-unbound+)))
559                        ((param var)
560                         `(setf (clos-slots-ref .slots. ,i) ,value))
561                        (initfn
562                         `(setf (clos-slots-ref .slots. ,i) (funcall ,value)))
563                        (initform/initfn
564                         (if before-method-p
565                             `(when (eq (clos-slots-ref .slots. ,i)
566                                        +slot-unbound+)
567                                (setf (clos-slots-ref .slots. ,i)
568                                      (funcall ,value)))
569                             `(setf (clos-slots-ref .slots. ,i)
570                                    (funcall ,value))))
571                        (initform
572                         (if before-method-p
573                             `(when (eq (clos-slots-ref .slots. ,i)
574                                        +slot-unbound+)
575                                (setf (clos-slots-ref .slots. ,i)
576                                      ',(eval value)))
577                             `(setf (clos-slots-ref .slots. ,i)
578                                    ',(eval value))))
579                        (constant
580                         `(setf (clos-slots-ref .slots. ,i) ',(eval value))))))
581             (class-init-forms
582              (loop for (location type value) in class-inits collect
583                      `(setf (cdr ',location)
584                             ,(ecase type
585                                (constant `',(eval value))
586                                ((param var) `,value)
587                                (initfn `(funcall ,value)))))))
588         (multiple-value-bind (vars bindings)
589             (loop for (var . initfn) in (nreverse default-inits)
590                   collect var into vars
591                   collect `(,var (funcall ,initfn)) into bindings
592                   finally (return (values vars bindings)))
593           (values bindings vars (nreverse defaulting-initargs)
594                   `(,@(delete nil instance-init-forms)
595                     ,@class-init-forms)))))))
596
597 ;;; Return an alist of lists (KEY LOCATION ...) telling, for each
598 ;;; key in INITKEYS, which locations the initarg initializes.
599 ;;; CLASS is the class of the instance being initialized.
600 (defun compute-initarg-locations (class initkeys)
601   (loop with slots = (class-slots class)
602         for key in initkeys collect
603           (loop for slot in slots
604                 if (memq key (slot-definition-initargs slot))
605                   collect (slot-definition-location slot) into locations
606                 else
607                   collect slot into remaining-slots
608                 finally
609                   (setq slots remaining-slots)
610                   (return (cons key locations)))))
611
612 \f
613 ;;; *******************************
614 ;;; External Entry Points  ********
615 ;;; *******************************
616
617 (defun update-ctors (reason &key class name generic-function method)
618   (labels ((reset (class &optional ri-cache-p (ctorsp t))
619              (when ctorsp
620                (dolist (ctor (plist-value class 'ctors))
621                  (install-initial-constructor ctor)))
622              (when ri-cache-p
623                (setf (plist-value class 'ri-initargs) ()))
624              (dolist (subclass (class-direct-subclasses class))
625                (reset subclass ri-cache-p ctorsp))))
626     (ecase reason
627       ;; CLASS must have been specified.
628       (finalize-inheritance
629        (reset class t))
630       ;; NAME must have been specified.
631       (setf-find-class
632        (loop for ctor in *all-ctors*
633              when (eq (ctor-class-name ctor) name) do
634              (when (ctor-class ctor)
635                (reset (ctor-class ctor)))
636              (loop-finish)))
637       ;; GENERIC-FUNCTION and METHOD must have been specified.
638       ((add-method remove-method)
639        (flet ((class-of-1st-method-param (method)
640                 (type-class (first (method-specializers method)))))
641          (case (generic-function-name generic-function)
642            ((make-instance allocate-instance
643              initialize-instance shared-initialize)
644             (reset (class-of-1st-method-param method) t t))
645            ((reinitialize-instance)
646             (reset (class-of-1st-method-param method) t nil))
647            (t (when (or (eq (generic-function-name generic-function)
648                             'slot-boundp-using-class)
649                         (equal (generic-function-name generic-function)
650                                '(setf slot-value-using-class)))
651                 ;; this looks awfully expensive, but given that one
652                 ;; can specialize on the SLOTD argument, nothing is
653                 ;; safe.  -- CSR, 2004-07-12
654                 (reset (find-class 'standard-object))))))))))
655
656 (defun precompile-ctors ()
657   (dolist (ctor *all-ctors*)
658     (when (null (ctor-class ctor))
659       (let ((class (find-class (ctor-class-name ctor) nil)))
660         (when (and class (class-finalized-p class))
661           (install-optimized-constructor ctor))))))
662
663 (defun check-ri-initargs (instance initargs)
664   (let* ((class (class-of instance))
665          (keys (plist-keys initargs))
666          (cached (assoc keys (plist-value class 'ri-initargs)
667                         :test #'equal))
668          (invalid-keys
669           (if (consp cached)
670               (cdr cached)
671               (let ((invalid
672                      ;; FIXME: give CHECK-INITARGS-1 and friends a
673                      ;; more mnemonic name and (possibly) a nicer,
674                      ;; more orthogonal interface.
675                      (check-initargs-1
676                       class initargs
677                       (list (list* 'reinitialize-instance instance initargs)
678                             (list* 'shared-initialize instance nil initargs))
679                       t nil)))
680                 (setf (plist-value class 'ri-initargs)
681                       (acons keys invalid cached))
682                 invalid))))
683     (when invalid-keys
684       (error 'initarg-error :class class :initargs invalid-keys))))
685
686 ;;; end of ctor.lisp