Replace DEF!METHOD and SB!XC:DEFMETHOD with just DEFMETHOD.
[sbcl.git] / src / pcl / ctor.lisp
blob98531be86f22f96ec4424180862e6d56095169ce
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) (sb-impl::std-instance-hash x))
222 ((fsc-instance-p x) (sb-impl::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 ;;; There are some MAKE-INSTANCE calls compiled prior to this macro definition.
365 ;;; While it would be trivial to move earlier, I'm not sure that it would
366 ;;; actually work.
367 (define-compiler-macro make-instance (&whole form &rest args &environment env)
368 (declare (ignore args))
369 ;; Compiling an optimized constructor for a non-standard class means
370 ;; compiling a lambda with (MAKE-INSTANCE #<SOME-CLASS X> ...) in it
371 ;; -- need to make sure we don't recurse there.
372 (or (unless *compiling-optimized-constructor*
373 (make-instance->constructor-call form (safe-code-p env)))
374 form))
376 (defun make-instance->constructor-call (form safe-code-p)
377 (destructuring-bind (class-arg &rest args) (cdr form)
378 (flet (;;
379 ;; Return the name of parameter number I of a constructor
380 ;; function.
381 (parameter-name (i)
382 (format-symbol *pcl-package* ".P~D." i))
383 ;; Check if CLASS-ARG is a constant symbol. Give up if
384 ;; not.
385 (constant-class-p ()
386 (and class-arg (constant-class-arg-p class-arg)))
387 ;; Check if ARGS are suitable for an optimized constructor.
388 ;; Return NIL from the outer function if not.
389 (check-args ()
390 (loop for (key . more) on args by #'cddr do
391 (when (or (null more)
392 (not (constant-symbol-p key))
393 (eq :allow-other-keys (constant-form-value key)))
394 (return-from make-instance->constructor-call nil)))))
395 (check-args)
396 ;; Collect a plist of initargs and constant values/parameter names
397 ;; in INITARGS. Collect non-constant initialization forms in
398 ;; VALUE-FORMS.
399 (multiple-value-bind (initargs value-forms)
400 (loop for (key value) on args by #'cddr and i from 0
401 collect (constant-form-value key) into initargs
402 if (constantp value)
403 collect value into initargs
404 else
405 collect (parameter-name i) into initargs
406 and collect value into value-forms
407 finally
408 (return (values initargs value-forms)))
409 (if (constant-class-p)
410 (let* ((class-or-name (constant-form-value class-arg))
411 (function-name (make-ctor-function-name class-or-name initargs
412 safe-code-p)))
413 (sb-int:check-deprecated-type (if (classp class-or-name)
414 (class-name class-or-name)
415 class-or-name))
416 ;; Prevent compiler warnings for calling the ctor.
417 (proclaim-as-fun-name function-name)
418 (note-name-defined function-name :function)
419 (when (eq (info :function :where-from function-name) :assumed)
420 (setf (info :function :where-from function-name) :defined)
421 (when (info :function :assumed-type function-name)
422 (setf (info :function :assumed-type function-name) nil)))
423 ;; Return code constructing a ctor at load time, which,
424 ;; when called, will set its funcallable instance
425 ;; function to an optimized constructor function.
426 `(locally
427 (declare (disable-package-locks ,function-name))
428 (let ((.x. (load-time-value
429 (ensure-ctor ',function-name ',class-or-name ',initargs
430 ',safe-code-p))))
431 (declare (ignore .x.))
432 ;; ??? check if this is worth it.
433 (declare
434 (ftype (or (function ,(make-list (length value-forms)
435 :initial-element t)
437 (function (&rest t) t))
438 ,function-name))
439 (funcall (function ,function-name) ,@value-forms))))
440 (when (and class-arg (not (constantp class-arg)))
441 ;; Build an inline cache: a CONS, with the actual cache
442 ;; in the CDR.
443 `(locally (declare (disable-package-locks .cache. .class-arg. .store. .fun.
444 make-instance))
445 (let* ((.cache. (load-time-value (cons 'ctor-cache nil)))
446 (.store. (cdr .cache.))
447 (.class-arg. ,class-arg))
448 (multiple-value-bind (.fun. .new-store.)
449 (ensure-cached-ctor .class-arg. .store. ',initargs ',safe-code-p)
450 ;; Thread safe: if multiple threads hit this in
451 ;; parallel, the update from the other one is
452 ;; just lost -- no harm done, except for the need
453 ;; to redo the work next time.
454 (unless (eq .store. .new-store.)
455 (setf (cdr .cache.) .new-store.))
456 (funcall (truly-the function .fun.) ,@value-forms))))))))))
458 ;;; **************************************************
459 ;;; Load-Time Constructor Function Generation *******
460 ;;; **************************************************
462 ;;; The system-supplied primary INITIALIZE-INSTANCE and
463 ;;; SHARED-INITIALIZE methods. One cannot initialize these variables
464 ;;; to the right values here because said functions don't exist yet
465 ;;; when this file is first loaded.
466 (defvar *the-system-ii-method* nil)
467 (defvar *the-system-si-method* nil)
469 (defun install-optimized-constructor (ctor)
470 (with-world-lock ()
471 (let* ((class-or-name (ctor-class-or-name ctor))
472 (class (ensure-class-finalized
473 (if (symbolp class-or-name)
474 (find-class class-or-name)
475 class-or-name))))
476 ;; We can have a class with an invalid layout here. Such a class
477 ;; cannot have a LAYOUT-INVALID of (:FLUSH ...) or (:OBSOLETE
478 ;; ...), because part of the deal is that those only happen from
479 ;; FORCE-CACHE-FLUSHES, which create a new valid wrapper for the
480 ;; class. An invalid layout of T needs to be flushed, however.
481 (when (eq (layout-invalid (class-wrapper class)) t)
482 (%force-cache-flushes class))
483 (setf (ctor-class ctor) class)
484 (pushnew ctor (plist-value class 'ctors) :test #'eq)
485 (multiple-value-bind (form locations names optimizedp)
486 (constructor-function-form ctor)
487 (setf (funcallable-instance-fun ctor)
488 (apply
489 (let ((*compiling-optimized-constructor* t))
490 (handler-bind ((compiler-note #'muffle-warning))
491 (compile nil `(lambda ,names ,form))))
492 locations)
493 (ctor-state ctor) (if optimizedp 'optimized 'fallback))))))
495 (defun constructor-function-form (ctor)
496 (let* ((class (ctor-class ctor))
497 (proto (class-prototype class))
498 (make-instance-methods
499 (compute-applicable-methods #'make-instance (list class)))
500 (allocate-instance-methods
501 (compute-applicable-methods #'allocate-instance (list class)))
502 ;; I stared at this in confusion for a while, thinking
503 ;; carefully about the possibility of the class prototype not
504 ;; being of sufficient discrimiating power, given the
505 ;; possibility of EQL-specialized methods on
506 ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE. However, given
507 ;; that this is a constructor optimization, the user doesn't
508 ;; yet have the instance to create a method with such an EQL
509 ;; specializer.
511 ;; There remains the (theoretical) possibility of someone
512 ;; coming along with code of the form
514 ;; (defmethod initialize-instance :before ((o foo) ...)
515 ;; (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
517 ;; but probably we can afford not to worry about this too
518 ;; much for now. -- CSR, 2004-07-12
519 (ii-methods
520 (compute-applicable-methods #'initialize-instance (list proto)))
521 (si-methods
522 (compute-applicable-methods #'shared-initialize (list proto t)))
523 (setf-svuc-slots
524 (loop for slot in (class-slots class)
525 when (cdr (compute-applicable-methods
526 #'(setf slot-value-using-class)
527 (list nil class proto slot)))
528 collect slot))
529 (sbuc-slots
530 (loop for slot in (class-slots class)
531 when (cdr (compute-applicable-methods
532 #'slot-boundp-using-class
533 (list class proto slot)))
534 collect slot)))
535 ;; Cannot initialize these variables earlier because the generic
536 ;; functions don't exist when PCL is built.
537 (when (null *the-system-si-method*)
538 (setq *the-system-si-method*
539 (find-method #'shared-initialize
540 () (list *the-class-slot-object* *the-class-t*)))
541 (setq *the-system-ii-method*
542 (find-method #'initialize-instance
543 () (list *the-class-slot-object*))))
544 ;; Note that when there are user-defined applicable methods on
545 ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
546 ;; together with the system-defined ones in what
547 ;; COMPUTE-APPLICABLE-METHODS returns.
548 (let ((maybe-invalid-initargs
549 (check-initargs-1
550 class
551 (append
552 (ctor-default-initkeys
553 (ctor-initargs ctor) (class-default-initargs class))
554 (plist-keys (ctor-initargs ctor)))
555 (append ii-methods si-methods) nil nil))
556 (custom-make-instance
557 (not (null (cdr make-instance-methods)))))
558 (if (and (not (structure-class-p class))
559 (not (condition-class-p class))
560 (not custom-make-instance)
561 (null (cdr allocate-instance-methods))
562 (every (lambda (x)
563 (member (slot-definition-allocation x)
564 '(:instance :class)))
565 (class-slots class))
566 (not maybe-invalid-initargs)
567 (not (hairy-around-or-nonstandard-primary-method-p
568 ii-methods *the-system-ii-method*))
569 (not (around-or-nonstandard-primary-method-p
570 si-methods *the-system-si-method*)))
571 (optimizing-generator ctor ii-methods si-methods setf-svuc-slots sbuc-slots)
572 (fallback-generator ctor ii-methods si-methods
573 (or maybe-invalid-initargs custom-make-instance))))))
575 (defun around-or-nonstandard-primary-method-p
576 (methods &optional standard-method)
577 (loop with primary-checked-p = nil
578 for method in methods
579 as qualifiers = (if (consp method)
580 (early-method-qualifiers method)
581 (safe-method-qualifiers method))
582 when (or (eq :around (car qualifiers))
583 (and (null qualifiers)
584 (not primary-checked-p)
585 (not (null standard-method))
586 (not (eq standard-method method))))
587 return t
588 when (null qualifiers) do
589 (setq primary-checked-p t)))
591 (defun hairy-around-or-nonstandard-primary-method-p
592 (methods &optional standard-method)
593 (loop with primary-checked-p = nil
594 for method in methods
595 as qualifiers = (if (consp method)
596 (early-method-qualifiers method)
597 (safe-method-qualifiers method))
598 when (or (and (eq :around (car qualifiers))
599 (not (simple-next-method-call-p method)))
600 (and (null qualifiers)
601 (not primary-checked-p)
602 (not (null standard-method))
603 (not (eq standard-method method))))
604 return t
605 when (null qualifiers) do
606 (setq primary-checked-p t)))
608 (defun fallback-generator (ctor ii-methods si-methods use-make-instance)
609 (declare (ignore ii-methods si-methods))
610 (let ((class (ctor-class ctor))
611 (lambda-list (make-ctor-parameter-list ctor))
612 (initargs (ctor-initargs ctor)))
613 (if use-make-instance
614 `(lambda ,lambda-list
615 (declare #.*optimize-speed*)
616 ;; The CTOR MAKE-INSTANCE optimization checks for
617 ;; *COMPILING-OPTIMIZED-CONSTRUCTOR* which is bound around
618 ;; compilation of the constructor, hence avoiding the
619 ;; possibility of endless recursion.
620 (make-instance ,class ,@(quote-plist-keys initargs)))
621 (let ((defaults (class-default-initargs class)))
622 (when defaults
623 (setf initargs (ctor-default-initargs initargs defaults)))
624 `(lambda ,lambda-list
625 (declare #.*optimize-speed*)
626 (fast-make-instance ,class ,@(quote-plist-keys initargs)))))))
628 ;;; Not as good as the real optimizing generator, but faster than going
629 ;;; via MAKE-INSTANCE: 1 GF call less, and no need to check initargs.
630 (defun fast-make-instance (class &rest initargs)
631 (declare #.*optimize-speed*)
632 (declare (dynamic-extent initargs))
633 (let ((.instance. (apply #'allocate-instance class initargs)))
634 (apply #'initialize-instance .instance. initargs)
635 .instance.))
637 (defun optimizing-generator
638 (ctor ii-methods si-methods setf-svuc-slots sbuc-slots)
639 (multiple-value-bind (locations names body early-unbound-markers-p)
640 (fake-initialization-emf ctor ii-methods si-methods
641 setf-svuc-slots sbuc-slots)
642 (let ((wrapper (class-wrapper (ctor-class ctor))))
643 (values
644 `(lambda ,(make-ctor-parameter-list ctor)
645 (declare #.*optimize-speed*)
646 (block nil
647 (when (layout-invalid ,wrapper)
648 (install-initial-constructor ,ctor)
649 (return (funcall ,ctor ,@(make-ctor-parameter-list ctor))))
650 ,(wrap-in-allocate-forms ctor body early-unbound-markers-p)))
651 locations
652 names
653 t))))
655 ;;; Return a form wrapped around BODY that allocates an instance constructed
656 ;;; by CTOR. EARLY-UNBOUND-MARKERS-P means slots may be accessed before we
657 ;;; have explicitly initialized them, requiring all slots to start as
658 ;;; +SLOT-UNBOUND+. The resulting form binds the local variables .INSTANCE. to
659 ;;; the instance, and .SLOTS. to the instance's slot vector around BODY.
660 (defun wrap-in-allocate-forms (ctor body early-unbound-markers-p)
661 (let* ((class (ctor-class ctor))
662 (wrapper (class-wrapper class))
663 (allocation-function (raw-instance-allocator class))
664 (slots-fetcher (slots-fetcher class)))
665 (if (eq allocation-function 'allocate-standard-instance)
666 `(let ((.instance. (%make-standard-instance nil 0))
667 (.slots. (make-array
668 ,(layout-length wrapper)
669 ,@(when early-unbound-markers-p
670 '(:initial-element +slot-unbound+)))))
671 (setf (std-instance-wrapper .instance.) ,wrapper)
672 (setf (std-instance-slots .instance.) .slots.)
673 ,body
674 .instance.)
675 `(let* ((.instance. (,allocation-function ,wrapper))
676 (.slots. (,slots-fetcher .instance.)))
677 (declare (ignorable .slots.))
678 ,body
679 .instance.))))
681 ;;; Return a form for invoking METHOD with arguments from ARGS. As
682 ;;; can be seen in METHOD-FUNCTION-FROM-FAST-FUNCTION, method
683 ;;; functions look like (LAMBDA (ARGS NEXT-METHODS) ...). We could
684 ;;; call fast method functions directly here, but benchmarks show that
685 ;;; there's no speed to gain, so lets avoid the hair here.
686 (defmacro invoke-method (method args &optional next-methods)
687 `(funcall ,(the function (method-function method)) ,args ,next-methods))
689 ;;; Return a form that is sort of an effective method comprising all
690 ;;; calls to INITIALIZE-INSTANCE and SHARED-INITIALIZE that would
691 ;;; normally have taken place when calling MAKE-INSTANCE.
692 (defun fake-initialization-emf
693 (ctor ii-methods si-methods setf-svuc-slots sbuc-slots)
694 (multiple-value-bind (ii-around ii-before ii-primary ii-after)
695 (standard-sort-methods ii-methods)
696 (declare (ignore ii-primary))
697 (multiple-value-bind (si-around si-before si-primary si-after)
698 (standard-sort-methods si-methods)
699 (declare (ignore si-primary))
700 (aver (null si-around))
701 (let ((initargs (ctor-initargs ctor))
702 ;; :BEFORE and :AROUND initialization methods, and SETF SVUC and
703 ;; SBUC methods can cause slots to be accessed before the we have
704 ;; touched them here, which requires the instance-vector to be
705 ;; initialized with +SLOT-UNBOUND+ to start with.
706 (early-unbound-markers-p (or ii-before si-before ii-around
707 setf-svuc-slots sbuc-slots)))
708 (multiple-value-bind
709 (locations names bindings vars defaulting-initargs body)
710 (slot-init-forms ctor
711 early-unbound-markers-p
712 setf-svuc-slots sbuc-slots)
713 (values
714 locations
715 names
716 `(let ,bindings
717 (declare (ignorable ,@vars))
718 (flet ((initialize-it (.ii-args. .next-methods.)
719 ;; This has all the :BEFORE and :AFTER methods,
720 ;; and BODY does what primary SI method would do.
721 (declare (ignore .next-methods.))
722 (let* ((.instance. (car .ii-args.))
723 ,@(when (or si-before si-after)
724 `((.si-args.
725 (list* .instance. t (cdr .ii-args.))))))
726 ,@(loop for method in ii-before
727 collect `(invoke-method ,method .ii-args.))
728 ,@(loop for method in si-before
729 collect `(invoke-method ,method .si-args.))
730 ,@body
731 ,@(loop for method in si-after
732 collect `(invoke-method ,method .si-args.))
733 ,@(loop for method in ii-after
734 collect `(invoke-method ,method .ii-args.))
735 .instance.)))
736 (declare (dynamic-extent #'initialize-it))
737 (let ((.ii-args.
738 ,@(if (or ii-before ii-after ii-around si-before si-after)
739 `((list .instance. ,@(quote-plist-keys initargs)
740 ,@defaulting-initargs))
741 `((list .instance.)))))
742 ,(if ii-around
743 ;; If there are :AROUND methods, call them first -- they get
744 ;; the normal chaining, with #'INITIALIZE-IT standing in for
745 ;; the rest.
746 `(let ((.next-methods.
747 (list ,@(cdr ii-around) #'initialize-it)))
748 (declare (dynamic-extent .next-methods.))
749 (invoke-method ,(car ii-around) .ii-args. .next-methods.))
750 ;; The simple case.
751 `(initialize-it .ii-args. nil)))))
752 early-unbound-markers-p))))))
754 ;;; Return four values from APPLICABLE-METHODS: around methods, before
755 ;;; methods, the applicable primary method, and applicable after
756 ;;; methods. Before and after methods are sorted in the order they
757 ;;; must be called.
758 (defun standard-sort-methods (applicable-methods)
759 (loop for method in applicable-methods
760 as qualifiers = (if (consp method)
761 (early-method-qualifiers method)
762 (safe-method-qualifiers method))
763 if (null qualifiers)
764 collect method into primary
765 else if (eq :around (car qualifiers))
766 collect method into around
767 else if (eq :after (car qualifiers))
768 collect method into after
769 else if (eq :before (car qualifiers))
770 collect method into before
771 finally
772 (return (values around before (first primary) (reverse after)))))
774 (defmacro with-type-checked ((type safe-p) &body body)
775 (if safe-p
776 ;; To handle FUNCTION types reasonable, we use SAFETY 3 and
777 ;; THE instead of e.g. CHECK-TYPE.
778 `(locally
779 (declare (optimize (safety 3)))
780 (the ,type (progn ,@body)))
781 `(progn ,@body)))
783 ;;; Return as multiple values bindings for default initialization arguments,
784 ;;; variable names, defaulting initargs and a body for initializing instance
785 ;;; and class slots of an object costructed by CTOR. The variable .SLOTS. is
786 ;;; assumed to bound to the instance's slot vector. EARLY-UNBOUND-MARKERS-P
787 ;;; means other code will initialize instance slots to +SLOT-UNBOUND+, and we
788 ;;; have to check if something has already set slots before we initialize
789 ;;; them.
790 (defun slot-init-forms (ctor early-unbound-markers-p setf-svuc-slots sbuc-slots)
791 (let* ((class (ctor-class ctor))
792 (initargs (ctor-initargs ctor))
793 (initkeys (plist-keys initargs))
794 (safe-p (ctor-safe-p ctor))
795 (wrapper (class-wrapper class))
796 (slot-vector
797 (make-array (layout-length wrapper) :initial-element nil))
798 (class-inits ())
799 (default-inits ())
800 (defaulting-initargs ())
801 (default-initargs (class-default-initargs class))
802 (initarg-locations
803 (compute-initarg-locations
804 class (append initkeys (mapcar #'car default-initargs)))))
805 (labels ((initarg-locations (initarg)
806 (cdr (assoc initarg initarg-locations :test #'eq)))
807 (initializedp (location)
808 (cond
809 ((consp location)
810 (assoc location class-inits :test #'eq))
811 ((integerp location)
812 (not (null (aref slot-vector location))))
813 (t (bug "Weird location in ~S" 'slot-init-forms))))
814 (class-init (location kind val type slotd)
815 (aver (consp location))
816 (unless (initializedp location)
817 (push (list location kind val type slotd) class-inits)))
818 (instance-init (location kind val type slotd)
819 (aver (integerp location))
820 (unless (initializedp location)
821 (setf (aref slot-vector location)
822 (list kind val type slotd))))
823 (default-init-var-name (i)
824 (format-symbol *pcl-package* ".D~D." i))
825 (location-var-name (i)
826 (format-symbol *pcl-package* ".L~D." i)))
827 ;; Loop over supplied initargs and values and record which
828 ;; instance and class slots they initialize.
829 (loop for (key value) on initargs by #'cddr
830 as kind = (if (constantp value) 'constant 'param)
831 as locations = (initarg-locations key)
832 do (loop for (location type slotd) in locations
833 do (if (consp location)
834 (class-init location kind value type slotd)
835 (instance-init location kind value type slotd))))
836 ;; Loop over default initargs of the class, recording
837 ;; initializations of slots that have not been initialized
838 ;; above. Default initargs which are not in the supplied
839 ;; initargs are treated as if they were appended to supplied
840 ;; initargs, that is, their values must be evaluated even
841 ;; if not actually used for initializing a slot.
842 (loop for (key initform initfn) in default-initargs and i from 0
843 unless (member key initkeys :test #'eq)
844 do (let* ((kind (if (constantp initform) 'constant 'var))
845 (init (if (eq kind 'var) initfn initform)))
846 (ecase kind
847 (constant
848 (push (list 'quote key) defaulting-initargs)
849 (push initform defaulting-initargs))
850 (var
851 (push (list 'quote key) defaulting-initargs)
852 (push (default-init-var-name i) defaulting-initargs)))
853 (when (eq kind 'var)
854 (let ((init-var (default-init-var-name i)))
855 (setq init init-var)
856 (push (cons init-var initfn) default-inits)))
857 (loop for (location type slotd) in (initarg-locations key)
858 do (if (consp location)
859 (class-init location kind init type slotd)
860 (instance-init location kind init type slotd)))))
861 ;; Loop over all slots of the class, filling in the rest from
862 ;; slot initforms.
863 (loop for slotd in (class-slots class)
864 as location = (slot-definition-location slotd)
865 as type = (slot-definition-type slotd)
866 as allocation = (slot-definition-allocation slotd)
867 as initfn = (slot-definition-initfunction slotd)
868 as initform = (slot-definition-initform slotd) do
869 (unless (or (eq allocation :class)
870 (null initfn)
871 (initializedp location))
872 (if (constantp initform)
873 (instance-init location 'initform initform type slotd)
874 (instance-init location
875 'initform/initfn initfn type slotd))))
876 ;; Generate the forms for initializing instance and class slots.
877 (let ((instance-init-forms
878 (loop for slot-entry across slot-vector and i from 0
879 as (kind value type slotd) = slot-entry
880 collect
881 (flet ((setf-form (value-form)
882 (if (member slotd setf-svuc-slots :test #'eq)
883 `(setf (slot-value-using-class
884 ,class .instance. ,slotd)
885 ,value-form)
886 `(setf (clos-slots-ref .slots. ,i)
887 (with-type-checked (,type ,safe-p)
888 ,value-form))))
889 (not-boundp-form ()
890 (if (member slotd sbuc-slots :test #'eq)
891 `(not (slot-boundp-using-class
892 ,class .instance. ,slotd))
893 `(eq (clos-slots-ref .slots. ,i)
894 +slot-unbound+))))
895 (ecase kind
896 ((nil)
897 (unless early-unbound-markers-p
898 `(setf (clos-slots-ref .slots. ,i)
899 +slot-unbound+)))
900 ((param var)
901 (setf-form value))
902 (initfn
903 (setf-form `(funcall ,value)))
904 (initform/initfn
905 (if early-unbound-markers-p
906 `(when ,(not-boundp-form)
907 ,(setf-form `(funcall ,value)))
908 (setf-form `(funcall ,value))))
909 (initform
910 (if early-unbound-markers-p
911 `(when ,(not-boundp-form)
912 ,(setf-form `',(constant-form-value value)))
913 (setf-form `',(constant-form-value value))))
914 (constant
915 (setf-form `',(constant-form-value value))))))))
916 ;; we are not allowed to modify QUOTEd locations, so we can't
917 ;; generate code like (setf (cdr ',location) arg). Instead,
918 ;; we have to do (setf (cdr .L0.) arg) and arrange for .L0. to
919 ;; be bound to the location.
920 (multiple-value-bind (names locations class-init-forms)
921 (loop with names
922 with locations
923 with i = -1
924 for (location kind value type slotd) in class-inits
925 for init-form
926 = (case kind
927 (constant `',(constant-form-value value))
928 ((param var) `,value)
929 (initfn `(funcall ,value)))
930 when (member slotd setf-svuc-slots :test #'eq)
931 collect `(setf (slot-value-using-class
932 ,class .instance. ,slotd)
933 ,init-form)
934 into class-init-forms
935 else collect
936 (let ((name (location-var-name (incf i))))
937 (push name names)
938 (push location locations)
939 `(setf (cdr ,name)
940 (with-type-checked (,type ,safe-p)
941 ,init-form)))
942 into class-init-forms
943 finally (return (values (nreverse names)
944 (nreverse locations)
945 class-init-forms)))
946 (multiple-value-bind (vars bindings)
947 (loop for (var . initfn) in (nreverse default-inits)
948 collect var into vars
949 collect `(,var (funcall ,initfn)) into bindings
950 finally (return (values vars bindings)))
951 (values locations names
952 bindings vars
953 (nreverse defaulting-initargs)
954 `(,@(delete nil instance-init-forms)
955 ,@class-init-forms))))))))
957 ;;; Return an alist of lists (KEY (LOCATION . TYPE-SPECIFIER) ...)
958 ;;; telling, for each key in INITKEYS, which locations the initarg
959 ;;; initializes and the associated type with the location. CLASS is
960 ;;; the class of the instance being initialized.
961 (defun compute-initarg-locations (class initkeys)
962 (loop with slots = (class-slots class)
963 for key in initkeys collect
964 (loop for slot in slots
965 if (memq key (slot-definition-initargs slot))
966 collect (list (slot-definition-location slot)
967 (slot-definition-type slot)
968 slot)
969 into locations
970 else
971 collect slot into remaining-slots
972 finally
973 (setq slots remaining-slots)
974 (return (cons key locations)))))
977 ;;; *******************************
978 ;;; External Entry Points ********
979 ;;; *******************************
981 (defun update-ctors (reason &key class name generic-function method)
982 (labels ((reset (class &optional initarg-caches-p (ctorsp t))
983 (when ctorsp
984 (dolist (ctor (plist-value class 'ctors))
985 (install-initial-constructor ctor)))
986 (when initarg-caches-p
987 (dolist (cache '(mi-initargs ri-initargs))
988 (setf (plist-value class cache) ())))
989 (dolist (subclass (class-direct-subclasses class))
990 (reset subclass initarg-caches-p ctorsp))))
991 (ecase reason
992 ;; CLASS must have been specified.
993 (finalize-inheritance
994 (reset class t))
995 ;; NAME must have been specified.
996 (setf-find-class
997 (loop for ctor in *all-ctors*
998 when (eq (ctor-class-or-name ctor) name) do
999 (when (ctor-class ctor)
1000 (reset (ctor-class ctor)))
1001 (loop-finish)))
1002 ;; GENERIC-FUNCTION and METHOD must have been specified.
1003 ((add-method remove-method)
1004 (flet ((class-of-1st-method-param (method)
1005 (type-class (first (method-specializers method)))))
1006 (case (generic-function-name generic-function)
1007 ((make-instance allocate-instance)
1008 ;; FIXME: I can't see a way of working out which classes a
1009 ;; given metaclass specializer are applicable to short of
1010 ;; iterating and testing with class-of. It would be good
1011 ;; to not invalidate caches of system classes at this
1012 ;; point (where it is not legal to define a method
1013 ;; applicable to them on system functions). -- CSR,
1014 ;; 2010-07-13
1015 (reset (find-class 'standard-object) t t))
1016 ((initialize-instance shared-initialize)
1017 (reset (class-of-1st-method-param method) t t))
1018 ((reinitialize-instance)
1019 (reset (class-of-1st-method-param method) t nil))
1020 (t (when (or (eq (generic-function-name generic-function)
1021 'slot-boundp-using-class)
1022 (equal (generic-function-name generic-function)
1023 '(setf slot-value-using-class)))
1024 ;; this looks awfully expensive, but given that one
1025 ;; can specialize on the SLOTD argument, nothing is
1026 ;; safe. -- CSR, 2004-07-12
1027 (reset (find-class 'standard-object))))))))))
1029 (defun precompile-ctors ()
1030 (dolist (ctor *all-ctors*)
1031 (when (null (ctor-class ctor))
1032 (let ((class (find-class (ctor-class-or-name ctor) nil)))
1033 (when (and class (class-finalized-p class))
1034 (install-optimized-constructor ctor))))))
1036 (defun maybe-call-ctor (class initargs)
1037 (flet ((frob-initargs (ctor)
1038 (do ((ctail (ctor-initargs ctor))
1039 (itail initargs)
1040 (args nil))
1041 ((or (null ctail) (null itail))
1042 (values (nreverse args) (and (null ctail) (null itail))))
1043 (unless (eq (pop ctail) (pop itail))
1044 (return nil))
1045 (let ((cval (pop ctail))
1046 (ival (pop itail)))
1047 (if (constantp cval)
1048 (unless (eql cval ival)
1049 (return nil))
1050 (push ival args))))))
1051 (dolist (ctor (plist-value class 'ctors))
1052 (when (eq (ctor-state ctor) 'optimized)
1053 (multiple-value-bind (ctor-args matchp)
1054 (frob-initargs ctor)
1055 (when matchp
1056 (return (apply ctor ctor-args))))))))
1058 ;;; FIXME: CHECK-FOO-INITARGS share most of their bodies.
1059 (defun check-mi-initargs (class initargs)
1060 (let* ((class-proto (class-prototype class))
1061 (keys (plist-keys initargs))
1062 (cache (plist-value class 'mi-initargs))
1063 (cached (assoc keys cache :test #'equal))
1064 (invalid-keys
1065 (if (consp cached)
1066 (cdr cached)
1067 (let ((invalid
1068 (check-initargs-1
1069 class initargs
1070 (list (list* 'allocate-instance class initargs)
1071 (list* 'initialize-instance class-proto initargs)
1072 (list* 'shared-initialize class-proto t initargs))
1073 t nil)))
1074 (setf (plist-value class 'mi-initargs)
1075 (acons keys invalid cache))
1076 invalid))))
1077 (when invalid-keys
1078 ;; FIXME: should have an operation here, and maybe a set of
1079 ;; valid keys.
1080 (error 'initarg-error :class class :initargs invalid-keys))))
1082 (defun check-ri-initargs (instance initargs)
1083 (let* ((class (class-of instance))
1084 (keys (plist-keys initargs))
1085 (cache (plist-value class 'ri-initargs))
1086 (cached (assoc keys cache :test #'equal))
1087 (invalid-keys
1088 (if (consp cached)
1089 (cdr cached)
1090 (let ((invalid
1091 ;; FIXME: give CHECK-INITARGS-1 and friends a
1092 ;; more mnemonic name and (possibly) a nicer,
1093 ;; more orthogonal interface.
1094 (check-initargs-1
1095 class initargs
1096 (list (list* 'reinitialize-instance instance initargs)
1097 (list* 'shared-initialize instance nil initargs))
1098 t nil)))
1099 (setf (plist-value class 'ri-initargs)
1100 (acons keys invalid cache))
1101 invalid))))
1102 (when invalid-keys
1103 (error 'initarg-error :class class :initargs invalid-keys))))
1105 ;;; end of ctor.lisp