Remove some test noise. A drop in the ocean unfortunately.
[sbcl.git] / src / pcl / ctor.lisp
blob4e878e2ab5e6c532db60a2ce951ebd8ba3aebc82
1 ;;;; This file contains the optimization machinery for make-instance.
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
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.
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.
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.
59 (in-package "SB-PCL")
61 ;;; ******************
62 ;;; Utilities *******
63 ;;; ******************
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)))
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))
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)))
87 (defun constant-class-arg-p (form)
88 (and (constantp form)
89 (let ((constant (constant-form-value form)))
90 (or (and (symbolp constant)
91 (not (null (symbol-package constant))))
92 (classp form)))))
94 (defun constant-symbol-p (form)
95 (and (constantp form)
96 (let ((constant (constant-form-value form)))
97 (and (symbolp constant)
98 (not (null (symbol-package constant)))))))
100 ;;; Somewhat akin to DEFAULT-INITARGS, but just collecting the defaulted
101 ;;; initargs for the call.
102 (defun ctor-default-initkeys (supplied-initargs class-default-initargs)
103 (loop for (key) in class-default-initargs
104 when (eq (getf supplied-initargs key '.not-there.) '.not-there.)
105 collect key))
107 ;;; Like DEFAULT-INITARGS, but return a list that can be spliced into source,
108 ;;; instead of a list with values already evaluated.
109 (defun ctor-default-initargs (supplied-initargs class-default-initargs)
110 (loop for (key form fun) in class-default-initargs
111 when (eq (getf supplied-initargs key '.not-there.) '.not-there.)
112 append (list key (if (constantp form) form `(funcall ,fun)))
113 into default-initargs
114 finally
115 (return (append supplied-initargs default-initargs))))
117 ;;; *****************
118 ;;; CTORS *********
119 ;;; *****************
121 ;;; Ctors are funcallable instances whose initial function is a
122 ;;; function computing an optimized constructor function when called.
123 ;;; When the optimized function is computed, the function of the
124 ;;; funcallable instance is set to it.
126 (!defstruct-with-alternate-metaclass ctor
127 :slot-names (function-name class-or-name class initargs state safe-p)
128 :boa-constructor %make-ctor
129 :superclass-name function
130 :metaclass-name static-classoid
131 :metaclass-constructor make-static-classoid
132 :dd-type funcallable-structure
133 :runtime-type-checks-p nil)
135 ;;; List of all defined ctors.
136 (defvar *all-ctors* ())
138 (defun make-ctor-parameter-list (ctor)
139 (plist-values (ctor-initargs ctor) :test (complement #'constantp)))
141 ;;; Reset CTOR to use a default function that will compute an
142 ;;; optimized constructor function when called.
143 (defun install-initial-constructor (ctor &key force-p)
144 (when (or force-p (ctor-class ctor))
145 (setf (ctor-class ctor) nil
146 (ctor-state ctor) 'initial)
147 (setf (funcallable-instance-fun ctor)
148 #'(lambda (&rest args)
149 (install-optimized-constructor ctor)
150 (apply ctor args)))
151 (setf (%funcallable-instance-info ctor 1)
152 (ctor-function-name ctor))))
154 (defun make-ctor-function-name (class-name initargs safe-code-p)
155 (labels ((arg-name (x)
156 (typecase x
157 ;; this list of types might look arbitrary but it is
158 ;; exactly the set of types descended into by EQUAL,
159 ;; which is the predicate used by globaldb to test for
160 ;; name equality.
161 (list (gensym "LIST-INITARG-"))
162 (string (gensym "STRING-INITARG-"))
163 (bit-vector (gensym "BIT-VECTOR-INITARG-"))
164 (pathname (gensym "PATHNAME-INITARG-"))
165 (t x)))
166 (munge (list)
167 (let ((*gensym-counter* 0))
168 (mapcar #'arg-name list))))
169 (list* 'ctor class-name safe-code-p (munge initargs))))
171 ;;; Keep this a separate function for testing.
172 (defun ensure-ctor (function-name class-name initargs safe-code-p)
173 (with-world-lock ()
174 (if (fboundp function-name)
175 (the ctor (fdefinition function-name))
176 (make-ctor function-name class-name initargs safe-code-p))))
178 ;;; Keep this a separate function for testing.
179 (defun make-ctor (function-name class-name initargs safe-p)
180 (without-package-locks ; for (setf symbol-function)
181 (let ((ctor (%make-ctor function-name class-name nil initargs nil safe-p)))
182 (install-initial-constructor ctor :force-p t)
183 (push ctor *all-ctors*)
184 (setf (fdefinition function-name) ctor)
185 ctor)))
187 ;;; *****************
188 ;;; Inline CTOR cache
189 ;;; *****************
191 ;;; The cache starts out as a list of CTORs, sorted with the most recently
192 ;;; used CTORs near the head. If it expands too much, we switch to a vector
193 ;;; with a simple hashing scheme.
195 ;;; Find CTOR for KEY (which is a class or class name) in a list. If the CTOR
196 ;;; is in the list but not one of the 4 first ones, return a new list with the
197 ;;; found CTOR at the head. Thread-safe: the new list shares structure with
198 ;;; the old, but is not desctructively modified. Returning the old list for
199 ;;; hits close to the head reduces ping-ponging with multiple threads seeking
200 ;;; the same list.
201 (defun find-ctor (key list)
202 (labels ((walk (tail from-head depth)
203 (declare (fixnum depth))
204 (if tail
205 (let ((ctor (car tail)))
206 (if (eq (ctor-class-or-name ctor) key)
207 (if (> depth 3)
208 (values ctor
209 (nconc (list ctor) (nreverse from-head) (cdr tail)))
210 (values ctor
211 list))
212 (walk (cdr tail)
213 (cons ctor from-head)
214 (logand #xf (1+ depth)))))
215 (values nil list))))
216 (walk list nil 0)))
218 (declaim (inline sxhash-symbol-or-class))
219 (defun sxhash-symbol-or-class (x)
220 (cond ((symbolp x) (sxhash x))
221 ((std-instance-p x) (std-instance-hash x))
222 ((fsc-instance-p x) (fsc-instance-hash x))
224 (bug "Something strange where symbol or class expected."))))
226 ;;; Max number of CTORs kept in an inline list cache. Once this is
227 ;;; exceeded we switch to a table.
228 (defconstant +ctor-list-max-size+ 12)
229 ;;; Max table size for CTOR cache. If the table fills up at this size
230 ;;; we keep the same size and drop 50% of the old entries.
231 (defconstant +ctor-table-max-size+ (expt 2 8))
232 ;;; Even if there is space in the cache, if we cannot fit a new entry
233 ;;; with max this number of collisions we expand the table (if possible)
234 ;;; and rehash.
235 (defconstant +ctor-table-max-probe-depth+ 5)
237 (defun make-ctor-table (size)
238 (declare (index size))
239 (let ((real-size (power-of-two-ceiling size)))
240 (if (< real-size +ctor-table-max-size+)
241 (values (make-array real-size :initial-element nil) nil)
242 (values (make-array +ctor-table-max-size+ :initial-element nil) t))))
244 (declaim (inline mix-ctor-hash))
245 (defun mix-ctor-hash (hash base)
246 (logand most-positive-fixnum (+ hash base 1)))
248 (defun put-ctor (ctor table)
249 (cond ((try-put-ctor ctor table)
250 (values ctor table))
252 (expand-ctor-table ctor table))))
254 ;;; Thread-safe: if two threads write to the same index in parallel, the other
255 ;;; result is just lost. This is not an issue as the CTORs are used as their
256 ;;; own keys. If both were EQ, we're good. If non-EQ, the next time the other
257 ;;; one is needed we just cache it again -- hopefully not getting stomped on
258 ;;; that time.
259 (defun try-put-ctor (ctor table)
260 (declare (simple-vector table) (optimize speed))
261 (let* ((class (ctor-class-or-name ctor))
262 (base (sxhash-symbol-or-class class))
263 (hash base)
264 (mask (1- (length table))))
265 (declare (fixnum base hash mask))
266 (loop repeat +ctor-table-max-probe-depth+
267 do (let* ((index (logand mask hash))
268 (old (aref table index)))
269 (cond ((and old (neq class (ctor-class-or-name old)))
270 (setf hash (mix-ctor-hash hash base)))
272 (setf (aref table index) ctor)
273 (return-from try-put-ctor t)))))
274 ;; Didn't fit, must expand
275 nil))
277 (defun get-ctor (class table)
278 (declare (simple-vector table) (optimize speed))
279 (let* ((base (sxhash-symbol-or-class class))
280 (hash base)
281 (mask (1- (length table))))
282 (declare (fixnum base hash mask))
283 (loop repeat +ctor-table-max-probe-depth+
284 do (let* ((index (logand mask hash))
285 (old (aref table index)))
286 (if (and old (eq class (ctor-class-or-name old)))
287 (return-from get-ctor old)
288 (setf hash (mix-ctor-hash hash base)))))
289 ;; Nothing.
290 nil))
292 ;;; Thread safe: the old table is read, but if another thread mutates
293 ;;; it while we're reading we still get a sane result -- either the old
294 ;;; or the new entry. The new table is locally allocated, so that's ok
295 ;;; too.
296 (defun expand-ctor-table (ctor old)
297 (declare (simple-vector old))
298 (let* ((old-size (length old))
299 (new-size (* 2 old-size))
300 (drop-random-entries nil))
301 (tagbody
302 :again
303 (multiple-value-bind (new max-size-p) (make-ctor-table new-size)
304 (let ((action (if drop-random-entries
305 ;; Same logic as in method caches -- see comment
306 ;; there.
307 (randomly-punting-lambda (old-ctor)
308 (try-put-ctor old-ctor new))
309 (lambda (old-ctor)
310 (unless (try-put-ctor old-ctor new)
311 (if max-size-p
312 (setf drop-random-entries t)
313 (setf new-size (* 2 new-size)))
314 (go :again))))))
315 (aver (try-put-ctor ctor new))
316 (dotimes (i old-size)
317 (let ((old-ctor (aref old i)))
318 (when old-ctor
319 (funcall action old-ctor))))
320 (return-from expand-ctor-table (values ctor new)))))))
322 (defun ctor-list-to-table (list)
323 (let ((table (make-ctor-table (length list))))
324 (dolist (ctor list)
325 (setf table (nth-value 1 (put-ctor ctor table))))
326 table))
328 (defun ensure-cached-ctor (class-name store initargs safe-code-p)
329 (flet ((maybe-ctor-for-caching ()
330 (if (typep class-name '(or symbol class))
331 (let ((name (make-ctor-function-name class-name initargs safe-code-p)))
332 (ensure-ctor name class-name initargs safe-code-p))
333 ;; Invalid first argument: let MAKE-INSTANCE worry about it.
334 (return-from ensure-cached-ctor
335 (values (lambda (&rest ctor-parameters)
336 (let (mi-initargs)
337 (doplist (key value) initargs
338 (push key mi-initargs)
339 (push (if (constantp value)
340 value
341 (pop ctor-parameters))
342 mi-initargs))
343 (apply #'make-instance class-name (nreverse mi-initargs))))
344 store)))))
345 (if (listp store)
346 (multiple-value-bind (ctor list) (find-ctor class-name store)
347 (if ctor
348 (values ctor list)
349 (let ((ctor (maybe-ctor-for-caching)))
350 (if (< (length list) +ctor-list-max-size+)
351 (values ctor (cons ctor list))
352 (values ctor (ctor-list-to-table list))))))
353 (let ((ctor (get-ctor class-name store)))
354 (if ctor
355 (values ctor store)
356 (put-ctor (maybe-ctor-for-caching) store))))))
358 ;;; ***********************************************
359 ;;; Compile-Time Expansion of MAKE-INSTANCE *******
360 ;;; ***********************************************
362 (defvar *compiling-optimized-constructor* nil)
364 (define-compiler-macro make-instance (&whole form &rest args &environment env)
365 (declare (ignore args))
366 ;; Compiling an optimized constructor for a non-standard class means
367 ;; compiling a lambda with (MAKE-INSTANCE #<SOME-CLASS X> ...) in it
368 ;; -- need to make sure we don't recurse there.
369 (or (unless *compiling-optimized-constructor*
370 (make-instance->constructor-call form (safe-code-p env)))
371 form))
373 (defun make-instance->constructor-call (form safe-code-p)
374 (destructuring-bind (class-arg &rest args) (cdr form)
375 (flet (;;
376 ;; Return the name of parameter number I of a constructor
377 ;; function.
378 (parameter-name (i)
379 (format-symbol *pcl-package* ".P~D." i))
380 ;; Check if CLASS-ARG is a constant symbol. Give up if
381 ;; not.
382 (constant-class-p ()
383 (and class-arg (constant-class-arg-p class-arg)))
384 ;; Check if ARGS are suitable for an optimized constructor.
385 ;; Return NIL from the outer function if not.
386 (check-args ()
387 (loop for (key . more) on args by #'cddr do
388 (when (or (null more)
389 (not (constant-symbol-p key))
390 (eq :allow-other-keys (constant-form-value key)))
391 (return-from make-instance->constructor-call nil)))))
392 (check-args)
393 ;; Collect a plist of initargs and constant values/parameter names
394 ;; in INITARGS. Collect non-constant initialization forms in
395 ;; VALUE-FORMS.
396 (multiple-value-bind (initargs value-forms)
397 (loop for (key value) on args by #'cddr and i from 0
398 collect (constant-form-value key) into initargs
399 if (constantp value)
400 collect value into initargs
401 else
402 collect (parameter-name i) into initargs
403 and collect value into value-forms
404 finally
405 (return (values initargs value-forms)))
406 (if (constant-class-p)
407 (let* ((class-or-name (constant-form-value class-arg))
408 (function-name (make-ctor-function-name class-or-name initargs
409 safe-code-p)))
410 ;; Prevent compiler warnings for calling the ctor.
411 (proclaim-as-fun-name function-name)
412 (note-name-defined function-name :function)
413 (when (eq (info :function :where-from function-name) :assumed)
414 (setf (info :function :where-from function-name) :defined)
415 (when (info :function :assumed-type function-name)
416 (setf (info :function :assumed-type function-name) nil)))
417 ;; Return code constructing a ctor at load time, which,
418 ;; when called, will set its funcallable instance
419 ;; function to an optimized constructor function.
420 `(locally
421 (declare (disable-package-locks ,function-name))
422 (let ((.x. (load-time-value
423 (ensure-ctor ',function-name ',class-or-name ',initargs
424 ',safe-code-p))))
425 (declare (ignore .x.))
426 ;; ??? check if this is worth it.
427 (declare
428 (ftype (or (function ,(make-list (length value-forms)
429 :initial-element t)
431 (function (&rest t) t))
432 ,function-name))
433 (funcall (function ,function-name) ,@value-forms))))
434 (when (and class-arg (not (constantp class-arg)))
435 ;; Build an inline cache: a CONS, with the actual cache
436 ;; in the CDR.
437 `(locally (declare (disable-package-locks .cache. .class-arg. .store. .fun.
438 make-instance))
439 (let* ((.cache. (load-time-value (cons 'ctor-cache nil)))
440 (.store. (cdr .cache.))
441 (.class-arg. ,class-arg))
442 (multiple-value-bind (.fun. .new-store.)
443 (ensure-cached-ctor .class-arg. .store. ',initargs ',safe-code-p)
444 ;; Thread safe: if multiple threads hit this in
445 ;; parallel, the update from the other one is
446 ;; just lost -- no harm done, except for the need
447 ;; to redo the work next time.
448 (unless (eq .store. .new-store.)
449 (setf (cdr .cache.) .new-store.))
450 (funcall (truly-the function .fun.) ,@value-forms))))))))))
452 ;;; **************************************************
453 ;;; Load-Time Constructor Function Generation *******
454 ;;; **************************************************
456 ;;; The system-supplied primary INITIALIZE-INSTANCE and
457 ;;; SHARED-INITIALIZE methods. One cannot initialize these variables
458 ;;; to the right values here because said functions don't exist yet
459 ;;; when this file is first loaded.
460 (defvar *the-system-ii-method* nil)
461 (defvar *the-system-si-method* nil)
463 (defun install-optimized-constructor (ctor)
464 (with-world-lock ()
465 (let* ((class-or-name (ctor-class-or-name ctor))
466 (class (ensure-class-finalized
467 (if (symbolp class-or-name)
468 (find-class class-or-name)
469 class-or-name))))
470 ;; We can have a class with an invalid layout here. Such a class
471 ;; cannot have a LAYOUT-INVALID of (:FLUSH ...) or (:OBSOLETE
472 ;; ...), because part of the deal is that those only happen from
473 ;; FORCE-CACHE-FLUSHES, which create a new valid wrapper for the
474 ;; class. An invalid layout of T needs to be flushed, however.
475 (when (eq (layout-invalid (class-wrapper class)) t)
476 (%force-cache-flushes class))
477 (setf (ctor-class ctor) class)
478 (pushnew ctor (plist-value class 'ctors) :test #'eq)
479 (multiple-value-bind (form locations names optimizedp)
480 (constructor-function-form ctor)
481 (setf (funcallable-instance-fun ctor)
482 (apply
483 (let ((*compiling-optimized-constructor* t))
484 (handler-bind ((compiler-note #'muffle-warning))
485 (compile nil `(lambda ,names ,form))))
486 locations)
487 (ctor-state ctor) (if optimizedp 'optimized 'fallback))))))
489 (defun constructor-function-form (ctor)
490 (let* ((class (ctor-class ctor))
491 (proto (class-prototype class))
492 (make-instance-methods
493 (compute-applicable-methods #'make-instance (list class)))
494 (allocate-instance-methods
495 (compute-applicable-methods #'allocate-instance (list class)))
496 ;; I stared at this in confusion for a while, thinking
497 ;; carefully about the possibility of the class prototype not
498 ;; being of sufficient discrimiating power, given the
499 ;; possibility of EQL-specialized methods on
500 ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE. However, given
501 ;; that this is a constructor optimization, the user doesn't
502 ;; yet have the instance to create a method with such an EQL
503 ;; specializer.
505 ;; There remains the (theoretical) possibility of someone
506 ;; coming along with code of the form
508 ;; (defmethod initialize-instance :before ((o foo) ...)
509 ;; (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
511 ;; but probably we can afford not to worry about this too
512 ;; much for now. -- CSR, 2004-07-12
513 (ii-methods
514 (compute-applicable-methods #'initialize-instance (list proto)))
515 (si-methods
516 (compute-applicable-methods #'shared-initialize (list proto t)))
517 (setf-svuc-slots
518 (loop for slot in (class-slots class)
519 when (cdr (compute-applicable-methods
520 #'(setf slot-value-using-class)
521 (list nil class proto slot)))
522 collect slot))
523 (sbuc-slots
524 (loop for slot in (class-slots class)
525 when (cdr (compute-applicable-methods
526 #'slot-boundp-using-class
527 (list class proto slot)))
528 collect slot)))
529 ;; Cannot initialize these variables earlier because the generic
530 ;; functions don't exist when PCL is built.
531 (when (null *the-system-si-method*)
532 (setq *the-system-si-method*
533 (find-method #'shared-initialize
534 () (list *the-class-slot-object* *the-class-t*)))
535 (setq *the-system-ii-method*
536 (find-method #'initialize-instance
537 () (list *the-class-slot-object*))))
538 ;; Note that when there are user-defined applicable methods on
539 ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
540 ;; together with the system-defined ones in what
541 ;; COMPUTE-APPLICABLE-METHODS returns.
542 (let ((maybe-invalid-initargs
543 (check-initargs-1
544 class
545 (append
546 (ctor-default-initkeys
547 (ctor-initargs ctor) (class-default-initargs class))
548 (plist-keys (ctor-initargs ctor)))
549 (append ii-methods si-methods) nil nil))
550 (custom-make-instance
551 (not (null (cdr make-instance-methods)))))
552 (if (and (not (structure-class-p class))
553 (not (condition-class-p class))
554 (not custom-make-instance)
555 (null (cdr allocate-instance-methods))
556 (every (lambda (x)
557 (member (slot-definition-allocation x)
558 '(:instance :class)))
559 (class-slots class))
560 (not maybe-invalid-initargs)
561 (not (hairy-around-or-nonstandard-primary-method-p
562 ii-methods *the-system-ii-method*))
563 (not (around-or-nonstandard-primary-method-p
564 si-methods *the-system-si-method*)))
565 (optimizing-generator ctor ii-methods si-methods setf-svuc-slots sbuc-slots)
566 (fallback-generator ctor ii-methods si-methods
567 (or maybe-invalid-initargs custom-make-instance))))))
569 (defun around-or-nonstandard-primary-method-p
570 (methods &optional standard-method)
571 (loop with primary-checked-p = nil
572 for method in methods
573 as qualifiers = (if (consp method)
574 (early-method-qualifiers method)
575 (safe-method-qualifiers method))
576 when (or (eq :around (car qualifiers))
577 (and (null qualifiers)
578 (not primary-checked-p)
579 (not (null standard-method))
580 (not (eq standard-method method))))
581 return t
582 when (null qualifiers) do
583 (setq primary-checked-p t)))
585 (defun hairy-around-or-nonstandard-primary-method-p
586 (methods &optional standard-method)
587 (loop with primary-checked-p = nil
588 for method in methods
589 as qualifiers = (if (consp method)
590 (early-method-qualifiers method)
591 (safe-method-qualifiers method))
592 when (or (and (eq :around (car qualifiers))
593 (not (simple-next-method-call-p method)))
594 (and (null qualifiers)
595 (not primary-checked-p)
596 (not (null standard-method))
597 (not (eq standard-method method))))
598 return t
599 when (null qualifiers) do
600 (setq primary-checked-p t)))
602 (defun fallback-generator (ctor ii-methods si-methods use-make-instance)
603 (declare (ignore ii-methods si-methods))
604 (let ((class (ctor-class ctor))
605 (lambda-list (make-ctor-parameter-list ctor))
606 (initargs (ctor-initargs ctor)))
607 (if use-make-instance
608 `(lambda ,lambda-list
609 (declare #.*optimize-speed*)
610 ;; The CTOR MAKE-INSTANCE optimization checks for
611 ;; *COMPILING-OPTIMIZED-CONSTRUCTOR* which is bound around
612 ;; compilation of the constructor, hence avoiding the
613 ;; possibility of endless recursion.
614 (make-instance ,class ,@(quote-plist-keys initargs)))
615 (let ((defaults (class-default-initargs class)))
616 (when defaults
617 (setf initargs (ctor-default-initargs initargs defaults)))
618 `(lambda ,lambda-list
619 (declare #.*optimize-speed*)
620 (fast-make-instance ,class ,@(quote-plist-keys initargs)))))))
622 ;;; Not as good as the real optimizing generator, but faster than going
623 ;;; via MAKE-INSTANCE: 1 GF call less, and no need to check initargs.
624 (defun fast-make-instance (class &rest initargs)
625 (declare #.*optimize-speed*)
626 (declare (dynamic-extent initargs))
627 (let ((.instance. (apply #'allocate-instance class initargs)))
628 (apply #'initialize-instance .instance. initargs)
629 .instance.))
631 (defun optimizing-generator
632 (ctor ii-methods si-methods setf-svuc-slots sbuc-slots)
633 (multiple-value-bind (locations names body early-unbound-markers-p)
634 (fake-initialization-emf ctor ii-methods si-methods
635 setf-svuc-slots sbuc-slots)
636 (let ((wrapper (class-wrapper (ctor-class ctor))))
637 (values
638 `(lambda ,(make-ctor-parameter-list ctor)
639 (declare #.*optimize-speed*)
640 (block nil
641 (when (layout-invalid ,wrapper)
642 (install-initial-constructor ,ctor)
643 (return (funcall ,ctor ,@(make-ctor-parameter-list ctor))))
644 ,(wrap-in-allocate-forms ctor body early-unbound-markers-p)))
645 locations
646 names
647 t))))
649 ;;; Return a form wrapped around BODY that allocates an instance constructed
650 ;;; by CTOR. EARLY-UNBOUND-MARKERS-P means slots may be accessed before we
651 ;;; have explicitly initialized them, requiring all slots to start as
652 ;;; +SLOT-UNBOUND+. The resulting form binds the local variables .INSTANCE. to
653 ;;; the instance, and .SLOTS. to the instance's slot vector around BODY.
654 (defun wrap-in-allocate-forms (ctor body early-unbound-markers-p)
655 (let* ((class (ctor-class ctor))
656 (wrapper (class-wrapper class))
657 (allocation-function (raw-instance-allocator class))
658 (slots-fetcher (slots-fetcher class)))
659 (if (eq allocation-function 'allocate-standard-instance)
660 `(let ((.instance. (%make-standard-instance nil
661 (get-instance-hash-code)))
662 (.slots. (make-array
663 ,(layout-length wrapper)
664 ,@(when early-unbound-markers-p
665 '(:initial-element +slot-unbound+)))))
666 (setf (std-instance-wrapper .instance.) ,wrapper)
667 (setf (std-instance-slots .instance.) .slots.)
668 ,body
669 .instance.)
670 `(let* ((.instance. (,allocation-function ,wrapper))
671 (.slots. (,slots-fetcher .instance.)))
672 (declare (ignorable .slots.))
673 ,body
674 .instance.))))
676 ;;; Return a form for invoking METHOD with arguments from ARGS. As
677 ;;; can be seen in METHOD-FUNCTION-FROM-FAST-FUNCTION, method
678 ;;; functions look like (LAMBDA (ARGS NEXT-METHODS) ...). We could
679 ;;; call fast method functions directly here, but benchmarks show that
680 ;;; there's no speed to gain, so lets avoid the hair here.
681 (defmacro invoke-method (method args &optional next-methods)
682 `(funcall ,(the function (method-function method)) ,args ,next-methods))
684 ;;; Return a form that is sort of an effective method comprising all
685 ;;; calls to INITIALIZE-INSTANCE and SHARED-INITIALIZE that would
686 ;;; normally have taken place when calling MAKE-INSTANCE.
687 (defun fake-initialization-emf
688 (ctor ii-methods si-methods setf-svuc-slots sbuc-slots)
689 (multiple-value-bind (ii-around ii-before ii-primary ii-after)
690 (standard-sort-methods ii-methods)
691 (declare (ignore ii-primary))
692 (multiple-value-bind (si-around si-before si-primary si-after)
693 (standard-sort-methods si-methods)
694 (declare (ignore si-primary))
695 (aver (null si-around))
696 (let ((initargs (ctor-initargs ctor))
697 ;; :BEFORE and :AROUND initialization methods, and SETF SVUC and
698 ;; SBUC methods can cause slots to be accessed before the we have
699 ;; touched them here, which requires the instance-vector to be
700 ;; initialized with +SLOT-UNBOUND+ to start with.
701 (early-unbound-markers-p (or ii-before si-before ii-around
702 setf-svuc-slots sbuc-slots)))
703 (multiple-value-bind
704 (locations names bindings vars defaulting-initargs body)
705 (slot-init-forms ctor
706 early-unbound-markers-p
707 setf-svuc-slots sbuc-slots)
708 (values
709 locations
710 names
711 `(let ,bindings
712 (declare (ignorable ,@vars))
713 (flet ((initialize-it (.ii-args. .next-methods.)
714 ;; This has all the :BEFORE and :AFTER methods,
715 ;; and BODY does what primary SI method would do.
716 (declare (ignore .next-methods.))
717 (let* ((.instance. (car .ii-args.))
718 ,@(when (or si-before si-after)
719 `((.si-args.
720 (list* .instance. t (cdr .ii-args.))))))
721 ,@(loop for method in ii-before
722 collect `(invoke-method ,method .ii-args.))
723 ,@(loop for method in si-before
724 collect `(invoke-method ,method .si-args.))
725 ,@body
726 ,@(loop for method in si-after
727 collect `(invoke-method ,method .si-args.))
728 ,@(loop for method in ii-after
729 collect `(invoke-method ,method .ii-args.))
730 .instance.)))
731 (declare (dynamic-extent #'initialize-it))
732 (let ((.ii-args.
733 ,@(if (or ii-before ii-after ii-around si-before si-after)
734 `((list .instance. ,@(quote-plist-keys initargs)
735 ,@defaulting-initargs))
736 `((list .instance.)))))
737 ,(if ii-around
738 ;; If there are :AROUND methods, call them first -- they get
739 ;; the normal chaining, with #'INITIALIZE-IT standing in for
740 ;; the rest.
741 `(let ((.next-methods.
742 (list ,@(cdr ii-around) #'initialize-it)))
743 (declare (dynamic-extent .next-methods.))
744 (invoke-method ,(car ii-around) .ii-args. .next-methods.))
745 ;; The simple case.
746 `(initialize-it .ii-args. nil)))))
747 early-unbound-markers-p))))))
749 ;;; Return four values from APPLICABLE-METHODS: around methods, before
750 ;;; methods, the applicable primary method, and applicable after
751 ;;; methods. Before and after methods are sorted in the order they
752 ;;; must be called.
753 (defun standard-sort-methods (applicable-methods)
754 (loop for method in applicable-methods
755 as qualifiers = (if (consp method)
756 (early-method-qualifiers method)
757 (safe-method-qualifiers method))
758 if (null qualifiers)
759 collect method into primary
760 else if (eq :around (car qualifiers))
761 collect method into around
762 else if (eq :after (car qualifiers))
763 collect method into after
764 else if (eq :before (car qualifiers))
765 collect method into before
766 finally
767 (return (values around before (first primary) (reverse after)))))
769 (defmacro with-type-checked ((type safe-p) &body body)
770 (if safe-p
771 ;; To handle FUNCTION types reasonable, we use SAFETY 3 and
772 ;; THE instead of e.g. CHECK-TYPE.
773 `(locally
774 (declare (optimize (safety 3)))
775 (the ,type (progn ,@body)))
776 `(progn ,@body)))
778 ;;; Return as multiple values bindings for default initialization arguments,
779 ;;; variable names, defaulting initargs and a body for initializing instance
780 ;;; and class slots of an object costructed by CTOR. The variable .SLOTS. is
781 ;;; assumed to bound to the instance's slot vector. EARLY-UNBOUND-MARKERS-P
782 ;;; means other code will initialize instance slots to +SLOT-UNBOUND+, and we
783 ;;; have to check if something has already set slots before we initialize
784 ;;; them.
785 (defun slot-init-forms (ctor early-unbound-markers-p setf-svuc-slots sbuc-slots)
786 (let* ((class (ctor-class ctor))
787 (initargs (ctor-initargs ctor))
788 (initkeys (plist-keys initargs))
789 (safe-p (ctor-safe-p ctor))
790 (wrapper (class-wrapper class))
791 (slot-vector
792 (make-array (layout-length wrapper) :initial-element nil))
793 (class-inits ())
794 (default-inits ())
795 (defaulting-initargs ())
796 (default-initargs (class-default-initargs class))
797 (initarg-locations
798 (compute-initarg-locations
799 class (append initkeys (mapcar #'car default-initargs)))))
800 (labels ((initarg-locations (initarg)
801 (cdr (assoc initarg initarg-locations :test #'eq)))
802 (initializedp (location)
803 (cond
804 ((consp location)
805 (assoc location class-inits :test #'eq))
806 ((integerp location)
807 (not (null (aref slot-vector location))))
808 (t (bug "Weird location in ~S" 'slot-init-forms))))
809 (class-init (location kind val type slotd)
810 (aver (consp location))
811 (unless (initializedp location)
812 (push (list location kind val type slotd) class-inits)))
813 (instance-init (location kind val type slotd)
814 (aver (integerp location))
815 (unless (initializedp location)
816 (setf (aref slot-vector location)
817 (list kind val type slotd))))
818 (default-init-var-name (i)
819 (format-symbol *pcl-package* ".D~D." i))
820 (location-var-name (i)
821 (format-symbol *pcl-package* ".L~D." i)))
822 ;; Loop over supplied initargs and values and record which
823 ;; instance and class slots they initialize.
824 (loop for (key value) on initargs by #'cddr
825 as kind = (if (constantp value) 'constant 'param)
826 as locations = (initarg-locations key)
827 do (loop for (location type slotd) in locations
828 do (if (consp location)
829 (class-init location kind value type slotd)
830 (instance-init location kind value type slotd))))
831 ;; Loop over default initargs of the class, recording
832 ;; initializations of slots that have not been initialized
833 ;; above. Default initargs which are not in the supplied
834 ;; initargs are treated as if they were appended to supplied
835 ;; initargs, that is, their values must be evaluated even
836 ;; if not actually used for initializing a slot.
837 (loop for (key initform initfn) in default-initargs and i from 0
838 unless (member key initkeys :test #'eq)
839 do (let* ((kind (if (constantp initform) 'constant 'var))
840 (init (if (eq kind 'var) initfn initform)))
841 (ecase kind
842 (constant
843 (push (list 'quote key) defaulting-initargs)
844 (push initform defaulting-initargs))
845 (var
846 (push (list 'quote key) defaulting-initargs)
847 (push (default-init-var-name i) defaulting-initargs)))
848 (when (eq kind 'var)
849 (let ((init-var (default-init-var-name i)))
850 (setq init init-var)
851 (push (cons init-var initfn) default-inits)))
852 (loop for (location type slotd) in (initarg-locations key)
853 do (if (consp location)
854 (class-init location kind init type slotd)
855 (instance-init location kind init type slotd)))))
856 ;; Loop over all slots of the class, filling in the rest from
857 ;; slot initforms.
858 (loop for slotd in (class-slots class)
859 as location = (slot-definition-location slotd)
860 as type = (slot-definition-type slotd)
861 as allocation = (slot-definition-allocation slotd)
862 as initfn = (slot-definition-initfunction slotd)
863 as initform = (slot-definition-initform slotd) do
864 (unless (or (eq allocation :class)
865 (null initfn)
866 (initializedp location))
867 (if (constantp initform)
868 (instance-init location 'initform initform type slotd)
869 (instance-init location
870 'initform/initfn initfn type slotd))))
871 ;; Generate the forms for initializing instance and class slots.
872 (let ((instance-init-forms
873 (loop for slot-entry across slot-vector and i from 0
874 as (kind value type slotd) = slot-entry
875 collect
876 (flet ((setf-form (value-form)
877 (if (member slotd setf-svuc-slots :test #'eq)
878 `(setf (slot-value-using-class
879 ,class .instance. ,slotd)
880 ,value-form)
881 `(setf (clos-slots-ref .slots. ,i)
882 (with-type-checked (,type ,safe-p)
883 ,value-form))))
884 (not-boundp-form ()
885 (if (member slotd sbuc-slots :test #'eq)
886 `(not (slot-boundp-using-class
887 ,class .instance. ,slotd))
888 `(eq (clos-slots-ref .slots. ,i)
889 +slot-unbound+))))
890 (ecase kind
891 ((nil)
892 (unless early-unbound-markers-p
893 `(setf (clos-slots-ref .slots. ,i)
894 +slot-unbound+)))
895 ((param var)
896 (setf-form value))
897 (initfn
898 (setf-form `(funcall ,value)))
899 (initform/initfn
900 (if early-unbound-markers-p
901 `(when ,(not-boundp-form)
902 ,(setf-form `(funcall ,value)))
903 (setf-form `(funcall ,value))))
904 (initform
905 (if early-unbound-markers-p
906 `(when ,(not-boundp-form)
907 ,(setf-form `',(constant-form-value value)))
908 (setf-form `',(constant-form-value value))))
909 (constant
910 (setf-form `',(constant-form-value value))))))))
911 ;; we are not allowed to modify QUOTEd locations, so we can't
912 ;; generate code like (setf (cdr ',location) arg). Instead,
913 ;; we have to do (setf (cdr .L0.) arg) and arrange for .L0. to
914 ;; be bound to the location.
915 (multiple-value-bind (names locations class-init-forms)
916 (loop with names
917 with locations
918 with i = -1
919 for (location kind value type slotd) in class-inits
920 for init-form
921 = (case kind
922 (constant `',(constant-form-value value))
923 ((param var) `,value)
924 (initfn `(funcall ,value)))
925 when (member slotd setf-svuc-slots :test #'eq)
926 collect `(setf (slot-value-using-class
927 ,class .instance. ,slotd)
928 ,init-form)
929 into class-init-forms
930 else collect
931 (let ((name (location-var-name (incf i))))
932 (push name names)
933 (push location locations)
934 `(setf (cdr ,name)
935 (with-type-checked (,type ,safe-p)
936 ,init-form)))
937 into class-init-forms
938 finally (return (values (nreverse names)
939 (nreverse locations)
940 class-init-forms)))
941 (multiple-value-bind (vars bindings)
942 (loop for (var . initfn) in (nreverse default-inits)
943 collect var into vars
944 collect `(,var (funcall ,initfn)) into bindings
945 finally (return (values vars bindings)))
946 (values locations names
947 bindings vars
948 (nreverse defaulting-initargs)
949 `(,@(delete nil instance-init-forms)
950 ,@class-init-forms))))))))
952 ;;; Return an alist of lists (KEY (LOCATION . TYPE-SPECIFIER) ...)
953 ;;; telling, for each key in INITKEYS, which locations the initarg
954 ;;; initializes and the associated type with the location. CLASS is
955 ;;; the class of the instance being initialized.
956 (defun compute-initarg-locations (class initkeys)
957 (loop with slots = (class-slots class)
958 for key in initkeys collect
959 (loop for slot in slots
960 if (memq key (slot-definition-initargs slot))
961 collect (list (slot-definition-location slot)
962 (slot-definition-type slot)
963 slot)
964 into locations
965 else
966 collect slot into remaining-slots
967 finally
968 (setq slots remaining-slots)
969 (return (cons key locations)))))
972 ;;; *******************************
973 ;;; External Entry Points ********
974 ;;; *******************************
976 (defun update-ctors (reason &key class name generic-function method)
977 (labels ((reset (class &optional initarg-caches-p (ctorsp t))
978 (when ctorsp
979 (dolist (ctor (plist-value class 'ctors))
980 (install-initial-constructor ctor)))
981 (when initarg-caches-p
982 (dolist (cache '(mi-initargs ri-initargs))
983 (setf (plist-value class cache) ())))
984 (dolist (subclass (class-direct-subclasses class))
985 (reset subclass initarg-caches-p ctorsp))))
986 (ecase reason
987 ;; CLASS must have been specified.
988 (finalize-inheritance
989 (reset class t))
990 ;; NAME must have been specified.
991 (setf-find-class
992 (loop for ctor in *all-ctors*
993 when (eq (ctor-class-or-name ctor) name) do
994 (when (ctor-class ctor)
995 (reset (ctor-class ctor)))
996 (loop-finish)))
997 ;; GENERIC-FUNCTION and METHOD must have been specified.
998 ((add-method remove-method)
999 (flet ((class-of-1st-method-param (method)
1000 (type-class (first (method-specializers method)))))
1001 (case (generic-function-name generic-function)
1002 ((make-instance allocate-instance)
1003 ;; FIXME: I can't see a way of working out which classes a
1004 ;; given metaclass specializer are applicable to short of
1005 ;; iterating and testing with class-of. It would be good
1006 ;; to not invalidate caches of system classes at this
1007 ;; point (where it is not legal to define a method
1008 ;; applicable to them on system functions). -- CSR,
1009 ;; 2010-07-13
1010 (reset (find-class 'standard-object) t t))
1011 ((initialize-instance shared-initialize)
1012 (reset (class-of-1st-method-param method) t t))
1013 ((reinitialize-instance)
1014 (reset (class-of-1st-method-param method) t nil))
1015 (t (when (or (eq (generic-function-name generic-function)
1016 'slot-boundp-using-class)
1017 (equal (generic-function-name generic-function)
1018 '(setf slot-value-using-class)))
1019 ;; this looks awfully expensive, but given that one
1020 ;; can specialize on the SLOTD argument, nothing is
1021 ;; safe. -- CSR, 2004-07-12
1022 (reset (find-class 'standard-object))))))))))
1024 (defun precompile-ctors ()
1025 (dolist (ctor *all-ctors*)
1026 (when (null (ctor-class ctor))
1027 (let ((class (find-class (ctor-class-or-name ctor) nil)))
1028 (when (and class (class-finalized-p class))
1029 (install-optimized-constructor ctor))))))
1031 (defun maybe-call-ctor (class initargs)
1032 (flet ((frob-initargs (ctor)
1033 (do ((ctail (ctor-initargs ctor))
1034 (itail initargs)
1035 (args nil))
1036 ((or (null ctail) (null itail))
1037 (values (nreverse args) (and (null ctail) (null itail))))
1038 (unless (eq (pop ctail) (pop itail))
1039 (return nil))
1040 (let ((cval (pop ctail))
1041 (ival (pop itail)))
1042 (if (constantp cval)
1043 (unless (eql cval ival)
1044 (return nil))
1045 (push ival args))))))
1046 (dolist (ctor (plist-value class 'ctors))
1047 (when (eq (ctor-state ctor) 'optimized)
1048 (multiple-value-bind (ctor-args matchp)
1049 (frob-initargs ctor)
1050 (when matchp
1051 (return (apply ctor ctor-args))))))))
1053 ;;; FIXME: CHECK-FOO-INITARGS share most of their bodies.
1054 (defun check-mi-initargs (class initargs)
1055 (let* ((class-proto (class-prototype class))
1056 (keys (plist-keys initargs))
1057 (cache (plist-value class 'mi-initargs))
1058 (cached (assoc keys cache :test #'equal))
1059 (invalid-keys
1060 (if (consp cached)
1061 (cdr cached)
1062 (let ((invalid
1063 (check-initargs-1
1064 class initargs
1065 (list (list* 'allocate-instance class initargs)
1066 (list* 'initialize-instance class-proto initargs)
1067 (list* 'shared-initialize class-proto t initargs))
1068 t nil)))
1069 (setf (plist-value class 'mi-initargs)
1070 (acons keys invalid cache))
1071 invalid))))
1072 (when invalid-keys
1073 ;; FIXME: should have an operation here, and maybe a set of
1074 ;; valid keys.
1075 (error 'initarg-error :class class :initargs invalid-keys))))
1077 (defun check-ri-initargs (instance initargs)
1078 (let* ((class (class-of instance))
1079 (keys (plist-keys initargs))
1080 (cache (plist-value class 'ri-initargs))
1081 (cached (assoc keys cache :test #'equal))
1082 (invalid-keys
1083 (if (consp cached)
1084 (cdr cached)
1085 (let ((invalid
1086 ;; FIXME: give CHECK-INITARGS-1 and friends a
1087 ;; more mnemonic name and (possibly) a nicer,
1088 ;; more orthogonal interface.
1089 (check-initargs-1
1090 class initargs
1091 (list (list* 'reinitialize-instance instance initargs)
1092 (list* 'shared-initialize instance nil initargs))
1093 t nil)))
1094 (setf (plist-value class 'ri-initargs)
1095 (acons keys invalid cache))
1096 invalid))))
1097 (when invalid-keys
1098 (error 'initarg-error :class class :initargs invalid-keys))))
1100 ;;; end of ctor.lisp