1.0.37.7: RETRY restart for NO-APPLICABLE-METHOD and NO-PRIMARY-METHOD
[sbcl.git] / src / pcl / dfun.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26 #|
27
28 This implementation of method lookup was redone in early August of 89.
29
30 It has the following properties:
31
32  - Its modularity makes it easy to modify the actual caching algorithm.
33    The caching algorithm is almost completely separated into the files
34    cache.lisp and dlap.lisp. This file just contains the various uses
35    of it. There will be more tuning as we get more results from Luis'
36    measurements of caching behavior.
37
38  - The metacircularity issues have been dealt with properly. All of
39    PCL now grounds out properly. Moreover, it is now possible to have
40    metaobject classes which are themselves not instances of standard
41    metaobject classes.
42
43 ** Modularity of the code **
44
45 The actual caching algorithm is isolated in a modest number of functions.
46 The code which generates cache lookup code is all found in cache.lisp and
47 dlap.lisp. Certain non-wrapper-caching special cases are in this file.
48
49 ** Handling the metacircularity **
50
51 In CLOS, method lookup is the potential source of infinite metacircular
52 regress. The metaobject protocol specification gives us wide flexibility
53 in how to address this problem. PCL uses a technique which handles the
54 problem not only for the metacircular language described in Chapter 3, but
55 also for the PCL protocol which includes additional generic functions
56 which control more aspects of the CLOS implementation.
57
58 The source of the metacircular regress can be seen in a number of ways.
59 One is that the specified method lookup protocol must, as part of doing
60 the method lookup (or at least the cache miss case), itself call generic
61 functions. It is easy to see that if the method lookup for a generic
62 function ends up calling that same generic function there can be trouble.
63
64 Fortunately, there is an easy solution at hand. The solution is based on
65 the restriction that portable code cannot change the class of a specified
66 metaobject. This restriction implies that for specified generic functions,
67 the method lookup protocol they follow is fixed.
68
69 More precisely, for such specified generic functions, most generic functions
70 that are called during their own method lookup will not run portable methods.
71 This allows the implementation to usurp the actual generic function call in
72 this case. In short, method lookup of a standard generic function, in the
73 case where the only applicable methods are themselves standard doesn't
74 have to do any method lookup to implement itself.
75
76 And so, we are saved.
77
78 Except see also BREAK-VICIOUS-METACIRCLE.  -- CSR, 2003-05-28
79
80 |#
81 \f
82 ;;; an alist in which each entry is of the form
83 ;;;   (<generator> . (<subentry> ...)).
84 ;;; Each subentry is of the form
85 ;;;   (<args> <constructor> <system>).
86 (defvar *dfun-constructors* ())
87
88 ;;; If this is NIL, then the whole mechanism for caching dfun constructors is
89 ;;; turned off. The only time that makes sense is when debugging LAP code.
90 (defvar *enable-dfun-constructor-caching* t)
91
92 (defun show-dfun-constructors ()
93   (format t "~&DFUN constructor caching is ~A."
94           (if *enable-dfun-constructor-caching*
95               "enabled" "disabled"))
96   (dolist (generator-entry *dfun-constructors*)
97     (dolist (args-entry (cdr generator-entry))
98       (format t "~&~S ~S"
99               (cons (car generator-entry) (caar args-entry))
100               (caddr args-entry)))))
101
102 (defvar *raise-metatypes-to-class-p* t)
103
104 (defun get-dfun-constructor (generator &rest args)
105   (when (and *raise-metatypes-to-class-p*
106              (member generator '(emit-checking emit-caching
107                                  emit-in-checking-cache-p emit-constant-value)))
108     (setq args (cons (mapcar (lambda (mt)
109                                (if (eq mt t)
110                                    mt
111                                    'class))
112                              (car args))
113                      (cdr args))))
114   (let* ((generator-entry (assq generator *dfun-constructors*))
115          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
116     (if (null *enable-dfun-constructor-caching*)
117         (apply (fdefinition generator) args)
118         (or (cadr args-entry)
119             (multiple-value-bind (new not-best-p)
120                 (apply (symbol-function generator) args)
121               (let ((entry (list (copy-list args) new (unless not-best-p 'pcl)
122                                  not-best-p)))
123                 (if generator-entry
124                     (push entry (cdr generator-entry))
125                     (push (list generator entry)
126                           *dfun-constructors*)))
127               (values new not-best-p))))))
128
129 (defun load-precompiled-dfun-constructor (generator args system constructor)
130   (let* ((generator-entry (assq generator *dfun-constructors*))
131          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
132     (if args-entry
133         (when (fourth args-entry)
134           (let* ((dfun-type (case generator
135                               (emit-checking 'checking)
136                               (emit-caching 'caching)
137                               (emit-constant-value 'constant-value)
138                               (emit-default-only 'default-method-only)))
139                  (metatypes (car args))
140                  (gfs (when dfun-type (gfs-of-type dfun-type))))
141             (dolist (gf gfs)
142               (when (and (equal metatypes
143                                 (arg-info-metatypes (gf-arg-info gf)))
144                          (let ((gf-name (generic-function-name gf)))
145                            (and (not (eq gf-name 'slot-value-using-class))
146                                 (not (equal gf-name
147                                             '(setf slot-value-using-class)))
148                                 (not (eq gf-name 'slot-boundp-using-class)))))
149                 (update-dfun gf)))
150             (setf (second args-entry) constructor)
151             (setf (third args-entry) system)
152             (setf (fourth args-entry) nil)))
153         (let ((entry (list args constructor system nil)))
154           (if generator-entry
155               (push entry (cdr generator-entry))
156               (push (list generator entry) *dfun-constructors*))))))
157
158 (defmacro precompile-dfun-constructors (&optional system)
159   (let ((*precompiling-lap* t))
160     `(progn
161        ,@(let (collect)
162            (dolist (generator-entry *dfun-constructors*)
163              (dolist (args-entry (cdr generator-entry))
164                (when (or (null (caddr args-entry))
165                          (eq (caddr args-entry) system))
166                  (when system (setf (caddr args-entry) system))
167                  (push `(load-precompiled-dfun-constructor
168                          ',(car generator-entry)
169                          ',(car args-entry)
170                          ',system
171                          ,(apply (fdefinition (car generator-entry))
172                                  (car args-entry)))
173                        collect))))
174            (nreverse collect)))))
175 \f
176 ;;; Standardized class slot access: when trying to break vicious
177 ;;; metacircles, we need a way to get at the values of slots of some
178 ;;; standard classes without going through the whole meta machinery,
179 ;;; because that would likely enter the vicious circle again.  The
180 ;;; following are helper functions that short-circuit the generic
181 ;;; lookup machinery.
182
183 (defvar *standard-classes*
184   '(standard-method standard-generic-function standard-class
185     standard-effective-slot-definition))
186
187 (defvar *standard-slot-locations* (make-hash-table :test 'equal))
188
189 (defun compute-standard-slot-locations ()
190   (let ((new (make-hash-table :test 'equal)))
191     (dolist (class-name *standard-classes*)
192       (let ((class (find-class class-name)))
193         (dolist (slot (class-slots class))
194           (setf (gethash (cons class (slot-definition-name slot)) new)
195                 (slot-definition-location slot)))))
196     (setf *standard-slot-locations* new)))
197
198 (defun maybe-update-standard-slot-locations (class)
199   (when (and (eq **boot-state** 'complete)
200              (memq (class-name class) *standard-classes*))
201     (compute-standard-slot-locations)))
202
203 (defun standard-slot-value (object slot-name class)
204   (let ((location (gethash (cons class slot-name) *standard-slot-locations*)))
205     (if location
206         (let ((value (if (funcallable-instance-p object)
207                          (funcallable-standard-instance-access object location)
208                          (standard-instance-access object location))))
209           (when (eq +slot-unbound+ value)
210             (error "~@<slot ~S of class ~S is unbound in object ~S~@:>"
211                    slot-name class object))
212           value)
213         (error "~@<cannot get standard value of slot ~S of class ~S ~
214                 in object ~S~@:>"
215                slot-name class object))))
216
217 (defun standard-slot-value/gf (gf slot-name)
218   (standard-slot-value gf slot-name *the-class-standard-generic-function*))
219
220 (defun standard-slot-value/method (method slot-name)
221   (standard-slot-value method slot-name *the-class-standard-method*))
222
223 (defun standard-slot-value/eslotd (slotd slot-name)
224   (standard-slot-value slotd slot-name
225                        *the-class-standard-effective-slot-definition*))
226
227 (defun standard-slot-value/class (class slot-name)
228   (standard-slot-value class slot-name *the-class-standard-class*))
229 \f
230 ;;; When all the methods of a generic function are automatically
231 ;;; generated reader or writer methods a number of special
232 ;;; optimizations are possible. These are important because of the
233 ;;; large number of generic functions of this type.
234 ;;;
235 ;;; There are a number of cases:
236 ;;;
237 ;;;   ONE-CLASS-ACCESSOR
238 ;;;     In this case, the accessor generic function has only been
239 ;;;     called with one class of argument. There is no cache vector,
240 ;;;     the wrapper of the one class, and the slot index are stored
241 ;;;     directly as closure variables of the discriminating function.
242 ;;;     This case can convert to either of the next kind.
243 ;;;
244 ;;;   TWO-CLASS-ACCESSOR
245 ;;;     Like above, but two classes. This is common enough to do
246 ;;;     specially. There is no cache vector. The two classes are
247 ;;;     stored a separate closure variables.
248 ;;;
249 ;;;   ONE-INDEX-ACCESSOR
250 ;;;     In this case, the accessor generic function has seen more than
251 ;;;     one class of argument, but the index of the slot is the same
252 ;;;     for all the classes that have been seen. A cache vector is
253 ;;;     used to store the wrappers that have been seen, the slot index
254 ;;;     is stored directly as a closure variable of the discriminating
255 ;;;     function. This case can convert to the next kind.
256 ;;;
257 ;;;   N-N-ACCESSOR
258 ;;;     This is the most general case. In this case, the accessor
259 ;;;     generic function has seen more than one class of argument and
260 ;;;     more than one slot index. A cache vector stores the wrappers
261 ;;;     and corresponding slot indexes.
262
263 (defstruct (dfun-info (:constructor nil)
264                       (:copier nil))
265   (cache nil))
266
267 (defstruct (no-methods (:constructor no-methods-dfun-info ())
268                        (:include dfun-info)
269                        (:copier nil)))
270
271 (defstruct (initial (:constructor initial-dfun-info ())
272                     (:include dfun-info)
273                     (:copier nil)))
274
275 (defstruct (initial-dispatch (:constructor initial-dispatch-dfun-info ())
276                              (:include dfun-info)
277                              (:copier nil)))
278
279 (defstruct (dispatch (:constructor dispatch-dfun-info ())
280                      (:include dfun-info)
281                      (:copier nil)))
282
283 (defstruct (default-method-only (:constructor default-method-only-dfun-info ())
284                                 (:include dfun-info)
285                                 (:copier nil)))
286
287 ;without caching:
288 ;  dispatch one-class two-class default-method-only
289
290 ;with caching:
291 ;  one-index n-n checking caching
292
293 ;accessor:
294 ;  one-class two-class one-index n-n
295 (defstruct (accessor-dfun-info (:constructor nil)
296                                (:include dfun-info)
297                                (:copier nil))
298   accessor-type) ; (member reader writer)
299
300 (defmacro dfun-info-accessor-type (di)
301   `(accessor-dfun-info-accessor-type ,di))
302
303 (defstruct (one-index-dfun-info (:constructor nil)
304                                 (:include accessor-dfun-info)
305                                 (:copier nil))
306   index)
307
308 (defmacro dfun-info-index (di)
309   `(one-index-dfun-info-index ,di))
310
311 (defstruct (n-n (:constructor n-n-dfun-info (accessor-type cache))
312                 (:include accessor-dfun-info)
313                 (:copier nil)))
314
315 (defstruct (one-class (:constructor one-class-dfun-info
316                                     (accessor-type index wrapper0))
317                       (:include one-index-dfun-info)
318                       (:copier nil))
319   wrapper0)
320
321 (defmacro dfun-info-wrapper0 (di)
322   `(one-class-wrapper0 ,di))
323
324 (defstruct (two-class (:constructor two-class-dfun-info
325                                     (accessor-type index wrapper0 wrapper1))
326                       (:include one-class)
327                       (:copier nil))
328   wrapper1)
329
330 (defmacro dfun-info-wrapper1 (di)
331   `(two-class-wrapper1 ,di))
332
333 (defstruct (one-index (:constructor one-index-dfun-info
334                                     (accessor-type index cache))
335                       (:include one-index-dfun-info)
336                       (:copier nil)))
337
338 (defstruct (checking (:constructor checking-dfun-info (function cache))
339                      (:include dfun-info)
340                      (:copier nil))
341   function)
342
343 (defmacro dfun-info-function (di)
344   `(checking-function ,di))
345
346 (defstruct (caching (:constructor caching-dfun-info (cache))
347                     (:include dfun-info)
348                     (:copier nil)))
349
350 (defstruct (constant-value (:constructor constant-value-dfun-info (cache))
351                            (:include dfun-info)
352                            (:copier nil)))
353
354 (defmacro dfun-update (generic-function function &rest args)
355   `(multiple-value-bind (dfun cache info)
356        (funcall ,function ,generic-function ,@args)
357      (update-dfun ,generic-function dfun cache info)))
358
359 (defun accessor-miss-function (gf dfun-info)
360   (ecase (dfun-info-accessor-type dfun-info)
361     ((reader boundp)
362      (lambda (arg)
363        (accessor-miss gf nil arg dfun-info)))
364     (writer
365      (lambda (new arg)
366        (accessor-miss gf new arg dfun-info)))))
367
368 #-sb-fluid (declaim (sb-ext:freeze-type dfun-info))
369 \f
370 (defun make-one-class-accessor-dfun (gf type wrapper index)
371   (let ((emit (ecase type
372                 (reader 'emit-one-class-reader)
373                 (boundp 'emit-one-class-boundp)
374                 (writer 'emit-one-class-writer)))
375         (dfun-info (one-class-dfun-info type index wrapper)))
376     (values
377      (funcall (get-dfun-constructor emit (consp index))
378               wrapper index
379               (accessor-miss-function gf dfun-info))
380      nil
381      dfun-info)))
382
383 (defun make-two-class-accessor-dfun (gf type w0 w1 index)
384   (let ((emit (ecase type
385                 (reader 'emit-two-class-reader)
386                 (boundp 'emit-two-class-boundp)
387                 (writer 'emit-two-class-writer)))
388         (dfun-info (two-class-dfun-info type index w0 w1)))
389     (values
390      (funcall (get-dfun-constructor emit (consp index))
391               w0 w1 index
392               (accessor-miss-function gf dfun-info))
393      nil
394      dfun-info)))
395
396 ;;; std accessors same index dfun
397 (defun make-one-index-accessor-dfun (gf type index &optional cache)
398   (let* ((emit (ecase type
399                  (reader 'emit-one-index-readers)
400                  (boundp 'emit-one-index-boundps)
401                  (writer 'emit-one-index-writers)))
402          (cache (or cache (make-cache :key-count 1 :value nil :size 4)))
403          (dfun-info (one-index-dfun-info type index cache)))
404     (declare (type cache cache))
405     (values
406      (funcall (get-dfun-constructor emit (consp index))
407               cache
408               index
409               (accessor-miss-function gf dfun-info))
410      cache
411      dfun-info)))
412
413 (defun make-n-n-accessor-dfun (gf type &optional cache)
414   (let* ((emit (ecase type
415                  (reader 'emit-n-n-readers)
416                  (boundp 'emit-n-n-boundps)
417                  (writer 'emit-n-n-writers)))
418          (cache (or cache (make-cache :key-count 1 :value t :size 2)))
419          (dfun-info (n-n-dfun-info type cache)))
420     (declare (type cache cache))
421     (values
422      (funcall (get-dfun-constructor emit)
423               cache
424               (accessor-miss-function gf dfun-info))
425      cache
426      dfun-info)))
427
428 (defun make-checking-dfun (generic-function function &optional cache)
429   (unless cache
430     (when (use-caching-dfun-p generic-function)
431       (return-from make-checking-dfun (make-caching-dfun generic-function)))
432     (when (use-dispatch-dfun-p generic-function)
433       (return-from make-checking-dfun (make-dispatch-dfun generic-function))))
434   (multiple-value-bind (nreq applyp metatypes nkeys)
435       (get-generic-fun-info generic-function)
436     (declare (ignore nreq))
437     (if (every (lambda (mt) (eq mt t)) metatypes)
438         (let ((dfun-info (default-method-only-dfun-info)))
439           (values
440            (funcall (get-dfun-constructor 'emit-default-only metatypes applyp)
441                     function)
442            nil
443            dfun-info))
444         (let* ((cache (or cache (make-cache :key-count nkeys :value nil :size 2)))
445                (dfun-info (checking-dfun-info function cache)))
446           (values
447            (funcall (get-dfun-constructor 'emit-checking metatypes applyp)
448                     cache
449                     function
450                     (lambda (&rest args)
451                       (checking-miss generic-function args dfun-info)))
452            cache
453            dfun-info)))))
454
455 (defun make-final-checking-dfun (generic-function function classes-list new-class)
456   (multiple-value-bind (nreq applyp metatypes nkeys)
457       (get-generic-fun-info generic-function)
458     (declare (ignore nreq applyp nkeys))
459     (if (every (lambda (mt) (eq mt t)) metatypes)
460         (values (lambda (&rest args)
461                   (invoke-emf function args))
462                 nil (default-method-only-dfun-info))
463         (let ((cache (make-final-ordinary-dfun-cache
464                       generic-function nil classes-list new-class)))
465           (make-checking-dfun generic-function function cache)))))
466
467 (defun use-default-method-only-dfun-p (generic-function)
468   (multiple-value-bind (nreq applyp metatypes nkeys)
469       (get-generic-fun-info generic-function)
470     (declare (ignore nreq applyp nkeys))
471     (every (lambda (mt) (eq mt t)) metatypes)))
472
473 (defun use-caching-dfun-p (generic-function)
474   (some (lambda (method) (method-plist-value method :slot-name-lists))
475         ;; KLUDGE: As of sbcl-0.6.4, it's very important for
476         ;; efficiency to know the type of the sequence argument to
477         ;; quantifiers (SOME/NOTANY/etc.) at compile time, but
478         ;; the compiler isn't smart enough to understand the :TYPE
479         ;; slot option for DEFCLASS, so we just tell
480         ;; it the type by hand here.
481         (the list
482              (if (early-gf-p generic-function)
483                  (early-gf-methods generic-function)
484                  (generic-function-methods generic-function)))))
485 \f
486 (defun make-caching-dfun (generic-function &optional cache)
487   (unless cache
488     (when (use-constant-value-dfun-p generic-function)
489       (return-from make-caching-dfun
490         (make-constant-value-dfun generic-function)))
491     (when (use-dispatch-dfun-p generic-function)
492       (return-from make-caching-dfun
493         (make-dispatch-dfun generic-function))))
494   (multiple-value-bind (nreq applyp metatypes nkeys)
495       (get-generic-fun-info generic-function)
496     (declare (ignore nreq))
497     (let* ((cache (or cache (make-cache :key-count nkeys :value t :size 2)))
498            (dfun-info (caching-dfun-info cache)))
499       (values
500        (funcall (get-dfun-constructor 'emit-caching metatypes applyp)
501                 cache
502                 (lambda (&rest args)
503                   (caching-miss generic-function args dfun-info)))
504        cache
505        dfun-info))))
506
507 (defun make-final-caching-dfun (generic-function classes-list new-class)
508   (let ((cache (make-final-ordinary-dfun-cache
509                 generic-function t classes-list new-class)))
510     (make-caching-dfun generic-function cache)))
511
512 (defun insure-caching-dfun (gf)
513   (multiple-value-bind (nreq applyp metatypes nkeys)
514       (get-generic-fun-info gf)
515     (declare (ignore nreq nkeys))
516     (when (and metatypes
517                (not (null (car metatypes)))
518                (dolist (mt metatypes nil)
519                  (unless (eq mt t) (return t))))
520       (get-dfun-constructor 'emit-caching metatypes applyp))))
521
522 (defun use-constant-value-dfun-p (gf &optional boolean-values-p)
523   (multiple-value-bind (nreq applyp metatypes nkeys)
524       (get-generic-fun-info gf)
525     (declare (ignore nreq metatypes nkeys))
526     (let* ((early-p (early-gf-p gf))
527            (methods (if early-p
528                         (early-gf-methods gf)
529                         (generic-function-methods gf)))
530            (default '(unknown)))
531       (and (null applyp)
532            (or (not (eq **boot-state** 'complete))
533                ;; If COMPUTE-APPLICABLE-METHODS is specialized, we
534                ;; can't use this, of course, because we can't tell
535                ;; which methods will be considered applicable.
536                ;;
537                ;; Also, don't use this dfun method if the generic
538                ;; function has a non-standard method combination,
539                ;; because if it has, it's not sure that method
540                ;; functions are used directly as effective methods,
541                ;; which CONSTANT-VALUE-MISS depends on.  The
542                ;; pre-defined method combinations like LIST are
543                ;; examples of that.
544                (and (compute-applicable-methods-emf-std-p gf)
545                     (eq (generic-function-method-combination gf)
546                         *standard-method-combination*)))
547            ;; Check that no method is eql-specialized, and that all
548            ;; methods return a constant value.  If BOOLEAN-VALUES-P,
549            ;; check that all return T or NIL.  Also, check that no
550            ;; method has qualifiers, to make sure that emfs are really
551            ;; method functions; see above.
552            (dolist (method methods t)
553              (when (eq **boot-state** 'complete)
554                (when (or (some #'eql-specializer-p
555                                (safe-method-specializers method))
556                          (safe-method-qualifiers method))
557                  (return nil)))
558              (let ((value (method-plist-value method :constant-value default)))
559                (when (or (eq value default)
560                          (and boolean-values-p
561                               (not (member value '(t nil)))))
562                  (return nil))))))))
563
564 (defun make-constant-value-dfun (generic-function &optional cache)
565   (multiple-value-bind (nreq applyp metatypes nkeys)
566       (get-generic-fun-info generic-function)
567     (declare (ignore nreq applyp))
568     (let* ((cache (or cache (make-cache :key-count nkeys :value t :size 2)))
569            (dfun-info (constant-value-dfun-info cache)))
570       (declare (type cache cache))
571       (values
572        (funcall (get-dfun-constructor 'emit-constant-value metatypes)
573                 cache
574                 (lambda (&rest args)
575                   (constant-value-miss generic-function args dfun-info)))
576        cache
577        dfun-info))))
578
579 (defun make-final-constant-value-dfun (generic-function classes-list new-class)
580   (let ((cache (make-final-ordinary-dfun-cache
581                 generic-function :constant-value classes-list new-class)))
582     (make-constant-value-dfun generic-function cache)))
583
584 (defun gf-has-method-with-nonstandard-specializer-p (gf)
585   (let ((methods (generic-function-methods gf)))
586     (dolist (method methods nil)
587       (unless (every (lambda (s) (standard-specializer-p s))
588                      (method-specializers method))
589         (return t)))))
590
591 (defun use-dispatch-dfun-p (gf &optional (caching-p (use-caching-dfun-p gf)))
592   (when (eq **boot-state** 'complete)
593     (unless (or caching-p
594                 (gf-requires-emf-keyword-checks gf)
595                 ;; DISPATCH-DFUN-COST will error if it encounters a
596                 ;; method with a non-standard specializer.
597                 (gf-has-method-with-nonstandard-specializer-p gf))
598       ;; This should return T when almost all dispatching is by
599       ;; eql specializers or built-in classes. In other words,
600       ;; return NIL if we might ever need to do more than
601       ;; one (non built-in) typep.
602       ;; Otherwise, it is probably at least as fast to use
603       ;; a caching dfun first, possibly followed by secondary dispatching.
604
605       #||;;; Original found in cmu 17f -- S L O W
606       (< (dispatch-dfun-cost gf) (caching-dfun-cost gf))
607       ||#
608       ;; This uses improved dispatch-dfun-cost below
609       (let ((cdc  (caching-dfun-cost gf))) ; fast
610         (> cdc (dispatch-dfun-cost gf cdc))))))
611
612 (defparameter *non-built-in-typep-cost* 100)
613 (defparameter *structure-typep-cost*  15)
614 (defparameter *built-in-typep-cost* 5)
615
616 ;;; According to comments in the original CMU CL version of PCL,
617 ;;; the cost LIMIT is important to cut off exponential growth for
618 ;;; large numbers of gf methods and argument lists.
619 (defun dispatch-dfun-cost (gf &optional limit)
620   (generate-discrimination-net-internal
621    gf (generic-function-methods gf) nil
622    (lambda (methods known-types)
623      (declare (ignore methods known-types))
624      0)
625    (lambda (position type true-value false-value)
626      (declare (ignore position))
627      (let* ((type-test-cost
628              (if (eq 'class (car type))
629                  (let* ((metaclass (class-of (cadr type)))
630                         (mcpl (class-precedence-list metaclass)))
631                    (cond ((memq *the-class-built-in-class* mcpl)
632                           *built-in-typep-cost*)
633                          ((memq *the-class-structure-class* mcpl)
634                           *structure-typep-cost*)
635                          (t
636                           *non-built-in-typep-cost*)))
637                  0))
638             (max-cost-so-far
639              (+ (max true-value false-value) type-test-cost)))
640        (when (and limit (<= limit max-cost-so-far))
641          (return-from dispatch-dfun-cost max-cost-so-far))
642        max-cost-so-far))
643    #'identity))
644
645 (defparameter *cache-lookup-cost*  30)
646 (defparameter *wrapper-of-cost* 15)
647 (defparameter *secondary-dfun-call-cost* 30)
648
649 (defun caching-dfun-cost (gf)
650   (let ((nreq (get-generic-fun-info gf)))
651     (+ *cache-lookup-cost*
652        (* *wrapper-of-cost* nreq)
653        (if (methods-contain-eql-specializer-p
654             (generic-function-methods gf))
655            *secondary-dfun-call-cost*
656            0))))
657
658 (declaim (inline make-callable))
659 (defun make-callable (gf methods generator method-alist wrappers)
660   (let* ((*applicable-methods* methods)
661          (callable (function-funcall generator method-alist wrappers)))
662     callable))
663
664 (defun make-dispatch-dfun (gf)
665   (values (get-dispatch-function gf) nil (dispatch-dfun-info)))
666
667 (defun get-dispatch-function (gf)
668   (let* ((methods (generic-function-methods gf))
669          (generator (get-secondary-dispatch-function1
670                      gf methods nil nil nil nil nil t)))
671     (make-callable gf methods generator nil nil)))
672
673 (defun make-final-dispatch-dfun (gf)
674   (make-dispatch-dfun gf))
675
676 (defun update-dispatch-dfuns ()
677   (dolist (gf (gfs-of-type '(dispatch initial-dispatch)))
678     (dfun-update gf #'make-dispatch-dfun)))
679
680 (defun make-final-ordinary-dfun-cache
681     (generic-function valuep classes-list new-class)
682   (let* ((arg-info (gf-arg-info generic-function))
683          (nkeys (arg-info-nkeys arg-info))
684          (new-class (and new-class
685                          (equal (type-of (gf-dfun-info generic-function))
686                                 (cond ((eq valuep t) 'caching)
687                                       ((eq valuep :constant-value) 'constant-value)
688                                       ((null valuep) 'checking)))
689                          new-class))
690          (cache (if new-class
691                     (copy-cache (gf-dfun-cache generic-function))
692                     (make-cache :key-count nkeys :value (not (null valuep))
693                                 :size 4))))
694     (make-emf-cache generic-function valuep cache classes-list new-class)))
695 \f
696 (defvar *dfun-miss-gfs-on-stack* ())
697
698 (defmacro dfun-miss ((gf args wrappers invalidp nemf
699                       &optional type index caching-p applicable)
700                      &body body)
701   (unless applicable (setq applicable (gensym)))
702   `(multiple-value-bind (,nemf ,applicable ,wrappers ,invalidp
703                          ,@(when type `(,type ,index)))
704        (cache-miss-values ,gf ,args ',(cond (caching-p 'caching)
705                                             (type 'accessor)
706                                             (t 'checking)))
707     (when (and ,applicable (not (memq ,gf *dfun-miss-gfs-on-stack*)))
708       (let ((*dfun-miss-gfs-on-stack* (cons ,gf *dfun-miss-gfs-on-stack*)))
709         ,@body))
710     ;; Create a FAST-INSTANCE-BOUNDP structure instance for a cached
711     ;; SLOT-BOUNDP so that INVOKE-EMF does the right thing, that is,
712     ;; does not signal a SLOT-UNBOUND error for a boundp test.
713     ,@(if type
714           ;; FIXME: could the NEMF not be a CONS (for :CLASS-allocated
715           ;; slots?)
716           `((if (and (eq ,type 'boundp) (integerp ,nemf))
717                 (invoke-emf (make-fast-instance-boundp :index ,nemf) ,args)
718                 (invoke-emf ,nemf ,args)))
719           `((invoke-emf ,nemf ,args)))))
720
721 ;;; The dynamically adaptive method lookup algorithm is implemented is
722 ;;; implemented as a kind of state machine. The kinds of
723 ;;; discriminating function is the state, the various kinds of reasons
724 ;;; for a cache miss are the state transitions.
725 ;;;
726 ;;; The code which implements the transitions is all in the miss
727 ;;; handlers for each kind of dfun. Those appear here.
728 ;;;
729 ;;; Note that within the states that cache, there are dfun updates
730 ;;; which simply select a new cache or cache field. Those are not
731 ;;; considered as state transitions.
732 (defvar *lazy-dfun-compute-p* t)
733 (defvar *early-p* nil)
734
735 ;;; This variable is used for controlling the load-time effective
736 ;;; method precomputation: precomputation will only be done for emfs
737 ;;; with fewer than methods than this value. This value has
738 ;;; traditionally been NIL on SBCL (meaning that precomputation will
739 ;;; always be done) but that makes method loading O(n^2). Use a small
740 ;;; value for now, to flush out any possible problems that doing a
741 ;;; limited amount of precomputation might cause. If none appear, we
742 ;;; might change it to a larger value later. -- JES, 2006-12-01
743 (declaim (type (or null unsigned-byte) *max-emf-precomputation-methods*))
744 (defvar *max-emf-precomputation-methods* 1)
745
746 (defun finalize-specializers (gf)
747   (let ((methods (generic-function-methods gf)))
748     (when (or (null *max-emf-precomputation-methods*)
749               (<= (length methods) *max-emf-precomputation-methods*))
750       (let ((all-finalized t))
751         (dolist (method methods all-finalized)
752           (dolist (specializer (method-specializers method))
753             (when (and (classp specializer)
754                        (not (class-finalized-p specializer)))
755               (if (class-has-a-forward-referenced-superclass-p specializer)
756                   (setq all-finalized nil)
757                   (finalize-inheritance specializer)))))))))
758
759 (defun make-initial-dfun (gf)
760   (let ((initial-dfun
761          #'(lambda (&rest args)
762              (initial-dfun gf args))))
763     (multiple-value-bind (dfun cache info)
764         (cond
765           ((and (eq **boot-state** 'complete)
766                 (not (finalize-specializers gf)))
767            (values initial-dfun nil (initial-dfun-info)))
768           ((and (eq **boot-state** 'complete)
769                 (compute-applicable-methods-emf-std-p gf))
770            (let* ((caching-p (use-caching-dfun-p gf))
771                   ;; KLUDGE: the only effect of this (when
772                   ;; *LAZY-DFUN-COMPUTE-P* is true, as it usually is)
773                   ;; is to signal an error when we try to add methods
774                   ;; with the wrong qualifiers to a generic function.
775                   (classes-list (precompute-effective-methods
776                                  gf caching-p
777                                  (not *lazy-dfun-compute-p*))))
778              (if *lazy-dfun-compute-p*
779                  (cond ((use-dispatch-dfun-p gf caching-p)
780                         (values initial-dfun
781                                 nil
782                                 (initial-dispatch-dfun-info)))
783                        (caching-p
784                         (insure-caching-dfun gf)
785                         (values initial-dfun nil (initial-dfun-info)))
786                        (t
787                         (values initial-dfun nil (initial-dfun-info))))
788                  (make-final-dfun-internal gf classes-list))))
789           (t
790            (let ((arg-info (if (early-gf-p gf)
791                                (early-gf-arg-info gf)
792                                (gf-arg-info gf)))
793                  (type nil))
794              (if (and (gf-precompute-dfun-and-emf-p arg-info)
795                       (setq type (final-accessor-dfun-type gf)))
796                  (if *early-p*
797                      (values (make-early-accessor gf type) nil nil)
798                      (make-final-accessor-dfun gf type))
799                  (values initial-dfun nil (initial-dfun-info))))))
800       (set-dfun gf dfun cache info))))
801
802 (defun make-early-accessor (gf type)
803   (let* ((methods (early-gf-methods gf))
804          (slot-name (early-method-standard-accessor-slot-name (car methods))))
805     (ecase type
806       (reader #'(lambda (instance)
807                   (let* ((class (class-of instance))
808                          (class-name (!bootstrap-get-slot 'class class 'name)))
809                     (!bootstrap-get-slot class-name instance slot-name))))
810       (boundp #'(lambda (instance)
811                   (let* ((class (class-of instance))
812                          (class-name (!bootstrap-get-slot 'class class 'name)))
813                     (not (eq +slot-unbound+
814                              (!bootstrap-get-slot class-name
815                                                   instance slot-name))))))
816       (writer #'(lambda (new-value instance)
817                   (let* ((class (class-of instance))
818                          (class-name (!bootstrap-get-slot 'class class 'name)))
819                     (!bootstrap-set-slot class-name instance slot-name new-value)))))))
820
821 (defun initial-dfun (gf args)
822   (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
823     (cond (invalidp)
824           ((and ntype nindex)
825            (dfun-update
826             gf #'make-one-class-accessor-dfun ntype wrappers nindex))
827           ((use-caching-dfun-p gf)
828            (dfun-update gf #'make-caching-dfun))
829           (t
830            (dfun-update gf #'make-checking-dfun
831             ;; nemf is suitable only for caching, have to do this:
832             (cache-miss-values gf args 'checking))))))
833
834 (defun make-final-dfun (gf &optional classes-list)
835   (multiple-value-bind (dfun cache info)
836       (make-final-dfun-internal gf classes-list)
837     (set-dfun gf dfun cache info)))
838
839 ;;; FIXME: What is this?
840 (defvar *new-class* nil)
841
842 (defun final-accessor-dfun-type (gf)
843   (let ((methods (if (early-gf-p gf)
844                      (early-gf-methods gf)
845                      (generic-function-methods gf))))
846     (cond ((every (lambda (method)
847                     (if (consp method)
848                         (let ((class (early-method-class method)))
849                           (or (eq class *the-class-standard-reader-method*)
850                               (eq class *the-class-global-reader-method*)))
851                         (or (standard-reader-method-p method)
852                             (global-reader-method-p method))))
853                   methods)
854            'reader)
855           ((every (lambda (method)
856                     (if (consp method)
857                         (let ((class (early-method-class method)))
858                           (or (eq class *the-class-standard-boundp-method*)
859                               (eq class *the-class-global-boundp-method*)))
860                         (or (standard-boundp-method-p method)
861                             (global-boundp-method-p method))))
862                   methods)
863            'boundp)
864           ((every (lambda (method)
865                     (if (consp method)
866                         (let ((class (early-method-class method)))
867                           (or (eq class *the-class-standard-writer-method*)
868                               (eq class *the-class-global-writer-method*)))
869                         (and
870                          (or (standard-writer-method-p method)
871                              (global-writer-method-p method))
872                          (not (safe-p
873                                (slot-definition-class
874                                 (accessor-method-slot-definition method)))))))
875                   methods)
876            'writer))))
877
878 (defun make-final-accessor-dfun (gf type &optional classes-list new-class)
879   (let ((table (make-hash-table :test #'eq)))
880     (multiple-value-bind (table all-index first second size no-class-slots-p)
881         (make-accessor-table gf type table)
882       (if table
883           (cond ((= size 1)
884                  (let ((w (class-wrapper first)))
885                    (make-one-class-accessor-dfun gf type w all-index)))
886                 ((and (= size 2) (or (integerp all-index) (consp all-index)))
887                  (let ((w0 (class-wrapper first))
888                        (w1 (class-wrapper second)))
889                    (make-two-class-accessor-dfun gf type w0 w1 all-index)))
890                 ((or (integerp all-index) (consp all-index))
891                  (let ((cache (hash-table-to-cache table :value nil :key-count 1)))
892                    (make-one-index-accessor-dfun gf type all-index cache)))
893                 (no-class-slots-p
894                  (let ((cache (hash-table-to-cache table :value t :key-count 1)))
895                    (make-n-n-accessor-dfun gf type cache)))
896                 (t
897                  (make-final-caching-dfun gf classes-list new-class)))
898           (make-final-caching-dfun gf classes-list new-class)))))
899
900 (defun make-final-dfun-internal (gf &optional classes-list)
901   (let ((methods (generic-function-methods gf)) type
902         (new-class *new-class*) (*new-class* nil)
903         specls all-same-p)
904     (cond ((null methods)
905            (values
906             #'(lambda (&rest args)
907                 (call-no-applicable-method gf args))
908             nil
909             (no-methods-dfun-info)))
910           ((setq type (final-accessor-dfun-type gf))
911            (make-final-accessor-dfun gf type classes-list new-class))
912           ((and (not (and (every (lambda (specl) (eq specl *the-class-t*))
913                                  (setq specls
914                                        (method-specializers (car methods))))
915                           (setq all-same-p
916                                 (every (lambda (method)
917                                          (and (equal specls
918                                                      (method-specializers
919                                                       method))))
920                                        methods))))
921                 (use-constant-value-dfun-p gf))
922            (make-final-constant-value-dfun gf classes-list new-class))
923           ((use-dispatch-dfun-p gf)
924            (make-final-dispatch-dfun gf))
925           ((and all-same-p (not (use-caching-dfun-p gf)))
926            (let ((emf (get-secondary-dispatch-function gf methods nil)))
927              (make-final-checking-dfun gf emf classes-list new-class)))
928           (t
929            (make-final-caching-dfun gf classes-list new-class)))))
930
931 (defvar *pcl-misc-random-state* (make-random-state))
932
933 (defun accessor-miss (gf new object dfun-info)
934   (let* ((ostate (type-of dfun-info))
935          (otype (dfun-info-accessor-type dfun-info))
936          oindex ow0 ow1 cache
937          (args (ecase otype
938                  ((reader boundp) (list object))
939                  (writer (list new object)))))
940     (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
941       ;; The following lexical functions change the state of the
942       ;; dfun to that which is their name.  They accept arguments
943       ;; which are the parameters of the new state, and get other
944       ;; information from the lexical variables bound above.
945       (flet ((two-class (index w0 w1)
946                (when (zerop (random 2 *pcl-misc-random-state*))
947                  (psetf w0 w1 w1 w0))
948                (dfun-update gf
949                             #'make-two-class-accessor-dfun
950                             ntype
951                             w0
952                             w1
953                             index))
954              (one-index (index &optional cache)
955                (dfun-update gf
956                             #'make-one-index-accessor-dfun
957                             ntype
958                             index
959                             cache))
960              (n-n (&optional cache)
961                (if (consp nindex)
962                    (dfun-update gf #'make-checking-dfun nemf)
963                    (dfun-update gf #'make-n-n-accessor-dfun ntype cache)))
964              (caching () ; because cached accessor emfs are much faster
965                          ; for accessors
966                (dfun-update gf #'make-caching-dfun))
967              (do-fill (update-fn)
968                (let ((ncache (fill-cache cache wrappers nindex)))
969                  (unless (eq ncache cache)
970                    (funcall update-fn ncache)))))
971         (cond ((null ntype)
972                (caching))
973               ((or invalidp
974                    (null nindex)))
975               ((not (pcl-instance-p object))
976                (caching))
977               ((or (neq ntype otype) (listp wrappers))
978                (caching))
979               (t
980                (ecase ostate
981                  (one-class
982                   (setq oindex (dfun-info-index dfun-info))
983                   (setq ow0 (dfun-info-wrapper0 dfun-info))
984                   (unless (eq ow0 wrappers)
985                     (if (eql nindex oindex)
986                         (two-class nindex ow0 wrappers)
987                         (n-n))))
988                  (two-class
989                   (setq oindex (dfun-info-index dfun-info))
990                   (setq ow0 (dfun-info-wrapper0 dfun-info))
991                   (setq ow1 (dfun-info-wrapper1 dfun-info))
992                   (unless (or (eq ow0 wrappers) (eq ow1 wrappers))
993                     (if (eql nindex oindex)
994                         (one-index nindex)
995                         (n-n))))
996                  (one-index
997                   (setq oindex (dfun-info-index dfun-info))
998                   (setq cache (dfun-info-cache dfun-info))
999                   (if (eql nindex oindex)
1000                       (do-fill (lambda (ncache)
1001                                  (one-index nindex ncache)))
1002                       (n-n)))
1003                  (n-n
1004                   (setq cache (dfun-info-cache dfun-info))
1005                   (if (consp nindex)
1006                       (caching)
1007                       (do-fill #'n-n))))))))))
1008
1009 (defun checking-miss (generic-function args dfun-info)
1010   (let ((oemf (dfun-info-function dfun-info))
1011         (cache (dfun-info-cache dfun-info)))
1012     (dfun-miss (generic-function args wrappers invalidp nemf)
1013       (cond (invalidp)
1014             ((eq oemf nemf)
1015              ;; The cache of a checking dfun doesn't hold any values,
1016              ;; so this NIL appears to be just a dummy-value we use in
1017              ;; order to insert the wrappers into the cache.
1018              (let ((ncache (fill-cache cache wrappers nil)))
1019                (unless (eq ncache cache)
1020                  (dfun-update generic-function #'make-checking-dfun
1021                               nemf ncache))))
1022             (t
1023              (dfun-update generic-function #'make-caching-dfun))))))
1024
1025 (defun caching-miss (generic-function args dfun-info)
1026   (let ((ocache (dfun-info-cache dfun-info)))
1027     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
1028       (cond (invalidp)
1029             (t
1030              (let ((ncache (fill-cache ocache wrappers emf)))
1031                (unless (eq ncache ocache)
1032                  (dfun-update generic-function
1033                               #'make-caching-dfun ncache))))))))
1034
1035 (defun constant-value-miss (generic-function args dfun-info)
1036   (let ((ocache (dfun-info-cache dfun-info)))
1037     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
1038       (unless invalidp
1039         (let* ((value
1040                 (typecase emf
1041                   (constant-fast-method-call
1042                    (constant-fast-method-call-value emf))
1043                   (constant-method-call
1044                    (constant-method-call-value emf))
1045                   (t
1046                    (bug "~S with non-constant EMF ~S" 'constant-value-miss emf))))
1047                (ncache (fill-cache ocache wrappers value)))
1048           (unless (eq ncache ocache)
1049             (dfun-update generic-function
1050                          #'make-constant-value-dfun ncache)))))))
1051 \f
1052 ;;; Given a generic function and a set of arguments to that generic
1053 ;;; function, return a mess of values.
1054 ;;;
1055 ;;;  <function>   The compiled effective method function for this set of
1056 ;;;            arguments.
1057 ;;;
1058 ;;;  <applicable> Sorted list of applicable methods.
1059 ;;;
1060 ;;;  <wrappers>   Is a single wrapper if the generic function has only
1061 ;;;            one key, that is arg-info-nkeys of the arg-info is 1.
1062 ;;;            Otherwise a list of the wrappers of the specialized
1063 ;;;            arguments to the generic function.
1064 ;;;
1065 ;;;            Note that all these wrappers are valid. This function
1066 ;;;            does invalid wrapper traps when it finds an invalid
1067 ;;;            wrapper and then returns the new, valid wrapper.
1068 ;;;
1069 ;;;  <invalidp>   True if any of the specialized arguments had an invalid
1070 ;;;            wrapper, false otherwise.
1071 ;;;
1072 ;;;  <type>       READER or WRITER when the only method that would be run
1073 ;;;            is a standard reader or writer method. To be specific,
1074 ;;;            the value is READER when the method combination is eq to
1075 ;;;            *standard-method-combination*; there are no applicable
1076 ;;;            :before, :after or :around methods; and the most specific
1077 ;;;            primary method is a standard reader method.
1078 ;;;
1079 ;;;  <index>      If <type> is READER or WRITER, and the slot accessed is
1080 ;;;            an :instance slot, this is the index number of that slot
1081 ;;;            in the object argument.
1082 (defvar *cache-miss-values-stack* ())
1083
1084 (defun cache-miss-values (gf args state)
1085   (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1086       (get-generic-fun-info gf)
1087     (declare (ignore nreq applyp nkeys))
1088     (with-dfun-wrappers (args metatypes)
1089       (dfun-wrappers invalid-wrapper-p wrappers classes types)
1090       (error-need-at-least-n-args gf (length metatypes))
1091       (multiple-value-bind (emf methods accessor-type index)
1092           (cache-miss-values-internal
1093            gf arg-info wrappers classes types state)
1094         (values emf methods
1095                 dfun-wrappers
1096                 invalid-wrapper-p
1097                 accessor-type index)))))
1098
1099 (defun cache-miss-values-internal (gf arg-info wrappers classes types state)
1100   (if (and classes (equal classes (cdr (assq gf *cache-miss-values-stack*))))
1101       (break-vicious-metacircle gf classes arg-info)
1102       (let ((*cache-miss-values-stack*
1103              (acons gf classes *cache-miss-values-stack*))
1104             (cam-std-p (or (null arg-info)
1105                            (gf-info-c-a-m-emf-std-p arg-info))))
1106         (multiple-value-bind (methods all-applicable-and-sorted-p)
1107             (if cam-std-p
1108                 (compute-applicable-methods-using-types gf types)
1109                 (compute-applicable-methods-using-classes gf classes))
1110
1111   (let* ((for-accessor-p (eq state 'accessor))
1112          (for-cache-p (or (eq state 'caching) (eq state 'accessor)))
1113          (emf (if (or cam-std-p all-applicable-and-sorted-p)
1114                   (let ((generator
1115                          (get-secondary-dispatch-function1
1116                           gf methods types nil (and for-cache-p wrappers)
1117                           all-applicable-and-sorted-p)))
1118                     (make-callable gf methods generator
1119                                    nil (and for-cache-p wrappers)))
1120                   (default-secondary-dispatch-function gf))))
1121     (multiple-value-bind (index accessor-type)
1122         (and for-accessor-p all-applicable-and-sorted-p methods
1123              (accessor-values gf arg-info classes methods))
1124       (values (if (integerp index) index emf)
1125               methods accessor-type index)))))))
1126
1127 ;;; Try to break a vicious circle while computing a cache miss.
1128 ;;; GF is the generic function, CLASSES are the classes of actual
1129 ;;; arguments, and ARG-INFO is the generic functions' arg-info.
1130 ;;;
1131 ;;; A vicious circle can be entered when the computation of the cache
1132 ;;; miss values itself depends on the values being computed.  For
1133 ;;; instance, adding a method which is an instance of a subclass of
1134 ;;; STANDARD-METHOD leads to cache misses for slot accessors of
1135 ;;; STANDARD-METHOD like METHOD-SPECIALIZERS, and METHOD-SPECIALIZERS
1136 ;;; is itself used while we compute cache miss values.
1137 (defun break-vicious-metacircle (gf classes arg-info)
1138   (when (typep gf 'standard-generic-function)
1139     (multiple-value-bind (class slotd accessor-type)
1140         (accesses-standard-class-slot-p gf)
1141       (when class
1142         (let ((method (find-standard-class-accessor-method
1143                        gf class accessor-type))
1144               (index (standard-slot-value/eslotd slotd 'location))
1145               (type (gf-info-simple-accessor-type arg-info)))
1146           (when (and method
1147                      (subtypep (ecase accessor-type
1148                                  ((reader) (car classes))
1149                                  ((writer) (cadr classes)))
1150                                class))
1151             (return-from break-vicious-metacircle
1152               (values index (list method) type index)))))))
1153   (error "~@<vicious metacircle:  The computation of an ~
1154           effective method of ~s for arguments of types ~s uses ~
1155           the effective method being computed.~@:>"
1156          gf classes))
1157
1158 ;;; Return (CLASS SLOTD ACCESSOR-TYPE) if some method of generic
1159 ;;; function GF accesses a slot of some class in *STANDARD-CLASSES*.
1160 ;;; CLASS is the class accessed, SLOTD is the effective slot definition
1161 ;;; object of the slot accessed, and ACCESSOR-TYPE is one of the symbols
1162 ;;; READER or WRITER describing the slot access.
1163 (defun accesses-standard-class-slot-p (gf)
1164   (flet ((standard-class-slot-access (gf class)
1165            (loop with gf-name = (standard-slot-value/gf gf 'name)
1166                  for slotd in (standard-slot-value/class class 'slots)
1167                  ;; FIXME: where does BOUNDP fit in here?  Is it
1168                  ;; relevant?
1169                  as readers = (standard-slot-value/eslotd slotd 'readers)
1170                  as writers = (standard-slot-value/eslotd slotd 'writers)
1171                  if (member gf-name readers :test #'equal)
1172                    return (values slotd 'reader)
1173                  else if (member gf-name writers :test #'equal)
1174                    return (values slotd 'writer))))
1175     (dolist (class-name *standard-classes*)
1176       (let ((class (find-class class-name)))
1177         (multiple-value-bind (slotd accessor-type)
1178             (standard-class-slot-access gf class)
1179           (when slotd
1180             (return (values class slotd accessor-type))))))))
1181
1182 ;;; Find a slot reader/writer method among the methods of generic
1183 ;;; function GF which reads/writes instances of class CLASS.
1184 ;;; TYPE is one of the symbols READER or WRITER.
1185 (defun find-standard-class-accessor-method (gf class type)
1186   (let ((cpl (standard-slot-value/class class '%class-precedence-list))
1187         (found-specializer *the-class-t*)
1188         (found-method nil))
1189     (dolist (method (standard-slot-value/gf gf 'methods) found-method)
1190       (let ((specializers (standard-slot-value/method method 'specializers))
1191             (qualifiers (standard-slot-value/method method 'qualifiers)))
1192         (when (and (null qualifiers)
1193                    (let ((subcpl (member (ecase type
1194                                            (reader (car specializers))
1195                                            (writer (cadr specializers)))
1196                                          cpl :test #'eq)))
1197                      (and subcpl (member found-specializer subcpl :test #'eq))))
1198           (setf found-specializer (ecase type
1199                                     (reader (car specializers))
1200                                     (writer (cadr specializers))))
1201           (setf found-method method))))))
1202
1203 (defun accessor-values (gf arg-info classes methods)
1204   (declare (ignore gf))
1205   (let* ((accessor-type (gf-info-simple-accessor-type arg-info))
1206          (accessor-class (case accessor-type
1207                            ((reader boundp) (car classes))
1208                            (writer (cadr classes)))))
1209     (accessor-values-internal accessor-type accessor-class methods)))
1210
1211 (defun accessor-values1 (gf accessor-type accessor-class)
1212   (let* ((type `(class-eq ,accessor-class))
1213          (types (ecase accessor-type
1214                   ((reader boundp) `(,type))
1215                   (writer `(t ,type))))
1216          (methods (compute-applicable-methods-using-types gf types)))
1217     (accessor-values-internal accessor-type accessor-class methods)))
1218
1219 (defun accessor-values-internal (accessor-type accessor-class methods)
1220   (dolist (meth methods)
1221     (when (if (consp meth)
1222               (early-method-qualifiers meth)
1223               (safe-method-qualifiers meth))
1224       (return-from accessor-values-internal (values nil nil))))
1225   (let* ((meth (car methods))
1226          (early-p (not (eq **boot-state** 'complete)))
1227          (slot-name (when accessor-class
1228                       (if (consp meth)
1229                           (and (early-method-standard-accessor-p meth)
1230                                (early-method-standard-accessor-slot-name meth))
1231                           (and (member *the-class-standard-object*
1232                                        (if early-p
1233                                            (early-class-precedence-list
1234                                             accessor-class)
1235                                            (class-precedence-list
1236                                             accessor-class))
1237                                        :test #'eq)
1238                                (accessor-method-p meth)
1239                                (accessor-method-slot-name meth)))))
1240          (slotd (and accessor-class
1241                      (if early-p
1242                          (dolist (slot (early-class-slotds accessor-class) nil)
1243                            (when (eql slot-name
1244                                       (early-slot-definition-name slot))
1245                              (return slot)))
1246                          (find-slot-definition accessor-class slot-name)))))
1247     (when (and slotd
1248                (or early-p
1249                    (slot-accessor-std-p slotd accessor-type))
1250                (or early-p
1251                    (not (safe-p accessor-class))))
1252       (values (if early-p
1253                   (early-slot-definition-location slotd)
1254                   (slot-definition-location slotd))
1255               accessor-type))))
1256
1257 (defun make-accessor-table (gf type &optional table)
1258   (unless table (setq table (make-hash-table :test 'eq)))
1259   (let ((methods (if (early-gf-p gf)
1260                      (early-gf-methods gf)
1261                      (generic-function-methods gf)))
1262         (all-index nil)
1263         (no-class-slots-p t)
1264         (early-p (not (eq **boot-state** 'complete)))
1265         first second (size 0))
1266     (declare (fixnum size))
1267     ;; class -> {(specl slotd)}
1268     (dolist (method methods)
1269       (let* ((specializers (if (consp method)
1270                                (early-method-specializers method t)
1271                                (method-specializers method)))
1272              (specl (ecase type
1273                       ((reader boundp) (car specializers))
1274                       (writer (cadr specializers))))
1275              (specl-cpl (if early-p
1276                             (early-class-precedence-list specl)
1277                             (when (class-finalized-p specl)
1278                               (class-precedence-list specl))))
1279              (so-p (member *the-class-standard-object* specl-cpl :test #'eq))
1280              (slot-name (if (consp method)
1281                             (and (early-method-standard-accessor-p method)
1282                                  (early-method-standard-accessor-slot-name
1283                                   method))
1284                             (accessor-method-slot-name method))))
1285         (when (or (null specl-cpl)
1286                   (null so-p)
1287                   (member *the-class-structure-object* specl-cpl :test #'eq))
1288           (return-from make-accessor-table nil))
1289         ;; Collect all the slot-definitions for SLOT-NAME from SPECL and
1290         ;; all of its subclasses. If either SPECL or one of the subclasses
1291         ;; is not a standard-class, bail out.
1292         (labels ((aux (class)
1293                    (let ((slotd (find-slot-definition class slot-name)))
1294                      (when slotd
1295                        (unless (or early-p (slot-accessor-std-p slotd type))
1296                          (return-from make-accessor-table nil))
1297                        (push (cons specl slotd) (gethash class table))))
1298                    (dolist (subclass (sb-pcl::class-direct-subclasses class))
1299                      (unless (class-finalized-p subclass)
1300                        (return-from make-accessor-table nil))
1301                      (aux subclass))))
1302           (aux specl))))
1303     (maphash (lambda (class specl+slotd-list)
1304                (dolist (sclass (if early-p
1305                                    (early-class-precedence-list class)
1306                                    (class-precedence-list class))
1307                                (error "This can't happen."))
1308                  (let ((a (assq sclass specl+slotd-list)))
1309                    (when a
1310                      (let* ((slotd (cdr a))
1311                             (index (if early-p
1312                                        (early-slot-definition-location slotd)
1313                                        (slot-definition-location slotd))))
1314                        (unless index (return-from make-accessor-table nil))
1315                        (setf (gethash class table) index)
1316                        (when (consp index) (setq no-class-slots-p nil))
1317                        (setq all-index (if (or (null all-index)
1318                                                (eql all-index index))
1319                                            index t))
1320                        (incf size)
1321                        (cond ((= size 1) (setq first class))
1322                              ((= size 2) (setq second class)))
1323                        (return nil))))))
1324              table)
1325     (values table all-index first second size no-class-slots-p)))
1326
1327 (defun compute-applicable-methods-using-types (generic-function types)
1328   (let ((definite-p t) (possibly-applicable-methods nil))
1329     (dolist (method (if (early-gf-p generic-function)
1330                         (early-gf-methods generic-function)
1331                         (safe-generic-function-methods generic-function)))
1332       (let ((specls (if (consp method)
1333                         (early-method-specializers method t)
1334                         (safe-method-specializers method)))
1335             (types types)
1336             (possibly-applicable-p t) (applicable-p t))
1337         (dolist (specl specls)
1338           (multiple-value-bind (specl-applicable-p specl-possibly-applicable-p)
1339               (specializer-applicable-using-type-p specl (pop types))
1340             (unless specl-applicable-p
1341               (setq applicable-p nil))
1342             (unless specl-possibly-applicable-p
1343               (setq possibly-applicable-p nil)
1344               (return nil))))
1345         (when possibly-applicable-p
1346           (unless applicable-p (setq definite-p nil))
1347           (push method possibly-applicable-methods))))
1348     (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1349         (get-generic-fun-info generic-function)
1350       (declare (ignore nreq applyp metatypes nkeys))
1351       (let* ((precedence (arg-info-precedence arg-info)))
1352         (values (sort-applicable-methods precedence
1353                                          (nreverse possibly-applicable-methods)
1354                                          types)
1355                 definite-p)))))
1356
1357 (defun sort-applicable-methods (precedence methods types)
1358   (sort-methods methods
1359                 precedence
1360                 (lambda (class1 class2 index)
1361                   (let* ((class (type-class (nth index types)))
1362                          (cpl (if (eq **boot-state** 'complete)
1363                                   (class-precedence-list class)
1364                                   (early-class-precedence-list class))))
1365                     (if (memq class2 (memq class1 cpl))
1366                         class1 class2)))))
1367
1368 (defun sort-methods (methods precedence compare-classes-function)
1369   (flet ((sorter (method1 method2)
1370            (dolist (index precedence)
1371              (let* ((specl1 (nth index (if (listp method1)
1372                                            (early-method-specializers method1
1373                                                                       t)
1374                                            (method-specializers method1))))
1375                     (specl2 (nth index (if (listp method2)
1376                                            (early-method-specializers method2
1377                                                                       t)
1378                                            (method-specializers method2))))
1379                     (order (order-specializers
1380                              specl1 specl2 index compare-classes-function)))
1381                (when order
1382                  (return-from sorter (eq order specl1)))))))
1383     (stable-sort methods #'sorter)))
1384
1385 (defun order-specializers (specl1 specl2 index compare-classes-function)
1386   (let ((type1 (if (eq **boot-state** 'complete)
1387                    (specializer-type specl1)
1388                    (!bootstrap-get-slot 'specializer specl1 '%type)))
1389         (type2 (if (eq **boot-state** 'complete)
1390                    (specializer-type specl2)
1391                    (!bootstrap-get-slot 'specializer specl2 '%type))))
1392     (cond ((eq specl1 specl2)
1393            nil)
1394           ((atom type1)
1395            specl2)
1396           ((atom type2)
1397            specl1)
1398           (t
1399            (case (car type1)
1400              (class    (case (car type2)
1401                          (class (funcall compare-classes-function
1402                                          specl1 specl2 index))
1403                          (t specl2)))
1404              (prototype (case (car type2)
1405                          (class (funcall compare-classes-function
1406                                          specl1 specl2 index))
1407                          (t specl2)))
1408              (class-eq (case (car type2)
1409                          (eql specl2)
1410                          ;; FIXME: This says that all CLASS-EQ
1411                          ;; specializers are equally specific, which
1412                          ;; is fair enough because only one CLASS-EQ
1413                          ;; specializer can ever be appliable.  If
1414                          ;; ORDER-SPECIALIZERS should only ever be
1415                          ;; called on specializers from applicable
1416                          ;; methods, we could replace this with a BUG.
1417                          (class-eq nil)
1418                          (class type1)))
1419              (eql      (case (car type2)
1420                          ;; similarly.
1421                          (eql nil)
1422                          (t specl1))))))))
1423
1424 (defun map-all-orders (methods precedence function)
1425   (let ((choices nil))
1426     (flet ((compare-classes-function (class1 class2 index)
1427              (declare (ignore index))
1428              (let ((choice nil))
1429                (dolist (c choices nil)
1430                  (when (or (and (eq (first c) class1)
1431                                 (eq (second c) class2))
1432                            (and (eq (first c) class2)
1433                                 (eq (second c) class1)))
1434                    (return (setq choice c))))
1435                (unless choice
1436                  (setq choice
1437                        (if (class-might-precede-p class1 class2)
1438                            (if (class-might-precede-p class2 class1)
1439                                (list class1 class2 nil t)
1440                                (list class1 class2 t))
1441                            (if (class-might-precede-p class2 class1)
1442                                (list class2 class1 t)
1443                                (let ((name1 (class-name class1))
1444                                      (name2 (class-name class2)))
1445                                  (if (and name1
1446                                           name2
1447                                           (symbolp name1)
1448                                           (symbolp name2)
1449                                           (string< (symbol-name name1)
1450                                                    (symbol-name name2)))
1451                                      (list class1 class2 t)
1452                                      (list class2 class1 t))))))
1453                  (push choice choices))
1454                (car choice))))
1455       (loop (funcall function
1456                      (sort-methods methods
1457                                    precedence
1458                                    #'compare-classes-function))
1459             (unless (dolist (c choices nil)
1460                       (unless (third c)
1461                         (rotatef (car c) (cadr c))
1462                         (return (setf (third c) t))))
1463               (return nil))))))
1464
1465 ;;; CMUCL comment: used only in map-all-orders
1466 (defun class-might-precede-p (class1 class2)
1467   (if (not *in-precompute-effective-methods-p*)
1468       (not (member class1 (cdr (class-precedence-list class2)) :test #'eq))
1469       (class-can-precede-p class1 class2)))
1470
1471 (defun compute-precedence (lambda-list nreq argument-precedence-order)
1472   (if (null argument-precedence-order)
1473       (let ((list nil))
1474         (dotimes-fixnum (i nreq list) (push (- (1- nreq) i) list)))
1475       (mapcar (lambda (x) (position x lambda-list))
1476               argument-precedence-order)))
1477
1478 (defun cpl-or-nil (class)
1479   (if (eq **boot-state** 'complete)
1480       (progn
1481         ;; KLUDGE: why not use (slot-boundp class
1482         ;; 'class-precedence-list)?  Well, unfortunately, CPL-OR-NIL is
1483         ;; used within COMPUTE-APPLICABLE-METHODS, including for
1484         ;; SLOT-BOUNDP-USING-CLASS... and the available mechanism for
1485         ;; breaking such nasty cycles in effective method computation
1486         ;; only works for readers and writers, not boundps.  It might
1487         ;; not be too hard to make it work for BOUNDP accessors, but in
1488         ;; the meantime we use an extra slot for exactly the result of
1489         ;; the SLOT-BOUNDP that we want.  (We cannot use
1490         ;; CLASS-FINALIZED-P, because in the process of class
1491         ;; finalization we need to use the CPL which has been computed
1492         ;; to cache effective methods for slot accessors.) -- CSR,
1493         ;; 2004-09-19.
1494
1495         (when (cpl-available-p class)
1496           (return-from cpl-or-nil (class-precedence-list class)))
1497
1498         ;; if we can finalize an unfinalized class, then do so
1499         (when (and (not (class-finalized-p class))
1500                    (not (class-has-a-forward-referenced-superclass-p class)))
1501           (finalize-inheritance class)
1502           (class-precedence-list class)))
1503
1504       (early-class-precedence-list class)))
1505
1506 (defun saut-and (specl type)
1507   (let ((applicable nil)
1508         (possibly-applicable t))
1509     (dolist (type (cdr type))
1510       (multiple-value-bind (appl poss-appl)
1511           (specializer-applicable-using-type-p specl type)
1512         (when appl (return (setq applicable t)))
1513         (unless poss-appl (return (setq possibly-applicable nil)))))
1514     (values applicable possibly-applicable)))
1515
1516 (defun saut-not (specl type)
1517   (let ((ntype (cadr type)))
1518     (values nil
1519             (case (car ntype)
1520               (class      (saut-not-class specl ntype))
1521               (class-eq   (saut-not-class-eq specl ntype))
1522               (prototype  (saut-not-prototype specl ntype))
1523               (eql      (saut-not-eql specl ntype))
1524               (t (error "~S cannot handle the second argument ~S"
1525                         'specializer-applicable-using-type-p type))))))
1526
1527 (defun saut-not-class (specl ntype)
1528   (let* ((class (type-class specl))
1529          (cpl (cpl-or-nil class)))
1530     (not (memq (cadr ntype) cpl))))
1531
1532 (defun saut-not-prototype (specl ntype)
1533   (let* ((class (case (car specl)
1534                   (eql       (class-of (cadr specl)))
1535                   (class-eq  (cadr specl))
1536                   (prototype (cadr specl))
1537                   (class     (cadr specl))))
1538          (cpl (cpl-or-nil class)))
1539     (not (memq (cadr ntype) cpl))))
1540
1541 (defun saut-not-class-eq (specl ntype)
1542   (let ((class (case (car specl)
1543                  (eql      (class-of (cadr specl)))
1544                  (class-eq (cadr specl)))))
1545     (not (eq class (cadr ntype)))))
1546
1547 (defun saut-not-eql (specl ntype)
1548   (case (car specl)
1549     (eql (not (eql (cadr specl) (cadr ntype))))
1550     (t   t)))
1551
1552 (defun class-applicable-using-class-p (specl type)
1553   (let ((pred (memq specl (cpl-or-nil type))))
1554     (values pred
1555             (or pred
1556                 (if (not *in-precompute-effective-methods-p*)
1557                     ;; classes might get common subclass
1558                     (superclasses-compatible-p specl type)
1559                     ;; worry only about existing classes
1560                     (classes-have-common-subclass-p specl type))))))
1561
1562 (defun classes-have-common-subclass-p (class1 class2)
1563   (or (eq class1 class2)
1564       (let ((class1-subs (class-direct-subclasses class1)))
1565         (or (memq class2 class1-subs)
1566             (dolist (class1-sub class1-subs nil)
1567               (when (classes-have-common-subclass-p class1-sub class2)
1568                 (return t)))))))
1569
1570 (defun saut-class (specl type)
1571   (case (car specl)
1572     (class (class-applicable-using-class-p (cadr specl) (cadr type)))
1573     (t     (values nil (let ((class (type-class specl)))
1574                          (memq (cadr type)
1575                                (cpl-or-nil class)))))))
1576
1577 (defun saut-class-eq (specl type)
1578   (if (eq (car specl) 'eql)
1579       (values nil (eq (class-of (cadr specl)) (cadr type)))
1580       (let ((pred (case (car specl)
1581                     (class-eq
1582                      (eq (cadr specl) (cadr type)))
1583                     (class
1584                      (or (eq (cadr specl) (cadr type))
1585                          (memq (cadr specl) (cpl-or-nil (cadr type))))))))
1586         (values pred pred))))
1587
1588 (defun saut-prototype (specl type)
1589   (declare (ignore specl type))
1590   (values nil nil)) ; XXX original PCL comment: fix this someday
1591
1592 (defun saut-eql (specl type)
1593   (let ((pred (case (car specl)
1594                 (eql    (eql (cadr specl) (cadr type)))
1595                 (class-eq   (eq (cadr specl) (class-of (cadr type))))
1596                 (class      (memq (cadr specl)
1597                                   (let ((class (class-of (cadr type))))
1598                                     (cpl-or-nil class)))))))
1599     (values pred pred)))
1600
1601 (defun specializer-applicable-using-type-p (specl type)
1602   (setq specl (type-from-specializer specl))
1603   (when (eq specl t)
1604     (return-from specializer-applicable-using-type-p (values t t)))
1605   ;; This is used by C-A-M-U-T and GENERATE-DISCRIMINATION-NET-INTERNAL,
1606   ;; and has only what they need.
1607   (if (or (atom type) (eq (car type) t))
1608       (values nil t)
1609       (case (car type)
1610         (and    (saut-and specl type))
1611         (not    (saut-not specl type))
1612         (class      (saut-class specl type))
1613         (prototype  (saut-prototype specl type))
1614         (class-eq   (saut-class-eq specl type))
1615         (eql    (saut-eql specl type))
1616         (t        (error "~S cannot handle the second argument ~S."
1617                            'specializer-applicable-using-type-p
1618                            type)))))
1619
1620 (defun map-all-classes (fun &optional (root t))
1621   (let ((all-classes (make-hash-table :test 'eq))
1622         (braid-p (or (eq **boot-state** 'braid)
1623                      (eq **boot-state** 'complete))))
1624     (labels ((do-class (class)
1625                (unless (gethash class all-classes)
1626                  (setf (gethash class all-classes) t)
1627                  (funcall fun class)
1628                  (mapc #'do-class
1629                        (if braid-p
1630                            (class-direct-subclasses class)
1631                            (early-class-direct-subclasses class))))))
1632       (do-class (if (symbolp root)
1633                     (find-class root)
1634                     root)))
1635     nil))
1636 \f
1637 ;;; Not synchronized, as all the uses we have for it are multiple ones
1638 ;;; and need WITH-LOCKED-HASH-TABLE in any case.
1639 ;;;
1640 ;;; FIXME: Is it really more efficient to store this stuff in a global
1641 ;;; table instead of having a slot in each method?
1642 ;;;
1643 ;;; FIXME: This table also seems to contain early methods, which should
1644 ;;; presumably be dropped during the bootstrap.
1645 (defvar *effective-method-cache* (make-hash-table :test 'eq))
1646
1647 (defun flush-effective-method-cache (generic-function)
1648   (let ((cache *effective-method-cache*))
1649     (with-locked-hash-table (cache)
1650       (dolist (method (generic-function-methods generic-function))
1651         (remhash method cache)))))
1652
1653 (defun get-secondary-dispatch-function (gf methods types
1654                                         &optional method-alist wrappers)
1655   (let ((generator
1656          (get-secondary-dispatch-function1
1657           gf methods types (not (null method-alist)) (not (null wrappers))
1658           (not (methods-contain-eql-specializer-p methods)))))
1659     (make-callable gf methods generator method-alist wrappers)))
1660
1661 (defun get-secondary-dispatch-function1 (gf methods types method-alist-p
1662                                             wrappers-p
1663                                             &optional
1664                                             all-applicable-p
1665                                             (all-sorted-p t)
1666                                             function-p)
1667    (if (null methods)
1668       (lambda (method-alist wrappers)
1669         (declare (ignore method-alist wrappers))
1670         (lambda (&rest args)
1671           (call-no-applicable-method gf args)))
1672       (let* ((key (car methods))
1673              (ht *effective-method-cache*)
1674              (ht-value (with-locked-hash-table (ht)
1675                          (or (gethash key ht)
1676                              (setf (gethash key ht) (cons nil nil))))))
1677         (if (and (null (cdr methods)) all-applicable-p ; the most common case
1678                  (null method-alist-p) wrappers-p (not function-p))
1679             (or (car ht-value)
1680                 (setf (car ht-value)
1681                       (get-secondary-dispatch-function2
1682                        gf methods types method-alist-p wrappers-p
1683                        all-applicable-p all-sorted-p function-p)))
1684             (let ((akey (list methods
1685                               (if all-applicable-p 'all-applicable types)
1686                               method-alist-p wrappers-p function-p)))
1687               (or (cdr (assoc akey (cdr ht-value) :test #'equal))
1688                   (let ((value (get-secondary-dispatch-function2
1689                                 gf methods types method-alist-p wrappers-p
1690                                 all-applicable-p all-sorted-p function-p)))
1691                     (push (cons akey value) (cdr ht-value))
1692                     value)))))))
1693
1694 (defun get-secondary-dispatch-function2 (gf methods types method-alist-p
1695                                             wrappers-p all-applicable-p
1696                                             all-sorted-p function-p)
1697   (if (and all-applicable-p all-sorted-p (not function-p))
1698       (if (eq **boot-state** 'complete)
1699           (let* ((combin (generic-function-method-combination gf))
1700                  (effective (compute-effective-method gf combin methods)))
1701             (make-effective-method-function1 gf effective method-alist-p
1702                                              wrappers-p))
1703           (let ((effective (standard-compute-effective-method gf nil methods)))
1704             (make-effective-method-function1 gf effective method-alist-p
1705                                              wrappers-p)))
1706       (let ((net (generate-discrimination-net
1707                   gf methods types all-sorted-p)))
1708         (compute-secondary-dispatch-function1 gf net function-p))))
1709
1710 (defun get-effective-method-function (gf methods
1711                                          &optional method-alist wrappers)
1712   (let ((generator
1713          (get-secondary-dispatch-function1
1714           gf methods nil (not (null method-alist)) (not (null wrappers)) t)))
1715     (make-callable gf methods generator method-alist wrappers)))
1716
1717 (defun get-effective-method-function1 (gf methods &optional (sorted-p t))
1718   (get-secondary-dispatch-function1 gf methods nil nil nil t sorted-p))
1719
1720 (defun methods-contain-eql-specializer-p (methods)
1721   (and (eq **boot-state** 'complete)
1722        (dolist (method methods nil)
1723          (when (dolist (spec (method-specializers method) nil)
1724                  (when (eql-specializer-p spec) (return t)))
1725            (return t)))))
1726 \f
1727 (defun update-dfun (generic-function &optional dfun cache info)
1728   (let ((early-p (early-gf-p generic-function)))
1729     (flet ((update ()
1730              ;; Save DFUN-STATE, so that COMPUTE-DISCRIMINATING-FUNCTION can
1731              ;; access it, and so that it's there for eg. future cache updates.
1732              (set-dfun generic-function dfun cache info)
1733              (let ((dfun (if early-p
1734                              (or dfun (make-initial-dfun generic-function))
1735                              (compute-discriminating-function generic-function))))
1736                (set-funcallable-instance-function generic-function dfun)
1737                (let ((gf-name (if early-p
1738                                   (!early-gf-name generic-function)
1739                                   (generic-function-name generic-function))))
1740                  (set-fun-name generic-function gf-name)
1741                  dfun))))
1742       ;; This needs to be atomic per generic function, consider:
1743       ;;   1. T1 sets dfun-state to S1 and computes discr. fun using S1
1744       ;;   2. T2 sets dfun-state to S2 and computes discr. fun using S2
1745       ;;   3. T2 sets fin
1746       ;;   4. T1 sets fin
1747       ;; Oops: now dfun-state and fin don't match! Since just calling
1748       ;; a generic can cause the dispatch function to be updated we
1749       ;; need a lock here.
1750       ;;
1751       ;; We need to accept recursion, because PCL is nasty and twisty,
1752       ;; and we need to disable interrupts because it would be bad if
1753       ;; we updated the DFUN-STATE but not the dispatch function.
1754       ;;
1755       ;; This is sufficient, because all the other calls to SET-DFUN
1756       ;; are part of this same code path (done while the lock is held),
1757       ;; which we AVER.
1758       ;;
1759       ;; FIXME: When our mutexes are smart about the need to wake up
1760       ;; sleepers we can put a mutex here instead -- but in the meantime
1761       ;; we use a spinlock to avoid a syscall for every dfun update.
1762       ;;
1763       ;; KLUDGE: No need to lock during bootstrap.
1764       (if early-p
1765           (update)
1766           (let ((lock (gf-lock generic-function)))
1767             ;; FIXME: GF-LOCK is a generic function... Are there cases
1768             ;; where we can end up in a metacircular loop here? In
1769             ;; case there are, better fetch it while interrupts are
1770             ;; still enabled...
1771             (sb-thread::call-with-recursive-system-spinlock #'update lock))))))
1772 \f
1773 (defvar *dfun-count* nil)
1774 (defvar *dfun-list* nil)
1775 (defvar *minimum-cache-size-to-list*)
1776
1777 ;;; These functions aren't used in SBCL, or documented anywhere that
1778 ;;; I'm aware of, but they look like they might be useful for
1779 ;;; debugging or performance tweaking or something, so I've just
1780 ;;; commented them out instead of deleting them. -- WHN 2001-03-28
1781 #||
1782 (defun list-dfun (gf)
1783   (let* ((sym (type-of (gf-dfun-info gf)))
1784          (a (assq sym *dfun-list*)))
1785     (unless a
1786       (push (setq a (list sym)) *dfun-list*))
1787     (push (generic-function-name gf) (cdr a))))
1788
1789 (defun list-all-dfuns ()
1790   (setq *dfun-list* nil)
1791   (map-all-generic-functions #'list-dfun)
1792   *dfun-list*)
1793
1794 (defun list-large-cache (gf)
1795   (let* ((sym (type-of (gf-dfun-info gf)))
1796          (cache (gf-dfun-cache gf)))
1797     (when cache
1798       (let ((size (cache-size cache)))
1799         (when (>= size *minimum-cache-size-to-list*)
1800           (let ((a (assoc size *dfun-list*)))
1801             (unless a
1802               (push (setq a (list size)) *dfun-list*))
1803             (push (let ((name (generic-function-name gf)))
1804                     (if (eq sym 'caching) name (list name sym)))
1805                   (cdr a))))))))
1806
1807 (defun list-large-caches (&optional (*minimum-cache-size-to-list* 130))
1808   (setq *dfun-list* nil)
1809   (map-all-generic-functions #'list-large-cache)
1810   (setq *dfun-list* (sort *dfun-list* #'< :key #'car))
1811   (mapc #'print *dfun-list*)
1812   (values))
1813
1814 (defun count-dfun (gf)
1815   (let* ((sym (type-of (gf-dfun-info gf)))
1816          (cache (gf-dfun-cache gf))
1817          (a (assq sym *dfun-count*)))
1818     (unless a
1819       (push (setq a (list sym 0 nil)) *dfun-count*))
1820     (incf (cadr a))
1821     (when cache
1822       (let* ((size (cache-size cache))
1823              (b (assoc size (third a))))
1824         (unless b
1825           (push (setq b (cons size 0)) (third a)))
1826         (incf (cdr b))))))
1827
1828 (defun count-all-dfuns ()
1829   (setq *dfun-count* (mapcar (lambda (type) (list type 0 nil))
1830                              '(ONE-CLASS TWO-CLASS DEFAULT-METHOD-ONLY
1831                                ONE-INDEX N-N CHECKING CACHING
1832                                DISPATCH)))
1833   (map-all-generic-functions #'count-dfun)
1834   (mapc (lambda (type+count+sizes)
1835           (setf (third type+count+sizes)
1836                 (sort (third type+count+sizes) #'< :key #'car)))
1837         *dfun-count*)
1838   (mapc (lambda (type+count+sizes)
1839           (format t "~&There are ~W dfuns of type ~S."
1840                   (cadr type+count+sizes) (car type+count+sizes))
1841           (format t "~%   ~S~%" (caddr type+count+sizes)))
1842         *dfun-count*)
1843   (values))
1844 ||#
1845
1846 (defun gfs-of-type (type)
1847   (unless (consp type) (setq type (list type)))
1848   (let ((gf-list nil))
1849     (map-all-generic-functions (lambda (gf)
1850                                  (when (memq (type-of (gf-dfun-info gf))
1851                                              type)
1852                                    (push gf gf-list))))
1853     gf-list))