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