0.9.18.38:
[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 (constant-form-value 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 safe-p)
111   :boa-constructor %make-ctor
112   :superclass-name function
113   :metaclass-name static-classoid
114   :metaclass-constructor make-static-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 safe-code-p)
138   (list* 'ctor class-name safe-code-p initargs))
139
140 ;;; Keep this a separate function for testing.
141 (defun ensure-ctor (function-name class-name initargs safe-code-p)
142   (unless (fboundp function-name)
143     (make-ctor function-name class-name initargs safe-code-p)))
144
145 ;;; Keep this a separate function for testing.
146 (defun make-ctor (function-name class-name initargs safe-p)
147   (without-package-locks ; for (setf symbol-function)
148    (let ((ctor (%make-ctor function-name class-name nil initargs safe-p)))
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 &environment env)
160   (declare (ignore args))
161   (or (make-instance->constructor-call form (safe-code-p env))
162       form))
163
164 (defun make-instance->constructor-call (form safe-code-p)
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 (constant-form-value 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 (constant-form-value 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 (constant-form-value class-name))
204                (function-name (make-ctor-function-name class-name initargs
205                                                        safe-code-p)))
206           ;; Prevent compiler warnings for calling the ctor.
207           (proclaim-as-fun-name function-name)
208           (note-name-defined function-name :function)
209           (when (eq (info :function :where-from function-name) :assumed)
210             (setf (info :function :where-from function-name) :defined)
211             (when (info :function :assumed-type function-name)
212               (setf (info :function :assumed-type function-name) nil)))
213           ;; Return code constructing a ctor at load time, which, when
214           ;; called, will set its funcallable instance function to an
215           ;; optimized constructor function.
216           `(locally
217                (declare (disable-package-locks ,function-name))
218             (let ((.x. (load-time-value
219                         (ensure-ctor ',function-name ',class-name ',initargs
220                                      ',safe-code-p))))
221               (declare (ignore .x.))
222               ;; ??? check if this is worth it.
223               (declare
224                (ftype (or (function ,(make-list (length value-forms)
225                                                 :initial-element t)
226                                     t)
227                           (function (&rest t) t))
228                       ,function-name))
229               (funcall (function ,function-name) ,@value-forms))))))))
230
231 \f
232 ;;; **************************************************
233 ;;; Load-Time Constructor Function Generation  *******
234 ;;; **************************************************
235
236 ;;; The system-supplied primary INITIALIZE-INSTANCE and
237 ;;; SHARED-INITIALIZE methods.  One cannot initialize these variables
238 ;;; to the right values here because said functions don't exist yet
239 ;;; when this file is first loaded.
240 (defvar *the-system-ii-method* nil)
241 (defvar *the-system-si-method* nil)
242
243 (defun install-optimized-constructor (ctor)
244   (let ((class (find-class (ctor-class-name ctor))))
245     (unless (class-finalized-p class)
246       (finalize-inheritance class))
247     (setf (ctor-class ctor) class)
248     (pushnew ctor (plist-value class 'ctors))
249     (setf (funcallable-instance-fun ctor)
250           (multiple-value-bind (form locations names)
251               (constructor-function-form ctor)
252             (apply (compile nil `(lambda ,names ,form)) locations)))))
253
254 (defun constructor-function-form (ctor)
255   (let* ((class (ctor-class ctor))
256          (proto (class-prototype class))
257          (make-instance-methods
258           (compute-applicable-methods #'make-instance (list class)))
259          (allocate-instance-methods
260           (compute-applicable-methods #'allocate-instance (list class)))
261          ;; I stared at this in confusion for a while, thinking
262          ;; carefully about the possibility of the class prototype not
263          ;; being of sufficient discrimiating power, given the
264          ;; possibility of EQL-specialized methods on
265          ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE.  However, given
266          ;; that this is a constructor optimization, the user doesn't
267          ;; yet have the instance to create a method with such an EQL
268          ;; specializer.
269          ;;
270          ;; There remains the (theoretical) possibility of someone
271          ;; coming along with code of the form
272          ;;
273          ;; (defmethod initialize-instance :before ((o foo) ...)
274          ;;   (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
275          ;;
276          ;; but probably we can afford not to worry about this too
277          ;; much for now.  -- CSR, 2004-07-12
278          (ii-methods
279           (compute-applicable-methods #'initialize-instance (list proto)))
280          (si-methods
281           (compute-applicable-methods #'shared-initialize (list proto t)))
282          (setf-svuc-slots-methods
283           (loop for slot in (class-slots class)
284                 collect (compute-applicable-methods
285                          #'(setf slot-value-using-class)
286                          (list nil class proto slot))))
287          (sbuc-slots-methods
288           (loop for slot in (class-slots class)
289                 collect (compute-applicable-methods
290                          #'slot-boundp-using-class
291                          (list class proto slot)))))
292     ;; Cannot initialize these variables earlier because the generic
293     ;; functions don't exist when PCL is built.
294     (when (null *the-system-si-method*)
295       (setq *the-system-si-method*
296             (find-method #'shared-initialize
297                          () (list *the-class-slot-object* *the-class-t*)))
298       (setq *the-system-ii-method*
299             (find-method #'initialize-instance
300                          () (list *the-class-slot-object*))))
301     ;; Note that when there are user-defined applicable methods on
302     ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
303     ;; together with the system-defined ones in what
304     ;; COMPUTE-APPLICABLE-METHODS returns.
305     (if (and (not (structure-class-p class))
306              (not (condition-class-p class))
307              (null (cdr make-instance-methods))
308              (null (cdr allocate-instance-methods))
309              (every (lambda (x)
310                       (member (slot-definition-allocation x)
311                               '(:instance :class)))
312                     (class-slots class))
313              (null (check-initargs-1
314                     class
315                     (append
316                      (ctor-default-initkeys
317                       (ctor-initargs ctor) (class-default-initargs class))
318                      (plist-keys (ctor-initargs ctor)))
319                     (append ii-methods si-methods) nil nil))
320              (not (around-or-nonstandard-primary-method-p
321                    ii-methods *the-system-ii-method*))
322              (not (around-or-nonstandard-primary-method-p
323                    si-methods *the-system-si-method*))
324              ;; the instance structure protocol goes through
325              ;; slot-value(-using-class) and friends (actually just
326              ;; (SETF SLOT-VALUE-USING-CLASS) and
327              ;; SLOT-BOUNDP-USING-CLASS), so if there are non-standard
328              ;; applicable methods we can't shortcircuit them.
329              (every (lambda (x) (= (length x) 1)) setf-svuc-slots-methods)
330              (every (lambda (x) (= (length x) 1)) sbuc-slots-methods))
331         (optimizing-generator ctor ii-methods si-methods)
332         (fallback-generator ctor ii-methods si-methods))))
333
334 (defun around-or-nonstandard-primary-method-p
335     (methods &optional standard-method)
336   (loop with primary-checked-p = nil
337         for method in methods
338         as qualifiers = (method-qualifiers method)
339         when (or (eq :around (car qualifiers))
340                  (and (null qualifiers)
341                       (not primary-checked-p)
342                       (not (null standard-method))
343                       (not (eq standard-method method))))
344           return t
345         when (null qualifiers) do
346           (setq primary-checked-p t)))
347
348 (defun fallback-generator (ctor ii-methods si-methods)
349   (declare (ignore ii-methods si-methods))
350   `(lambda ,(make-ctor-parameter-list ctor)
351      ;; The CTOR MAKE-INSTANCE optimization only kicks in when the
352      ;; first argument to MAKE-INSTANCE is a constant symbol: by
353      ;; calling it with a class, as here, we inhibit the optimization,
354      ;; so removing the possibility of endless recursion.  -- CSR,
355      ;; 2004-07-12
356      (make-instance ,(ctor-class ctor)
357       ,@(quote-plist-keys (ctor-initargs ctor)))))
358
359 (defun optimizing-generator (ctor ii-methods si-methods)
360   (multiple-value-bind (locations names body before-method-p)
361       (fake-initialization-emf ctor ii-methods si-methods)
362     (values
363      `(lambda ,(make-ctor-parameter-list ctor)
364        (declare #.*optimize-speed*)
365        ,(wrap-in-allocate-forms ctor body before-method-p))
366      locations
367      names)))
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 (locations names bindings vars defaulting-initargs body)
417             (slot-init-forms ctor (or ii-before si-before))
418         (values
419          locations
420          names
421          `(let ,bindings
422            (declare (ignorable ,@vars))
423            (let (,@(when (or ii-before ii-after)
424                      `((.ii-args.
425                         (list .instance. ,@(quote-plist-keys initargs) ,@defaulting-initargs))))
426                  ,@(when (or si-before si-after)
427                      `((.si-args.
428                         (list .instance. t ,@(quote-plist-keys initargs) ,@defaulting-initargs)))))
429             ,@(loop for method in ii-before
430                     collect `(invoke-method ,method .ii-args.))
431             ,@(loop for method in si-before
432                     collect `(invoke-method ,method .si-args.))
433             ,@body
434             ,@(loop for method in si-after
435                     collect `(invoke-method ,method .si-args.))
436             ,@(loop for method in ii-after
437                     collect `(invoke-method ,method .ii-args.))))
438          (or ii-before si-before)))))))
439
440 ;;; Return four values from APPLICABLE-METHODS: around methods, before
441 ;;; methods, the applicable primary method, and applicable after
442 ;;; methods.  Before and after methods are sorted in the order they
443 ;;; must be called.
444 (defun standard-sort-methods (applicable-methods)
445   (loop for method in applicable-methods
446         as qualifiers = (method-qualifiers method)
447         if (null qualifiers)
448           collect method into primary
449         else if (eq :around (car qualifiers))
450           collect method into around
451         else if (eq :after (car qualifiers))
452           collect method into after
453         else if (eq :before (car qualifiers))
454           collect method into before
455         finally
456           (return (values around before (first primary) (reverse after)))))
457
458 (defmacro with-type-checked ((type safe-p) &body body)
459   (if safe-p
460       ;; To handle FUNCTION types reasonable, we use SAFETY 3 and
461       ;; THE instead of e.g. CHECK-TYPE.
462       `(locally
463            (declare (optimize (safety 3)))
464          (the ,type (progn ,@body)))
465       `(progn ,@body)))
466
467 ;;; Return as multiple values bindings for default initialization
468 ;;; arguments, variable names, defaulting initargs and a body for
469 ;;; initializing instance and class slots of an object costructed by
470 ;;; CTOR.  The variable .SLOTS. is assumed to bound to the instance's
471 ;;; slot vector.  BEFORE-METHOD-P T means before-methods will be
472 ;;; called, which means that 1) other code will initialize instance
473 ;;; slots to +SLOT-UNBOUND+ before the before-methods are run, and
474 ;;; that we have to check if these before-methods have set slots.
475 (defun slot-init-forms (ctor before-method-p)
476   (let* ((class (ctor-class ctor))
477          (initargs (ctor-initargs ctor))
478          (initkeys (plist-keys initargs))
479          (safe-p (ctor-safe-p ctor))
480          (slot-vector
481           (make-array (layout-length (class-wrapper class))
482                       :initial-element nil))
483          (class-inits ())
484          (default-inits ())
485          (defaulting-initargs ())
486          (default-initargs (class-default-initargs class))
487          (initarg-locations
488           (compute-initarg-locations
489            class (append initkeys (mapcar #'car default-initargs)))))
490     (labels ((initarg-locations (initarg)
491                (cdr (assoc initarg initarg-locations :test #'eq)))
492              (initializedp (location)
493                (cond
494                  ((consp location)
495                   (assoc location class-inits :test #'eq))
496                  ((integerp location)
497                   (not (null (aref slot-vector location))))
498                  (t (bug "Weird location in ~S" 'slot-init-forms))))
499              (class-init (location kind val type)
500                (aver (consp location))
501                (unless (initializedp location)
502                  (push (list location kind val type) class-inits)))
503              (instance-init (location kind val type)
504                (aver (integerp location))
505                (unless (initializedp location)
506                  (setf (aref slot-vector location) (list kind val type))))
507              (default-init-var-name (i)
508                (let ((ps #(.d0. .d1. .d2. .d3. .d4. .d5.)))
509                  (if (array-in-bounds-p ps i)
510                      (aref ps i)
511                      (format-symbol *pcl-package* ".D~D." i))))
512              (location-var-name (i)
513                (let ((ls #(.l0. .l1. .l2. .l3. .l4. .l5.)))
514                  (if (array-in-bounds-p ls i)
515                      (aref ls i)
516                      (format-symbol *pcl-package* ".L~D." i)))))
517       ;; Loop over supplied initargs and values and record which
518       ;; instance and class slots they initialize.
519       (loop for (key value) on initargs by #'cddr
520             as kind = (if (constantp value) 'constant 'param)
521             as locations = (initarg-locations key)
522             do (loop for (location . type) in locations
523                      do (if (consp location)
524                             (class-init location kind value type)
525                             (instance-init location kind value type))))
526       ;; Loop over default initargs of the class, recording
527       ;; initializations of slots that have not been initialized
528       ;; above.  Default initargs which are not in the supplied
529       ;; initargs are treated as if they were appended to supplied
530       ;; initargs, that is, their values must be evaluated even
531       ;; if not actually used for initializing a slot.
532       (loop for (key initform initfn) in default-initargs and i from 0
533             unless (member key initkeys :test #'eq) do
534             (let* ((kind (if (constantp initform) 'constant 'var))
535                    (init (if (eq kind 'var) initfn initform)))
536               (ecase kind
537                 (constant
538                  (push key defaulting-initargs)
539                  (push initform defaulting-initargs))
540                 (var
541                  (push key defaulting-initargs)
542                  (push (default-init-var-name i) defaulting-initargs)))
543               (when (eq kind 'var)
544                 (let ((init-var (default-init-var-name i)))
545                   (setq init init-var)
546                   (push (cons init-var initfn) default-inits)))
547               (loop for (location . type) in (initarg-locations key)
548                     do (if (consp location)
549                            (class-init location kind init type)
550                            (instance-init location kind init type)))))
551       ;; Loop over all slots of the class, filling in the rest from
552       ;; slot initforms.
553       (loop for slotd in (class-slots class)
554             as location = (slot-definition-location slotd)
555             as type = (slot-definition-type slotd)
556             as allocation = (slot-definition-allocation slotd)
557             as initfn = (slot-definition-initfunction slotd)
558             as initform = (slot-definition-initform slotd) do
559               (unless (or (eq allocation :class)
560                           (null initfn)
561                           (initializedp location))
562                 (if (constantp initform)
563                     (instance-init location 'initform initform type)
564                     (instance-init location 'initform/initfn initfn type))))
565       ;; Generate the forms for initializing instance and class slots.
566       (let ((instance-init-forms
567              (loop for slot-entry across slot-vector and i from 0
568                    as (kind value type) = slot-entry collect
569                      (ecase kind
570                        ((nil)
571                         (unless before-method-p
572                           `(setf (clos-slots-ref .slots. ,i) +slot-unbound+)))
573                        ((param var)
574                         `(setf (clos-slots-ref .slots. ,i)
575                                (with-type-checked (,type ,safe-p)
576                                    ,value)))
577                        (initfn
578                         `(setf (clos-slots-ref .slots. ,i)
579                                (with-type-checked (,type ,safe-p)
580                                  (funcall ,value))))
581                        (initform/initfn
582                         (if before-method-p
583                             `(when (eq (clos-slots-ref .slots. ,i)
584                                        +slot-unbound+)
585                                (setf (clos-slots-ref .slots. ,i)
586                                      (with-type-checked (,type ,safe-p)
587                                        (funcall ,value))))
588                             `(setf (clos-slots-ref .slots. ,i)
589                                    (with-type-checked (,type ,safe-p)
590                                      (funcall ,value)))))
591                        (initform
592                         (if before-method-p
593                             `(when (eq (clos-slots-ref .slots. ,i)
594                                        +slot-unbound+)
595                                (setf (clos-slots-ref .slots. ,i)
596                                      (with-type-checked (,type ,safe-p)
597                                        ',(constant-form-value value))))
598                             `(setf (clos-slots-ref .slots. ,i)
599                                    (with-type-checked (,type ,safe-p)
600                                      ',(constant-form-value value)))))
601                        (constant
602                         `(setf (clos-slots-ref .slots. ,i)
603                                (with-type-checked (,type ,safe-p)
604                                  ',(constant-form-value value))))))))
605         ;; we are not allowed to modify QUOTEd locations, so we can't
606         ;; generate code like (setf (cdr ',location) arg).  Instead,
607         ;; we have to do (setf (cdr .L0.) arg) and arrange for .L0. to
608         ;; be bound to the location.
609         (multiple-value-bind (names locations class-init-forms)
610             (loop for (location kind value type) in class-inits
611                   for i upfrom 0
612                   for name = (location-var-name i)
613                   collect name into names
614                   collect location into locations
615                   collect `(setf (cdr ,name)
616                                  (with-type-checked (,type ,safe-p)
617                                    ,(case kind
618                                           (constant `',(constant-form-value value))
619                                           ((param var) `,value)
620                                           (initfn `(funcall ,value)))))
621                   into class-init-forms
622                   finally (return (values names locations class-init-forms)))
623           (multiple-value-bind (vars bindings)
624               (loop for (var . initfn) in (nreverse default-inits)
625                     collect var into vars
626                     collect `(,var (funcall ,initfn)) into bindings
627                     finally (return (values vars bindings)))
628             (values locations names
629                     bindings vars
630                     (nreverse defaulting-initargs)
631                     `(,@(delete nil instance-init-forms)
632                       ,@class-init-forms))))))))
633
634 ;;; Return an alist of lists (KEY (LOCATION . TYPE-SPECIFIER) ...)
635 ;;; telling, for each key in INITKEYS, which locations the initarg
636 ;;; initializes and the associated type with the location.  CLASS is
637 ;;; the class of the instance being initialized.
638 (defun compute-initarg-locations (class initkeys)
639   (loop with slots = (class-slots class)
640         for key in initkeys collect
641           (loop for slot in slots
642                 if (memq key (slot-definition-initargs slot))
643                   collect (cons (slot-definition-location slot)
644                                 (slot-definition-type slot))
645                           into locations
646                 else
647                   collect slot into remaining-slots
648                 finally
649                   (setq slots remaining-slots)
650                   (return (cons key locations)))))
651
652 \f
653 ;;; *******************************
654 ;;; External Entry Points  ********
655 ;;; *******************************
656
657 (defun update-ctors (reason &key class name generic-function method)
658   (labels ((reset (class &optional ri-cache-p (ctorsp t))
659              (when ctorsp
660                (dolist (ctor (plist-value class 'ctors))
661                  (install-initial-constructor ctor)))
662              (when ri-cache-p
663                (setf (plist-value class 'ri-initargs) ()))
664              (dolist (subclass (class-direct-subclasses class))
665                (reset subclass ri-cache-p ctorsp))))
666     (ecase reason
667       ;; CLASS must have been specified.
668       (finalize-inheritance
669        (reset class t))
670       ;; NAME must have been specified.
671       (setf-find-class
672        (loop for ctor in *all-ctors*
673              when (eq (ctor-class-name ctor) name) do
674              (when (ctor-class ctor)
675                (reset (ctor-class ctor)))
676              (loop-finish)))
677       ;; GENERIC-FUNCTION and METHOD must have been specified.
678       ((add-method remove-method)
679        (flet ((class-of-1st-method-param (method)
680                 (type-class (first (method-specializers method)))))
681          (case (generic-function-name generic-function)
682            ((make-instance allocate-instance
683              initialize-instance shared-initialize)
684             (reset (class-of-1st-method-param method) t t))
685            ((reinitialize-instance)
686             (reset (class-of-1st-method-param method) t nil))
687            (t (when (or (eq (generic-function-name generic-function)
688                             'slot-boundp-using-class)
689                         (equal (generic-function-name generic-function)
690                                '(setf slot-value-using-class)))
691                 ;; this looks awfully expensive, but given that one
692                 ;; can specialize on the SLOTD argument, nothing is
693                 ;; safe.  -- CSR, 2004-07-12
694                 (reset (find-class 'standard-object))))))))))
695
696 (defun precompile-ctors ()
697   (dolist (ctor *all-ctors*)
698     (when (null (ctor-class ctor))
699       (let ((class (find-class (ctor-class-name ctor) nil)))
700         (when (and class (class-finalized-p class))
701           (install-optimized-constructor ctor))))))
702
703 (defun check-ri-initargs (instance initargs)
704   (let* ((class (class-of instance))
705          (keys (plist-keys initargs))
706          (cached (assoc keys (plist-value class 'ri-initargs)
707                         :test #'equal))
708          (invalid-keys
709           (if (consp cached)
710               (cdr cached)
711               (let ((invalid
712                      ;; FIXME: give CHECK-INITARGS-1 and friends a
713                      ;; more mnemonic name and (possibly) a nicer,
714                      ;; more orthogonal interface.
715                      (check-initargs-1
716                       class initargs
717                       (list (list* 'reinitialize-instance instance initargs)
718                             (list* 'shared-initialize instance nil initargs))
719                       t nil)))
720                 (setf (plist-value class 'ri-initargs)
721                       (acons keys invalid cached))
722                 invalid))))
723     (when invalid-keys
724       (error 'initarg-error :class class :initargs invalid-keys))))
725
726 ;;; end of ctor.lisp