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