0.7.10.31:
[sbcl.git] / src / pcl / methods.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 ;;; methods
28 ;;;
29 ;;; Methods themselves are simple inanimate objects. Most properties of
30 ;;; methods are immutable, methods cannot be reinitialized. The following
31 ;;; properties of methods can be changed:
32 ;;;   METHOD-GENERIC-FUNCTION
33 ;;;   METHOD-FUNCTION       ??
34
35 (defmethod method-function ((method standard-method))
36   (or (slot-value method 'function)
37       (let ((fmf (slot-value method 'fast-function)))
38         (unless fmf ; The :BEFORE SHARED-INITIALIZE method prevents this.
39           (error "~S doesn't seem to have a METHOD-FUNCTION." method))
40         (setf (slot-value method 'function)
41               (method-function-from-fast-function fmf)))))
42
43 (defmethod accessor-method-class ((method standard-accessor-method))
44   (car (slot-value method 'specializers)))
45
46 (defmethod accessor-method-class ((method standard-writer-method))
47   (cadr (slot-value method 'specializers)))
48
49 ;;; initialization
50 ;;;
51 ;;; Error checking is done in before methods. Because of the simplicity of
52 ;;; standard method objects the standard primary method can fill the slots.
53 ;;;
54 ;;; Methods are not reinitializable.
55
56 (defmethod reinitialize-instance ((method standard-method) &rest initargs)
57   (declare (ignore initargs))
58   (error "An attempt was made to reinitialize the method ~S.~%~
59           Method objects cannot be reinitialized."
60          method))
61
62 (defmethod legal-documentation-p ((object standard-method) x)
63   (if (or (null x) (stringp x))
64       t
65       "a string or NULL"))
66
67 (defmethod legal-lambda-list-p ((object standard-method) x)
68   (declare (ignore x))
69   t)
70
71 (defmethod legal-method-function-p ((object standard-method) x)
72   (if (functionp x)
73       t
74       "a function"))
75
76 (defmethod legal-qualifiers-p ((object standard-method) x)
77   (flet ((improper-list ()
78            (return-from legal-qualifiers-p "Is not a proper list.")))
79     (dolist-carefully (q x improper-list)
80       (let ((ok (legal-qualifier-p object q)))
81         (unless (eq ok t)
82           (return-from legal-qualifiers-p
83             (format nil "Contains ~S which ~A" q ok)))))
84     t))
85
86 (defmethod legal-qualifier-p ((object standard-method) x)
87   (if (and x (atom x))
88       t
89       "is not a non-null atom"))
90
91 (defmethod legal-slot-name-p ((object standard-method) x)
92   (cond ((not (symbolp x)) "is not a symbol and so cannot be bound")
93         ((keywordp x)      "is a keyword and so cannot be bound")
94         ((memq x '(t nil)) "cannot be bound")
95         ((constantp x)     "is a constant and so cannot be bound")
96         (t t)))
97
98 (defmethod legal-specializers-p ((object standard-method) x)
99   (flet ((improper-list ()
100            (return-from legal-specializers-p "Is not a proper list.")))
101     (dolist-carefully (s x improper-list)
102       (let ((ok (legal-specializer-p object s)))
103         (unless (eq ok t)
104           (return-from legal-specializers-p
105             (format nil "Contains ~S which ~A" s ok)))))
106     t))
107
108 (defvar *allow-experimental-specializers-p* nil)
109
110 (defmethod legal-specializer-p ((object standard-method) x)
111   (if (if *allow-experimental-specializers-p*
112           (specializerp x)
113           (or (classp x)
114               (eql-specializer-p x)))
115       t
116       "is neither a class object nor an EQL specializer"))
117
118 (defmethod shared-initialize :before ((method standard-method)
119                                       slot-names
120                                       &key qualifiers
121                                            lambda-list
122                                            specializers
123                                            function
124                                            fast-function
125                                            documentation)
126   (declare (ignore slot-names))
127   (flet ((lose (initarg value string)
128            (error "when initializing the method ~S:~%~
129                    The ~S initialization argument was: ~S.~%~
130                    which ~A."
131                   method initarg value string)))
132     (let ((check-qualifiers    (legal-qualifiers-p method qualifiers))
133           (check-lambda-list   (legal-lambda-list-p method lambda-list))
134           (check-specializers  (legal-specializers-p method specializers))
135           (check-fun (legal-method-function-p method
136                                               (or function
137                                                   fast-function)))
138           (check-documentation (legal-documentation-p method documentation)))
139       (unless (eq check-qualifiers t)
140         (lose :qualifiers qualifiers check-qualifiers))
141       (unless (eq check-lambda-list t)
142         (lose :lambda-list lambda-list check-lambda-list))
143       (unless (eq check-specializers t)
144         (lose :specializers specializers check-specializers))
145       (unless (eq check-fun t)
146         (lose :function function check-fun))
147       (unless (eq check-documentation t)
148         (lose :documentation documentation check-documentation)))))
149
150 (defmethod shared-initialize :before ((method standard-accessor-method)
151                                       slot-names
152                                       &key slot-name slot-definition)
153   (declare (ignore slot-names))
154   (unless slot-definition
155     (let ((legalp (legal-slot-name-p method slot-name)))
156       ;; FIXME: nasty convention; should be renamed to ILLEGAL-SLOT-NAME-P and
157       ;; ILLEGALP, and the convention redone to be less twisty
158       (unless (eq legalp t)
159         (error "The value of the :SLOT-NAME initarg ~A." legalp)))))
160
161 (defmethod shared-initialize :after ((method standard-method) slot-names
162                                      &rest initargs
163                                      &key qualifiers method-spec plist)
164   (declare (ignore slot-names method-spec plist))
165   (initialize-method-function initargs nil method)
166   (setf (plist-value method 'qualifiers) qualifiers)
167   #+ignore
168   (setf (slot-value method 'closure-generator)
169         (method-function-closure-generator (slot-value method 'function))))
170
171 (defmethod shared-initialize :after ((method standard-accessor-method)
172                                      slot-names
173                                      &key)
174   (declare (ignore slot-names))
175   (with-slots (slot-name slot-definition)
176     method
177     (unless slot-definition
178       (let ((class (accessor-method-class method)))
179         (when (slot-class-p class)
180           (setq slot-definition (find slot-name (class-direct-slots class)
181                                       :key #'slot-definition-name)))))
182     (when (and slot-definition (null slot-name))
183       (setq slot-name (slot-definition-name slot-definition)))))
184
185 (defmethod method-qualifiers ((method standard-method))
186   (plist-value method 'qualifiers))
187 \f
188 (defvar *the-class-generic-function*
189   (find-class 'generic-function))
190 (defvar *the-class-standard-generic-function*
191   (find-class 'standard-generic-function))
192 \f
193 (defmethod shared-initialize :before
194            ((generic-function standard-generic-function)
195             slot-names
196             &key (name nil namep)
197                  (lambda-list () lambda-list-p)
198                  argument-precedence-order
199                  declarations
200                  documentation
201                  (method-class nil method-class-supplied-p)
202                  (method-combination nil method-combination-supplied-p))
203   (declare (ignore slot-names
204                    declarations argument-precedence-order documentation
205                    lambda-list lambda-list-p))
206
207   (when namep
208     (set-fun-name generic-function name))
209
210   (flet ((initarg-error (initarg value string)
211            (error "when initializing the generic function ~S:~%~
212                    The ~S initialization argument was: ~A.~%~
213                    It must be ~A."
214                   generic-function initarg value string)))
215     (cond (method-class-supplied-p
216            (when (symbolp method-class)
217              (setq method-class (find-class method-class)))
218            (unless (and (classp method-class)
219                         (*subtypep (class-eq-specializer method-class)
220                                    *the-class-method*))
221              (initarg-error :method-class
222                             method-class
223                             "a subclass of the class METHOD"))
224            (setf (slot-value generic-function 'method-class) method-class))
225           ((slot-boundp generic-function 'method-class))
226           (t
227            (initarg-error :method-class
228                           "not supplied"
229                           "a subclass of the class METHOD")))
230     (cond (method-combination-supplied-p
231            (unless (method-combination-p method-combination)
232              (initarg-error :method-combination
233                             method-combination
234                             "a method combination object")))
235           ((slot-boundp generic-function 'method-combination))
236           (t
237            (initarg-error :method-combination
238                           "not supplied"
239                           "a method combination object")))))
240
241 #||
242 (defmethod reinitialize-instance ((generic-function standard-generic-function)
243                                   &rest initargs
244                                   &key name
245                                        lambda-list
246                                        argument-precedence-order
247                                        declarations
248                                        documentation
249                                        method-class
250                                        method-combination)
251   (declare (ignore documentation declarations argument-precedence-order
252                    lambda-list name method-class method-combination))
253   (macrolet ((add-initarg (check name slot-name)
254                `(unless ,check
255                   (push (slot-value generic-function ,slot-name) initargs)
256                   (push ,name initargs))))
257 ;   (add-initarg name :name 'name)
258 ;   (add-initarg lambda-list :lambda-list 'lambda-list)
259 ;   (add-initarg argument-precedence-order
260 ;                :argument-precedence-order
261 ;                'argument-precedence-order)
262 ;   (add-initarg declarations :declarations 'declarations)
263 ;   (add-initarg documentation :documentation 'documentation)
264 ;   (add-initarg method-class :method-class 'method-class)
265 ;   (add-initarg method-combination :method-combination 'method-combination)
266     (apply #'call-next-method generic-function initargs)))
267 ||#
268 \f
269 ;;; These three are scheduled for demolition.
270
271 (defmethod remove-named-method (generic-function-name argument-specifiers
272                                                       &optional extra)
273   (let ((generic-function ())
274         (method ()))
275     (cond ((or (null (fboundp generic-function-name))
276                (not (generic-function-p
277                       (setq generic-function
278                             (fdefinition generic-function-name)))))
279            (error "~S does not name a generic function."
280                   generic-function-name))
281           ((null (setq method (get-method generic-function
282                                           extra
283                                           (parse-specializers
284                                             argument-specifiers)
285                                           nil)))
286            (error "There is no method for the generic function ~S~%~
287                    which matches the ARGUMENT-SPECIFIERS ~S."
288                   generic-function
289                   argument-specifiers))
290           (t
291            (remove-method generic-function method)))))
292
293 (defun real-add-named-method (generic-function-name
294                               qualifiers
295                               specializers
296                               lambda-list
297                               &rest other-initargs)
298   (unless (and (fboundp generic-function-name)
299                (typep (fdefinition generic-function-name) 'generic-function))
300     (sb-kernel::style-warn "implicitly creating new generic function ~S"
301                            generic-function-name))
302   ;; XXX What about changing the class of the generic function if
303   ;; there is one? Whose job is that, anyway? Do we need something
304   ;; kind of like CLASS-FOR-REDEFINITION?
305   (let* ((generic-function
306            (ensure-generic-function generic-function-name))
307          (specs (parse-specializers specializers))
308          (proto (method-prototype-for-gf generic-function-name))
309          (new (apply #'make-instance (class-of proto)
310                                      :qualifiers qualifiers
311                                      :specializers specs
312                                      :lambda-list lambda-list
313                                      other-initargs)))
314     (add-method generic-function new)))
315
316 (defun real-get-method (generic-function qualifiers specializers
317                                          &optional (errorp t))
318   (let ((hit 
319           (dolist (method (generic-function-methods generic-function))
320             (let ((mspecializers (method-specializers method)))
321               (when (and (equal qualifiers (method-qualifiers method))
322                          (= (length specializers) (length mspecializers))
323                          (every #'same-specializer-p specializers
324                                 (method-specializers method)))
325                 (return method))))))
326     (cond (hit hit)
327           ((null errorp) nil)
328           (t
329            (error "no method on ~S with qualifiers ~:S and specializers ~:S"
330                   generic-function qualifiers specializers)))))
331 \f
332 (defmethod find-method ((generic-function standard-generic-function)
333                         qualifiers specializers &optional (errorp t))
334   (real-get-method generic-function qualifiers
335                    (parse-specializers specializers) errorp))
336 \f
337 ;;; Compute various information about a generic-function's arglist by looking
338 ;;; at the argument lists of the methods. The hair for trying not to use
339 ;;; &REST arguments lives here.
340 ;;;  The values returned are:
341 ;;;    number-of-required-arguments
342 ;;;       the number of required arguments to this generic-function's
343 ;;;       discriminating function
344 ;;;    &rest-argument-p
345 ;;;       whether or not this generic-function's discriminating
346 ;;;       function takes an &rest argument.
347 ;;;    specialized-argument-positions
348 ;;;       a list of the positions of the arguments this generic-function
349 ;;;       specializes (e.g. for a classical generic-function this is the
350 ;;;       list: (1)).
351 (defmethod compute-discriminating-function-arglist-info
352            ((generic-function standard-generic-function))
353   ;;(declare (values number-of-required-arguments &rest-argument-p
354   ;;             specialized-argument-postions))
355   (let ((number-required nil)
356         (restp nil)
357         (specialized-positions ())
358         (methods (generic-function-methods generic-function)))
359     (dolist (method methods)
360       (multiple-value-setq (number-required restp specialized-positions)
361         (compute-discriminating-function-arglist-info-internal
362          generic-function method number-required restp specialized-positions)))
363     (values number-required restp (sort specialized-positions #'<))))
364
365 (defun compute-discriminating-function-arglist-info-internal
366        (generic-function method number-of-requireds restp
367         specialized-argument-positions)
368   (declare (ignore generic-function)
369            (type (or null fixnum) number-of-requireds))
370   (let ((requireds 0))
371     (declare (fixnum requireds))
372     ;; Go through this methods arguments seeing how many are required,
373     ;; and whether there is an &rest argument.
374     (dolist (arg (method-lambda-list method))
375       (cond ((eq arg '&aux) (return))
376             ((memq arg '(&optional &rest &key))
377              (return (setq restp t)))
378             ((memq arg lambda-list-keywords))
379             (t (incf requireds))))
380     ;; Now go through this method's type specifiers to see which
381     ;; argument positions are type specified. Treat T specially
382     ;; in the usual sort of way. For efficiency don't bother to
383     ;; keep specialized-argument-positions sorted, rather depend
384     ;; on our caller to do that.
385     (let ((pos 0))
386       (dolist (type-spec (method-specializers method))
387         (unless (eq type-spec *the-class-t*)
388           (pushnew pos specialized-argument-positions))
389         (incf pos)))
390     ;; Finally merge the values for this method into the values
391     ;; for the exisiting methods and return them. Note that if
392     ;; num-of-requireds is NIL it means this is the first method
393     ;; and we depend on that.
394     (values (min (or number-of-requireds requireds) requireds)
395             (or restp
396                 (and number-of-requireds (/= number-of-requireds requireds)))
397             specialized-argument-positions)))
398
399 (defun make-discriminating-function-arglist (number-required-arguments restp)
400   (nconc (let ((args nil))
401            (dotimes (i number-required-arguments)
402              (push (intern (format nil "Discriminating Function Arg ~D" i))
403                    args))
404            (nreverse args))
405          (when restp
406                `(&rest ,(intern "Discriminating Function &rest Arg")))))
407 \f
408 (defmethod generic-function-argument-precedence-order
409     ((gf standard-generic-function))
410   (aver (eq *boot-state* 'complete))
411   (loop with arg-info = (gf-arg-info gf)
412         with lambda-list = (arg-info-lambda-list arg-info)
413         for argument-position in (arg-info-precedence arg-info)
414         collect (nth argument-position lambda-list)))
415
416 (defmethod generic-function-lambda-list ((gf generic-function))
417   (gf-lambda-list gf))
418
419 (defmethod gf-fast-method-function-p ((gf standard-generic-function))
420   (gf-info-fast-mf-p (slot-value gf 'arg-info)))
421
422 (defmethod initialize-instance :after ((gf standard-generic-function)
423                                        &key (lambda-list nil lambda-list-p)
424                                        argument-precedence-order)
425   (with-slots (arg-info)
426     gf
427     (if lambda-list-p
428         (set-arg-info gf
429                       :lambda-list lambda-list
430                       :argument-precedence-order argument-precedence-order)
431         (set-arg-info gf))
432     (when (arg-info-valid-p arg-info)
433       (update-dfun gf))))
434
435 (defmethod reinitialize-instance :after ((gf standard-generic-function)
436                                          &rest args
437                                          &key (lambda-list nil lambda-list-p)
438                                          (argument-precedence-order
439                                           nil argument-precedence-order-p))
440   (with-slots (arg-info)
441     gf
442     (if lambda-list-p
443         (if argument-precedence-order-p
444             (set-arg-info gf
445                           :lambda-list lambda-list
446                           :argument-precedence-order argument-precedence-order)
447             (set-arg-info gf
448                           :lambda-list lambda-list))
449         (set-arg-info gf))
450     (when (and (arg-info-valid-p arg-info)
451                args
452                (or lambda-list-p (cddr args)))
453       (update-dfun gf))))
454
455 (declaim (special *lazy-dfun-compute-p*))
456
457 (defun set-methods (gf methods)
458   (setf (generic-function-methods gf) nil)
459   (loop (when (null methods) (return gf))
460         (real-add-method gf (pop methods) methods)))
461
462 (defun real-add-method (generic-function method &optional skip-dfun-update-p)
463   (when (method-generic-function method)
464     (error "The method ~S is already part of the generic~@
465             function ~S. It can't be added to another generic~@
466             function until it is removed from the first one."
467            method (method-generic-function method)))
468   (flet ((similar-lambda-lists-p (method-a method-b)
469            (multiple-value-bind (a-nreq a-nopt a-keyp a-restp)
470                (analyze-lambda-list (method-lambda-list method-a))
471              (multiple-value-bind (b-nreq b-nopt b-keyp b-restp)
472                  (analyze-lambda-list (method-lambda-list method-b))
473                (and (= a-nreq b-nreq)
474                     (= a-nopt b-nopt)
475                     (eq (or a-keyp a-restp)
476                         (or b-keyp b-restp)))))))
477       (let* ((name (generic-function-name generic-function))
478              (qualifiers (method-qualifiers method))
479              (specializers (method-specializers method))
480              (existing (get-method generic-function
481                                    qualifiers
482                                    specializers
483                                    nil)))
484
485         ;; If there is already a method like this one then we must get
486         ;; rid of it before proceeding.  Note that we call the generic
487         ;; function REMOVE-METHOD to remove it rather than doing it in
488         ;; some internal way.
489         (when (and existing (similar-lambda-lists-p existing method))
490           (remove-method generic-function existing))
491
492         (setf (method-generic-function method) generic-function)
493         (pushnew method (generic-function-methods generic-function))
494         (dolist (specializer specializers)
495           (add-direct-method specializer method))
496
497         ;; KLUDGE: SET-ARG-INFO contains the error-detecting logic for
498         ;; detecting attempts to add methods with incongruent lambda
499         ;; lists.  However, according to Gerd Moellmann on cmucl-imp,
500         ;; it also depends on the new method already having been added
501         ;; to the generic function.  Therefore, we need to remove it
502         ;; again on error:
503         (let ((remove-again-p t))
504           (unwind-protect
505                (progn
506                  (set-arg-info generic-function :new-method method)
507                  (setq remove-again-p nil))
508             (when remove-again-p
509               (remove-method generic-function method))))
510         (unless skip-dfun-update-p
511           (update-ctors 'add-method
512                         :generic-function generic-function
513                         :method method)
514           (update-dfun generic-function))
515         method)))
516
517 (defun real-remove-method (generic-function method)
518   ;; Note: Error check prohibited by ANSI spec removed.
519   (when  (eq generic-function (method-generic-function method))
520     (let* ((name         (generic-function-name generic-function))
521            (specializers (method-specializers method))
522            (methods      (generic-function-methods generic-function))
523            (new-methods  (remove method methods)))
524       (setf (method-generic-function method) nil)
525       (setf (generic-function-methods generic-function) new-methods)
526       (dolist (specializer (method-specializers method))
527         (remove-direct-method specializer method))
528       (set-arg-info generic-function)
529       (update-ctors 'remove-method
530                     :generic-function generic-function
531                     :method method)
532       (update-dfun generic-function)
533       generic-function)))
534 \f
535 (defun compute-applicable-methods-function (generic-function arguments)
536   (values (compute-applicable-methods-using-types
537            generic-function
538            (types-from-args generic-function arguments 'eql))))
539
540 (defmethod compute-applicable-methods
541     ((generic-function generic-function) arguments)
542   (values (compute-applicable-methods-using-types
543            generic-function
544            (types-from-args generic-function arguments 'eql))))
545
546 (defmethod compute-applicable-methods-using-classes
547     ((generic-function generic-function) classes)
548   (compute-applicable-methods-using-types
549    generic-function
550    (types-from-args generic-function classes 'class-eq)))
551
552 (defun proclaim-incompatible-superclasses (classes)
553   (setq classes (mapcar (lambda (class)
554                           (if (symbolp class)
555                               (find-class class)
556                               class))
557                         classes))
558   (dolist (class classes)
559     (dolist (other-class classes)
560       (unless (eq class other-class)
561         (pushnew other-class (class-incompatible-superclass-list class))))))
562
563 (defun superclasses-compatible-p (class1 class2)
564   (let ((cpl1 (class-precedence-list class1))
565         (cpl2 (class-precedence-list class2)))
566     (dolist (sc1 cpl1 t)
567       (dolist (ic (class-incompatible-superclass-list sc1))
568         (when (memq ic cpl2)
569           (return-from superclasses-compatible-p nil))))))
570
571 (mapc
572  #'proclaim-incompatible-superclasses
573  '(;; superclass class
574    (built-in-class std-class structure-class) ; direct subclasses of pcl-class
575    (standard-class funcallable-standard-class)
576    ;; superclass metaobject
577    (class eql-specializer class-eq-specializer method method-combination
578     generic-function slot-definition)
579    ;; metaclass built-in-class
580    (number sequence character           ; direct subclasses of t, but not array
581     standard-object structure-object)   ;                        or symbol
582    (number array character symbol       ; direct subclasses of t, but not
583     standard-object structure-object)   ;                        sequence
584    (complex float rational)             ; direct subclasses of number
585    (integer ratio)                      ; direct subclasses of rational
586    (list vector)                        ; direct subclasses of sequence
587    (cons null)                          ; direct subclasses of list
588    (string bit-vector)                  ; direct subclasses of vector
589    ))
590 \f
591 (defmethod same-specializer-p ((specl1 specializer) (specl2 specializer))
592   nil)
593
594 (defmethod same-specializer-p ((specl1 class) (specl2 class))
595   (eq specl1 specl2))
596
597 (defmethod specializer-class ((specializer class))
598   specializer)
599
600 (defmethod same-specializer-p ((specl1 class-eq-specializer)
601                                (specl2 class-eq-specializer))
602   (eq (specializer-class specl1) (specializer-class specl2)))
603
604 (defmethod same-specializer-p ((specl1 eql-specializer)
605                                (specl2 eql-specializer))
606   (eq (specializer-object specl1) (specializer-object specl2)))
607
608 (defmethod specializer-class ((specializer eql-specializer))
609   (class-of (slot-value specializer 'object)))
610
611 (defvar *in-gf-arg-info-p* nil)
612 (setf (gdefinition 'arg-info-reader)
613       (let ((mf (initialize-method-function
614                  (make-internal-reader-method-function
615                   'standard-generic-function 'arg-info)
616                  t)))
617         (lambda (&rest args) (funcall mf args nil))))
618
619
620 (defun error-need-at-least-n-args (function n)
621   (error "~@<The function ~2I~_~S ~I~_requires at least ~W argument~:P.~:>"
622          function
623          n))
624
625 (defun types-from-args (generic-function arguments &optional type-modifier)
626   (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
627       (get-generic-fun-info generic-function)
628     (declare (ignore applyp metatypes nkeys))
629     (let ((types-rev nil))
630       (dotimes-fixnum (i nreq)
631         i
632         (unless arguments
633           (error-need-at-least-n-args (generic-function-name generic-function)
634                                       nreq))
635         (let ((arg (pop arguments)))
636           (push (if type-modifier `(,type-modifier ,arg) arg) types-rev)))
637       (values (nreverse types-rev) arg-info))))
638
639 (defun get-wrappers-from-classes (nkeys wrappers classes metatypes)
640   (let* ((w wrappers) (w-tail w) (mt-tail metatypes))
641     (dolist (class (if (listp classes) classes (list classes)))
642       (unless (eq t (car mt-tail))
643         (let ((c-w (class-wrapper class)))
644           (unless c-w (return-from get-wrappers-from-classes nil))
645           (if (eql nkeys 1)
646               (setq w c-w)
647               (setf (car w-tail) c-w
648                     w-tail (cdr w-tail)))))
649       (setq mt-tail (cdr mt-tail)))
650     w))
651
652 (defun sdfun-for-caching (gf classes)
653   (let ((types (mapcar #'class-eq-type classes)))
654     (multiple-value-bind (methods all-applicable-and-sorted-p)
655         (compute-applicable-methods-using-types gf types)
656       (function-funcall (get-secondary-dispatch-function1
657                          gf methods types nil t all-applicable-and-sorted-p)
658                         nil (mapcar #'class-wrapper classes)))))
659
660 (defun value-for-caching (gf classes)
661   (let ((methods (compute-applicable-methods-using-types
662                    gf (mapcar #'class-eq-type classes))))
663     (method-function-get (or (method-fast-function (car methods))
664                              (method-function (car methods)))
665                          :constant-value)))
666
667 (defun default-secondary-dispatch-function (generic-function)
668   (lambda (&rest args)
669     (let ((methods (compute-applicable-methods generic-function args)))
670       (if methods
671           (let ((emf (get-effective-method-function generic-function
672                                                     methods)))
673             (invoke-emf emf args))
674           (apply #'no-applicable-method generic-function args)))))
675
676 (defun list-eq (x y)
677   (loop (when (atom x) (return (eq x y)))
678         (when (atom y) (return nil))
679         (unless (eq (car x) (car y)) (return nil))
680         (setq x (cdr x)  y (cdr y))))
681
682 (defvar *std-cam-methods* nil)
683
684 (defun compute-applicable-methods-emf (generic-function)
685   (if (eq *boot-state* 'complete)
686       (let* ((cam (gdefinition 'compute-applicable-methods))
687              (cam-methods (compute-applicable-methods-using-types
688                            cam (list `(eql ,generic-function) t))))
689         (values (get-effective-method-function cam cam-methods)
690                 (list-eq cam-methods
691                          (or *std-cam-methods*
692                              (setq *std-cam-methods*
693                                    (compute-applicable-methods-using-types
694                                     cam (list `(eql ,cam) t)))))))
695       (values #'compute-applicable-methods-function t)))
696
697 (defun compute-applicable-methods-emf-std-p (gf)
698   (gf-info-c-a-m-emf-std-p (gf-arg-info gf)))
699
700 (defvar *old-c-a-m-gf-methods* nil)
701
702 (defun update-all-c-a-m-gf-info (c-a-m-gf)
703   (let ((methods (generic-function-methods c-a-m-gf)))
704     (if (and *old-c-a-m-gf-methods*
705              (every (lambda (old-method)
706                       (member old-method methods))
707                     *old-c-a-m-gf-methods*))
708         (let ((gfs-to-do nil)
709               (gf-classes-to-do nil))
710           (dolist (method methods)
711             (unless (member method *old-c-a-m-gf-methods*)
712               (let ((specl (car (method-specializers method))))
713                 (if (eql-specializer-p specl)
714                     (pushnew (specializer-object specl) gfs-to-do)
715                     (pushnew (specializer-class specl) gf-classes-to-do)))))
716           (map-all-generic-functions
717            (lambda (gf)
718              (when (or (member gf gfs-to-do)
719                        (dolist (class gf-classes-to-do nil)
720                          (member class
721                                  (class-precedence-list (class-of gf)))))
722                (update-c-a-m-gf-info gf)))))
723         (map-all-generic-functions #'update-c-a-m-gf-info))
724     (setq *old-c-a-m-gf-methods* methods)))
725
726 (defun update-gf-info (gf)
727   (update-c-a-m-gf-info gf)
728   (update-gf-simple-accessor-type gf))
729
730 (defun update-c-a-m-gf-info (gf)
731   (unless (early-gf-p gf)
732     (multiple-value-bind (c-a-m-emf std-p)
733         (compute-applicable-methods-emf gf)
734       (let ((arg-info (gf-arg-info gf)))
735         (setf (gf-info-static-c-a-m-emf arg-info) c-a-m-emf)
736         (setf (gf-info-c-a-m-emf-std-p arg-info) std-p)))))
737
738 (defun update-gf-simple-accessor-type (gf)
739   (let ((arg-info (gf-arg-info gf)))
740     (setf (gf-info-simple-accessor-type arg-info)
741           (let* ((methods (generic-function-methods gf))
742                  (class (and methods (class-of (car methods))))
743                  (type (and class
744                             (cond ((eq class
745                                        *the-class-standard-reader-method*)
746                                    'reader)
747                                   ((eq class
748                                        *the-class-standard-writer-method*)
749                                    'writer)
750                                   ((eq class
751                                        *the-class-standard-boundp-method*)
752                                    'boundp)))))
753             (when (and (gf-info-c-a-m-emf-std-p arg-info)
754                        type
755                        (dolist (method (cdr methods) t)
756                          (unless (eq class (class-of method)) (return nil)))
757                        (eq (generic-function-method-combination gf)
758                            *standard-method-combination*))
759               type)))))
760
761 (defun get-accessor-method-function (gf type class slotd)
762   (let* ((std-method (standard-svuc-method type))
763          (str-method (structure-svuc-method type))
764          (types1 `((eql ,class) (class-eq ,class) (eql ,slotd)))
765          (types (if (eq type 'writer) `(t ,@types1) types1))
766          (methods (compute-applicable-methods-using-types gf types))
767          (std-p (null (cdr methods))))
768     (values
769      (if std-p
770          (get-optimized-std-accessor-method-function class slotd type)
771          (get-accessor-from-svuc-method-function
772           class slotd
773           (get-secondary-dispatch-function
774            gf methods types
775            `((,(car (or (member std-method methods)
776                         (member str-method methods)
777                         (error "error in get-accessor-method-function")))
778               ,(get-optimized-std-slot-value-using-class-method-function
779                 class slotd type)))
780            (unless (and (eq type 'writer)
781                         (dolist (method methods t)
782                           (unless (eq (car (method-specializers method))
783                                       *the-class-t*)
784                             (return nil))))
785              (let ((wrappers (list (wrapper-of class)
786                                    (class-wrapper class)
787                                    (wrapper-of slotd))))
788                (if (eq type 'writer)
789                    (cons (class-wrapper *the-class-t*) wrappers)
790                    wrappers))))
791           type))
792      std-p)))
793
794 ;;; used by OPTIMIZE-SLOT-VALUE-BY-CLASS-P (vector.lisp)
795 (defun update-slot-value-gf-info (gf type)
796   (unless *new-class*
797     (update-std-or-str-methods gf type))
798   (when (and (standard-svuc-method type) (structure-svuc-method type))
799     (flet ((update-class (class)
800              (when (class-finalized-p class)
801                (dolist (slotd (class-slots class))
802                  (compute-slot-accessor-info slotd type gf)))))
803       (if *new-class*
804           (update-class *new-class*)
805           (map-all-classes #'update-class 'slot-object)))))
806
807 (defvar *standard-slot-value-using-class-method* nil)
808 (defvar *standard-setf-slot-value-using-class-method* nil)
809 (defvar *standard-slot-boundp-using-class-method* nil)
810 (defvar *structure-slot-value-using-class-method* nil)
811 (defvar *structure-setf-slot-value-using-class-method* nil)
812 (defvar *structure-slot-boundp-using-class-method* nil)
813
814 (defun standard-svuc-method (type)
815   (case type
816     (reader *standard-slot-value-using-class-method*)
817     (writer *standard-setf-slot-value-using-class-method*)
818     (boundp *standard-slot-boundp-using-class-method*)))
819
820 (defun set-standard-svuc-method (type method)
821   (case type
822     (reader (setq *standard-slot-value-using-class-method* method))
823     (writer (setq *standard-setf-slot-value-using-class-method* method))
824     (boundp (setq *standard-slot-boundp-using-class-method* method))))
825
826 (defun structure-svuc-method (type)
827   (case type
828     (reader *structure-slot-value-using-class-method*)
829     (writer *structure-setf-slot-value-using-class-method*)
830     (boundp *structure-slot-boundp-using-class-method*)))
831
832 (defun set-structure-svuc-method (type method)
833   (case type
834     (reader (setq *structure-slot-value-using-class-method* method))
835     (writer (setq *structure-setf-slot-value-using-class-method* method))
836     (boundp (setq *structure-slot-boundp-using-class-method* method))))
837
838 (defun update-std-or-str-methods (gf type)
839   (dolist (method (generic-function-methods gf))
840     (let ((specls (method-specializers method)))
841       (when (and (or (not (eq type 'writer))
842                      (eq (pop specls) *the-class-t*))
843                  (every #'classp specls))
844         (cond ((and (eq (class-name (car specls))
845                         'std-class)
846                     (eq (class-name (cadr specls))
847                         'std-object)
848                     (eq (class-name (caddr specls))
849                         'standard-effective-slot-definition))
850                (set-standard-svuc-method type method))
851               ((and (eq (class-name (car specls))
852                         'structure-class)
853                     (eq (class-name (cadr specls))
854                         'structure-object)
855                     (eq (class-name (caddr specls))
856                         'structure-effective-slot-definition))
857                (set-structure-svuc-method type method)))))))
858
859 (defun mec-all-classes-internal (spec precompute-p)
860   (cons (specializer-class spec)
861         (and (classp spec)
862              precompute-p
863              (not (or (eq spec *the-class-t*)
864                       (eq spec *the-class-slot-object*)
865                       (eq spec *the-class-std-object*)
866                       (eq spec *the-class-standard-object*)
867                       (eq spec *the-class-structure-object*)))
868              (let ((sc (class-direct-subclasses spec)))
869                (when sc
870                  (mapcan (lambda (class)
871                            (mec-all-classes-internal class precompute-p))
872                          sc))))))
873
874 (defun mec-all-classes (spec precompute-p)
875   (let ((classes (mec-all-classes-internal spec precompute-p)))
876     (if (null (cdr classes))
877         classes
878         (let* ((a-classes (cons nil classes))
879                (tail classes))
880           (loop (when (null (cdr tail))
881                   (return (cdr a-classes)))
882                 (let ((class (cadr tail))
883                       (ttail (cddr tail)))
884                   (if (dolist (c ttail nil)
885                         (when (eq class c) (return t)))
886                       (setf (cdr tail) (cddr tail))
887                       (setf tail (cdr tail)))))))))
888
889 (defun mec-all-class-lists (spec-list precompute-p)
890   (if (null spec-list)
891       (list nil)
892       (let* ((car-all-classes (mec-all-classes (car spec-list)
893                                                precompute-p))
894              (all-class-lists (mec-all-class-lists (cdr spec-list)
895                                                    precompute-p)))
896         (mapcan (lambda (list)
897                   (mapcar (lambda (c) (cons c list)) car-all-classes))
898                 all-class-lists))))
899
900 (defun make-emf-cache (generic-function valuep cache classes-list new-class)
901   (let* ((arg-info (gf-arg-info generic-function))
902          (nkeys (arg-info-nkeys arg-info))
903          (metatypes (arg-info-metatypes arg-info))
904          (wrappers (unless (eq nkeys 1) (make-list nkeys)))
905          (precompute-p (gf-precompute-dfun-and-emf-p arg-info))
906          (default '(default)))
907     (flet ((add-class-list (classes)
908              (when (or (null new-class) (memq new-class classes))
909                (let ((wrappers (get-wrappers-from-classes
910                                 nkeys wrappers classes metatypes)))
911                  (when (and wrappers
912                             (eq default (probe-cache cache wrappers default)))
913                    (let ((value (cond ((eq valuep t)
914                                        (sdfun-for-caching generic-function
915                                                           classes))
916                                       ((eq valuep :constant-value)
917                                        (value-for-caching generic-function
918                                                           classes)))))
919                      (setq cache (fill-cache cache wrappers value t))))))))
920       (if classes-list
921           (mapc #'add-class-list classes-list)
922           (dolist (method (generic-function-methods generic-function))
923             (mapc #'add-class-list
924                   (mec-all-class-lists (method-specializers method)
925                                        precompute-p))))
926       cache)))
927
928 (defmacro class-test (arg class)
929   (cond ((eq class *the-class-t*)
930          t)
931         ((eq class *the-class-slot-object*)
932          `(not (cl:typep (cl:class-of ,arg) 'cl:built-in-class)))
933         ((eq class *the-class-std-object*)
934          `(or (std-instance-p ,arg) (fsc-instance-p ,arg)))
935         ((eq class *the-class-standard-object*)
936          `(std-instance-p ,arg))
937         ((eq class *the-class-funcallable-standard-object*)
938          `(fsc-instance-p ,arg))
939         (t
940          `(typep ,arg ',(class-name class)))))
941
942 (defmacro class-eq-test (arg class)
943   `(eq (class-of ,arg) ',class))
944
945 (defmacro eql-test (arg object)
946   `(eql ,arg ',object))
947
948 (defun dnet-methods-p (form)
949   (and (consp form)
950        (or (eq (car form) 'methods)
951            (eq (car form) 'unordered-methods))))
952
953 ;;; This is CASE, but without gensyms.
954 (defmacro scase (arg &rest clauses)
955   `(let ((.case-arg. ,arg))
956      (cond ,@(mapcar (lambda (clause)
957                        (list* (cond ((null (car clause))
958                                      nil)
959                                     ((consp (car clause))
960                                      (if (null (cdar clause))
961                                          `(eql .case-arg.
962                                                ',(caar clause))
963                                          `(member .case-arg.
964                                                   ',(car clause))))
965                                     ((member (car clause) '(t otherwise))
966                                      `t)
967                                     (t
968                                      `(eql .case-arg. ',(car clause))))
969                               nil
970                               (cdr clause)))
971                      clauses))))
972
973 (defmacro mcase (arg &rest clauses) `(scase ,arg ,@clauses))
974
975 (defun generate-discrimination-net (generic-function methods types sorted-p)
976   (let* ((arg-info (gf-arg-info generic-function))
977          (precedence (arg-info-precedence arg-info)))
978     (generate-discrimination-net-internal
979      generic-function methods types
980      (lambda (methods known-types)
981        (if (or sorted-p
982                (block one-order-p
983                  (let ((sorted-methods nil))
984                    (map-all-orders
985                     (copy-list methods) precedence
986                     (lambda (methods)
987                       (when sorted-methods (return-from one-order-p nil))
988                       (setq sorted-methods methods)))
989                    (setq methods sorted-methods))
990                  t))
991            `(methods ,methods ,known-types)
992            `(unordered-methods ,methods ,known-types)))
993      (lambda (position type true-value false-value)
994        (let ((arg (dfun-arg-symbol position)))
995          (if (eq (car type) 'eql)
996              (let* ((false-case-p (and (consp false-value)
997                                        (or (eq (car false-value) 'scase)
998                                            (eq (car false-value) 'mcase))
999                                        (eq arg (cadr false-value))))
1000                     (false-clauses (if false-case-p
1001                                        (cddr false-value)
1002                                        `((t ,false-value))))
1003                     (case-sym (if (and (dnet-methods-p true-value)
1004                                        (if false-case-p
1005                                            (eq (car false-value) 'mcase)
1006                                            (dnet-methods-p false-value)))
1007                                   'mcase
1008                                   'scase))
1009                     (type-sym `(,(cadr type))))
1010                `(,case-sym ,arg
1011                            (,type-sym ,true-value)
1012                            ,@false-clauses))
1013              `(if ,(let ((arg (dfun-arg-symbol position)))
1014                      (case (car type)
1015                        (class    `(class-test    ,arg ,(cadr type)))
1016                        (class-eq `(class-eq-test ,arg ,(cadr type)))))
1017                   ,true-value
1018                   ,false-value))))
1019      #'identity)))
1020
1021 (defun class-from-type (type)
1022   (if (or (atom type) (eq (car type) t))
1023       *the-class-t*
1024       (case (car type)
1025         (and (dolist (type (cdr type) *the-class-t*)
1026                (when (and (consp type) (not (eq (car type) 'not)))
1027                  (return (class-from-type type)))))
1028         (not *the-class-t*)
1029         (eql (class-of (cadr type)))
1030         (class-eq (cadr type))
1031         (class (cadr type)))))
1032
1033 (defun precompute-effective-methods (gf caching-p &optional classes-list-p)
1034   (let* ((arg-info (gf-arg-info gf))
1035          (methods (generic-function-methods gf))
1036          (precedence (arg-info-precedence arg-info))
1037          (*in-precompute-effective-methods-p* t)
1038          (classes-list nil))
1039     (generate-discrimination-net-internal
1040      gf methods nil
1041      (lambda (methods known-types)
1042        (when methods
1043          (when classes-list-p
1044            (push (mapcar #'class-from-type known-types) classes-list))
1045          (let ((no-eql-specls-p (not (methods-contain-eql-specializer-p
1046                                       methods))))
1047            (map-all-orders
1048             methods precedence
1049             (lambda (methods)
1050               (get-secondary-dispatch-function1
1051                gf methods known-types
1052                nil caching-p no-eql-specls-p))))))
1053      (lambda (position type true-value false-value)
1054        (declare (ignore position type true-value false-value))
1055        nil)
1056      (lambda (type)
1057        (if (and (consp type) (eq (car type) 'eql))
1058            `(class-eq ,(class-of (cadr type)))
1059            type)))
1060     classes-list))
1061
1062 ;;; We know that known-type implies neither new-type nor `(not ,new-type).
1063 (defun augment-type (new-type known-type)
1064   (if (or (eq known-type t)
1065           (eq (car new-type) 'eql))
1066       new-type
1067       (let ((so-far (if (and (consp known-type) (eq (car known-type) 'and))
1068                         (cdr known-type)
1069                         (list known-type))))
1070         (unless (eq (car new-type) 'not)
1071           (setq so-far
1072                 (mapcan (lambda (type)
1073                           (unless (*subtypep new-type type)
1074                             (list type)))
1075                         so-far)))
1076         (if (null so-far)
1077             new-type
1078             `(and ,new-type ,@so-far)))))
1079
1080 (defun generate-discrimination-net-internal
1081     (gf methods types methods-function test-fun type-function)
1082   (let* ((arg-info (gf-arg-info gf))
1083          (precedence (arg-info-precedence arg-info))
1084          (nreq (arg-info-number-required arg-info))
1085          (metatypes (arg-info-metatypes arg-info)))
1086     (labels ((do-column (p-tail contenders known-types)
1087                (if p-tail
1088                    (let* ((position (car p-tail))
1089                           (known-type (or (nth position types) t)))
1090                      (if (eq (nth position metatypes) t)
1091                          (do-column (cdr p-tail) contenders
1092                                     (cons (cons position known-type)
1093                                           known-types))
1094                          (do-methods p-tail contenders
1095                                      known-type () known-types)))
1096                    (funcall methods-function contenders
1097                             (let ((k-t (make-list nreq)))
1098                               (dolist (index+type known-types)
1099                                 (setf (nth (car index+type) k-t)
1100                                       (cdr index+type)))
1101                               k-t))))
1102              (do-methods (p-tail contenders known-type winners known-types)
1103                ;; CONTENDERS
1104                ;;   is a (sorted) list of methods that must be discriminated.
1105                ;; KNOWN-TYPE
1106                ;;   is the type of this argument, constructed from tests
1107                ;;   already made.
1108                ;; WINNERS
1109                ;;   is a (sorted) list of methods that are potentially
1110                ;;   applicable after the discrimination has been made.
1111                (if (null contenders)
1112                    (do-column (cdr p-tail)
1113                               winners
1114                               (cons (cons (car p-tail) known-type)
1115                                     known-types))
1116                    (let* ((position (car p-tail))
1117                           (method (car contenders))
1118                           (specl (nth position (method-specializers method)))
1119                           (type (funcall type-function
1120                                          (type-from-specializer specl))))
1121                      (multiple-value-bind (app-p maybe-app-p)
1122                          (specializer-applicable-using-type-p type known-type)
1123                        (flet ((determined-to-be (truth-value)
1124                                 (if truth-value app-p (not maybe-app-p)))
1125                               (do-if (truth &optional implied)
1126                                 (let ((ntype (if truth type `(not ,type))))
1127                                   (do-methods p-tail
1128                                     (cdr contenders)
1129                                     (if implied
1130                                         known-type
1131                                         (augment-type ntype known-type))
1132                                     (if truth
1133                                         (append winners `(,method))
1134                                         winners)
1135                                     known-types))))
1136                          (cond ((determined-to-be nil) (do-if nil t))
1137                                ((determined-to-be t)   (do-if t   t))
1138                                (t (funcall test-fun position type
1139                                            (do-if t) (do-if nil))))))))))
1140       (do-column precedence methods ()))))
1141
1142 (defun compute-secondary-dispatch-function (generic-function net &optional
1143                                             method-alist wrappers)
1144   (function-funcall (compute-secondary-dispatch-function1 generic-function net)
1145                     method-alist wrappers))
1146
1147 (defvar *eq-case-table-limit* 15)
1148 (defvar *case-table-limit* 10)
1149
1150 (defun compute-mcase-parameters (case-list)
1151   (unless (eq t (caar (last case-list)))
1152     (error "The key for the last case arg to mcase was not T"))
1153   (let* ((eq-p (dolist (case case-list t)
1154                  (unless (or (eq (car case) t)
1155                              (symbolp (caar case)))
1156                    (return nil))))
1157          (len (1- (length case-list)))
1158          (type (cond ((= len 1)
1159                       :simple)
1160                      ((<= len
1161                           (if eq-p
1162                               *eq-case-table-limit*
1163                               *case-table-limit*))
1164                       :assoc)
1165                      (t
1166                       :hash-table))))
1167     (list eq-p type)))
1168
1169 (defmacro mlookup (key info default &optional eq-p type)
1170   (unless (or (eq eq-p t) (null eq-p))
1171     (error "Invalid eq-p argument"))
1172   (ecase type
1173     (:simple
1174      `(if (,(if eq-p 'eq 'eql) ,key (car ,info))
1175           (cdr ,info)
1176           ,default))
1177     (:assoc
1178      `(dolist (e ,info ,default)
1179         (when (,(if eq-p 'eq 'eql) (car e) ,key)
1180           (return (cdr e)))))
1181     (:hash-table
1182      `(gethash ,key ,info ,default))))
1183
1184 (defun net-test-converter (form)
1185   (if (atom form)
1186       (default-test-converter form)
1187       (case (car form)
1188         ((invoke-effective-method-function invoke-fast-method-call)
1189          '.call.)
1190         (methods
1191          '.methods.)
1192         (unordered-methods
1193          '.umethods.)
1194         (mcase
1195          `(mlookup ,(cadr form)
1196                    nil
1197                    nil
1198                    ,@(compute-mcase-parameters (cddr form))))
1199         (t (default-test-converter form)))))
1200
1201 (defun net-code-converter (form)
1202   (if (atom form)
1203       (default-code-converter form)
1204       (case (car form)
1205         ((methods unordered-methods)
1206          (let ((gensym (gensym)))
1207            (values gensym
1208                    (list gensym))))
1209         (mcase
1210          (let ((mp (compute-mcase-parameters (cddr form)))
1211                (gensym (gensym)) (default (gensym)))
1212            (values `(mlookup ,(cadr form) ,gensym ,default ,@mp)
1213                    (list gensym default))))
1214         (t
1215          (default-code-converter form)))))
1216
1217 (defun net-constant-converter (form generic-function)
1218   (or (let ((c (methods-converter form generic-function)))
1219         (when c (list c)))
1220       (if (atom form)
1221           (default-constant-converter form)
1222           (case (car form)
1223             (mcase
1224              (let* ((mp (compute-mcase-parameters (cddr form)))
1225                     (list (mapcar (lambda (clause)
1226                                     (let ((key (car clause))
1227                                           (meth (cadr clause)))
1228                                       (cons (if (consp key) (car key) key)
1229                                             (methods-converter
1230                                              meth generic-function))))
1231                                   (cddr form)))
1232                     (default (car (last list))))
1233                (list (list* :mcase mp (nbutlast list))
1234                      (cdr default))))
1235             (t
1236              (default-constant-converter form))))))
1237
1238 (defun methods-converter (form generic-function)
1239   (cond ((and (consp form) (eq (car form) 'methods))
1240          (cons '.methods.
1241                (get-effective-method-function1 generic-function (cadr form))))
1242         ((and (consp form) (eq (car form) 'unordered-methods))
1243          (default-secondary-dispatch-function generic-function))))
1244
1245 (defun convert-methods (constant method-alist wrappers)
1246   (if (and (consp constant)
1247            (eq (car constant) '.methods.))
1248       (funcall (cdr constant) method-alist wrappers)
1249       constant))
1250
1251 (defun convert-table (constant method-alist wrappers)
1252   (cond ((and (consp constant)
1253               (eq (car constant) :mcase))
1254          (let ((alist (mapcar (lambda (k+m)
1255                                 (cons (car k+m)
1256                                       (convert-methods (cdr k+m)
1257                                                        method-alist
1258                                                        wrappers)))
1259                               (cddr constant)))
1260                (mp (cadr constant)))
1261            (ecase (cadr mp)
1262              (:simple
1263               (car alist))
1264              (:assoc
1265               alist)
1266              (:hash-table
1267               (let ((table (make-hash-table :test (if (car mp) 'eq 'eql))))
1268                 (dolist (k+m alist)
1269                   (setf (gethash (car k+m) table) (cdr k+m)))
1270                 table)))))))
1271
1272 (defun compute-secondary-dispatch-function1 (generic-function net
1273                                              &optional function-p)
1274   (cond
1275    ((and (eq (car net) 'methods) (not function-p))
1276     (get-effective-method-function1 generic-function (cadr net)))
1277    (t
1278     (let* ((name (generic-function-name generic-function))
1279            (arg-info (gf-arg-info generic-function))
1280            (metatypes (arg-info-metatypes arg-info))
1281            (applyp (arg-info-applyp arg-info))
1282            (fmc-arg-info (cons (length metatypes) applyp))
1283            (arglist (if function-p
1284                         (make-dfun-lambda-list metatypes applyp)
1285                         (make-fast-method-call-lambda-list metatypes applyp))))
1286       (multiple-value-bind (cfunction constants)
1287           (get-fun1 `(,(if function-p
1288                            'sb-kernel:instance-lambda
1289                            'lambda)
1290                       ,arglist
1291                       ,@(unless function-p
1292                           `((declare (ignore .pv-cell.
1293                                              .next-method-call.))))
1294                       (locally (declare #.*optimize-speed*)
1295                                (let ((emf ,net))
1296                                  ,(make-emf-call metatypes applyp 'emf))))
1297                     #'net-test-converter
1298                     #'net-code-converter
1299                     (lambda (form)
1300                       (net-constant-converter form generic-function)))
1301         (lambda (method-alist wrappers)
1302           (let* ((alist (list nil))
1303                  (alist-tail alist))
1304             (dolist (constant constants)
1305               (let* ((a (or (dolist (a alist nil)
1306                               (when (eq (car a) constant)
1307                                 (return a)))
1308                             (cons constant
1309                                   (or (convert-table
1310                                        constant method-alist wrappers)
1311                                       (convert-methods
1312                                        constant method-alist wrappers)))))
1313                      (new (list a)))
1314                 (setf (cdr alist-tail) new)
1315                 (setf alist-tail new)))
1316             (let ((function (apply cfunction (mapcar #'cdr (cdr alist)))))
1317               (if function-p
1318                   function
1319                   (make-fast-method-call
1320                    :function (set-fun-name function `(sdfun-method ,name))
1321                    :arg-info fmc-arg-info))))))))))
1322
1323 (defvar *show-make-unordered-methods-emf-calls* nil)
1324
1325 (defun make-unordered-methods-emf (generic-function methods)
1326   (when *show-make-unordered-methods-emf-calls*
1327     (format t "~&make-unordered-methods-emf ~S~%"
1328             (generic-function-name generic-function)))
1329   (lambda (&rest args)
1330     (let* ((types (types-from-args generic-function args 'eql))
1331            (smethods (sort-applicable-methods generic-function
1332                                               methods
1333                                               types))
1334            (emf (get-effective-method-function generic-function smethods)))
1335       (invoke-emf emf args))))
1336 \f
1337 ;;; The value returned by compute-discriminating-function is a function
1338 ;;; object. It is called a discriminating function because it is called
1339 ;;; when the generic function is called and its role is to discriminate
1340 ;;; on the arguments to the generic function and then call appropriate
1341 ;;; method functions.
1342 ;;;
1343 ;;; A discriminating function can only be called when it is installed as
1344 ;;; the funcallable instance function of the generic function for which
1345 ;;; it was computed.
1346 ;;;
1347 ;;; More precisely, if compute-discriminating-function is called with an
1348 ;;; argument <gf1>, and returns a result <df1>, that result must not be
1349 ;;; passed to apply or funcall directly. Rather, <df1> must be stored as
1350 ;;; the funcallable instance function of the same generic function <gf1>
1351 ;;; (using set-funcallable-instance-fun). Then the generic function
1352 ;;; can be passed to funcall or apply.
1353 ;;;
1354 ;;; An important exception is that methods on this generic function are
1355 ;;; permitted to return a function which itself ends up calling the value
1356 ;;; returned by a more specific method. This kind of `encapsulation' of
1357 ;;; discriminating function is critical to many uses of the MOP.
1358 ;;;
1359 ;;; As an example, the following canonical case is legal:
1360 ;;;
1361 ;;;   (defmethod compute-discriminating-function ((gf my-generic-function))
1362 ;;;     (let ((std (call-next-method)))
1363 ;;;       (lambda (arg)
1364 ;;;         (print (list 'call-to-gf gf arg))
1365 ;;;         (funcall std arg))))
1366 ;;;
1367 ;;; Because many discriminating functions would like to use a dynamic
1368 ;;; strategy in which the precise discriminating function changes with
1369 ;;; time it is important to specify how a discriminating function is
1370 ;;; permitted itself to change the funcallable instance function of the
1371 ;;; generic function.
1372 ;;;
1373 ;;; Discriminating functions may set the funcallable instance function
1374 ;;; of the generic function, but the new value must be generated by making
1375 ;;; a call to COMPUTE-DISCRIMINATING-FUNCTION. This is to ensure that any
1376 ;;; more specific methods which may have encapsulated the discriminating
1377 ;;; function will get a chance to encapsulate the new, inner discriminating
1378 ;;; function.
1379 ;;;
1380 ;;; This implies that if a discriminating function wants to modify itself
1381 ;;; it should first store some information in the generic function proper,
1382 ;;; and then call compute-discriminating-function. The appropriate method
1383 ;;; on compute-discriminating-function will see the information stored in
1384 ;;; the generic function and generate a discriminating function accordingly.
1385 ;;;
1386 ;;; The following is an example of a discriminating function which modifies
1387 ;;; itself in accordance with this protocol:
1388 ;;;
1389 ;;;   (defmethod compute-discriminating-function ((gf my-generic-function))
1390 ;;;     (lambda (arg)
1391 ;;;      (cond (<some condition>
1392 ;;;             <store some info in the generic function>
1393 ;;;             (set-funcallable-instance-fun
1394 ;;;               gf
1395 ;;;               (compute-discriminating-function gf))
1396 ;;;             (funcall gf arg))
1397 ;;;            (t
1398 ;;;             <call-a-method-of-gf>))))
1399 ;;;
1400 ;;; Whereas this code would not be legal:
1401 ;;;
1402 ;;;   (defmethod compute-discriminating-function ((gf my-generic-function))
1403 ;;;     (lambda (arg)
1404 ;;;      (cond (<some condition>
1405 ;;;             (set-funcallable-instance-fun
1406 ;;;               gf
1407 ;;;               (lambda (a) ..))
1408 ;;;             (funcall gf arg))
1409 ;;;            (t
1410 ;;;             <call-a-method-of-gf>))))
1411 ;;;
1412 ;;; NOTE:  All the examples above assume that all instances of the class
1413 ;;;     my-generic-function accept only one argument.
1414
1415 (defun slot-value-using-class-dfun (class object slotd)
1416   (declare (ignore class))
1417   (function-funcall (slot-definition-reader-function slotd) object))
1418
1419 (defun setf-slot-value-using-class-dfun (new-value class object slotd)
1420   (declare (ignore class))
1421   (function-funcall (slot-definition-writer-function slotd) new-value object))
1422
1423 (defun slot-boundp-using-class-dfun (class object slotd)
1424   (declare (ignore class))
1425   (function-funcall (slot-definition-boundp-function slotd) object))
1426
1427 (defmethod compute-discriminating-function ((gf standard-generic-function))
1428   (with-slots (dfun-state arg-info) gf
1429     (typecase dfun-state
1430       (null (let ((name (generic-function-name gf)))
1431               (when (eq name 'compute-applicable-methods)
1432                 (update-all-c-a-m-gf-info gf))
1433               (cond ((eq name 'slot-value-using-class)
1434                      (update-slot-value-gf-info gf 'reader)
1435                      #'slot-value-using-class-dfun)
1436                     ((equal name '(setf slot-value-using-class))
1437                      (update-slot-value-gf-info gf 'writer)
1438                      #'setf-slot-value-using-class-dfun)
1439                     ((eq name 'slot-boundp-using-class)
1440                      (update-slot-value-gf-info gf 'boundp)
1441                      #'slot-boundp-using-class-dfun)
1442                     ((gf-precompute-dfun-and-emf-p arg-info)
1443                      (make-final-dfun gf))
1444                     (t
1445                      (make-initial-dfun gf)))))
1446       (function dfun-state)
1447       (cons (car dfun-state)))))
1448
1449 (defmethod update-gf-dfun ((class std-class) gf)
1450   (let ((*new-class* class)
1451         #|| (name (generic-function-name gf)) ||#
1452         (arg-info (gf-arg-info gf)))
1453     (cond #||
1454           ((eq name 'slot-value-using-class)
1455            (update-slot-value-gf-info gf 'reader))
1456           ((equal name '(setf slot-value-using-class))
1457            (update-slot-value-gf-info gf 'writer))
1458           ((eq name 'slot-boundp-using-class)
1459            (update-slot-value-gf-info gf 'boundp))
1460           ||#
1461           ((gf-precompute-dfun-and-emf-p arg-info)
1462            (multiple-value-bind (dfun cache info)
1463                (make-final-dfun-internal gf)
1464              (set-dfun gf dfun cache info) ; lest the cache be freed twice
1465              (update-dfun gf dfun cache info))))))
1466 \f
1467 (defmethod function-keywords ((method standard-method))
1468   (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1469       (analyze-lambda-list (if (consp method)
1470                                (early-method-lambda-list method)
1471                                (method-lambda-list method)))
1472     (declare (ignore nreq nopt keysp restp))
1473     (values keywords allow-other-keys-p)))
1474
1475 (defun method-ll->generic-function-ll (ll)
1476   (multiple-value-bind
1477       (nreq nopt keysp restp allow-other-keys-p keywords keyword-parameters)
1478       (analyze-lambda-list ll)
1479     (declare (ignore nreq nopt keysp restp allow-other-keys-p keywords))
1480     (remove-if (lambda (s)
1481                  (or (memq s keyword-parameters)
1482                      (eq s '&allow-other-keys)))
1483                ll)))
1484 \f
1485 ;;; This is based on the rules of method lambda list congruency defined in
1486 ;;; the spec. The lambda list it constructs is the pretty union of the
1487 ;;; lambda lists of all the methods. It doesn't take method applicability
1488 ;;; into account at all yet.
1489 (defmethod generic-function-pretty-arglist
1490            ((generic-function standard-generic-function))
1491   (let ((methods (generic-function-methods generic-function)))
1492     (if methods
1493       (let ((arglist ()))
1494         ;; arglist is constructed from the GF's methods - maybe with
1495         ;; keys and rest stuff added
1496         (multiple-value-bind (required optional rest key allow-other-keys)
1497             (method-pretty-arglist (car methods))
1498           (dolist (m (cdr methods))
1499             (multiple-value-bind (method-key-keywords
1500                                   method-allow-other-keys
1501                                   method-key)
1502                 (function-keywords m)
1503               ;; we've modified function-keywords to return what we want as
1504               ;;  the third value, no other change here.
1505               (declare (ignore method-key-keywords))
1506               (setq key (union key method-key))
1507               (setq allow-other-keys (or allow-other-keys
1508                                          method-allow-other-keys))))
1509           (when allow-other-keys
1510             (setq arglist '(&allow-other-keys)))
1511           (when key
1512             (setq arglist (nconc (list '&key) key arglist)))
1513           (when rest
1514             (setq arglist (nconc (list '&rest rest) arglist)))
1515           (when optional
1516             (setq arglist (nconc (list '&optional) optional arglist)))
1517           (nconc required arglist)))
1518       ;; otherwise we take the lambda-list from the GF directly, with no
1519       ;; other 'keys' added ...
1520       (let ((lambda-list (generic-function-lambda-list generic-function)))
1521         lambda-list))))
1522
1523 (defmethod method-pretty-arglist ((method standard-method))
1524   (let ((required ())
1525         (optional ())
1526         (rest nil)
1527         (key ())
1528         (allow-other-keys nil)
1529         (state 'required)
1530         (arglist (method-lambda-list method)))
1531     (dolist (arg arglist)
1532       (cond ((eq arg '&optional)         (setq state 'optional))
1533             ((eq arg '&rest)             (setq state 'rest))
1534             ((eq arg '&key)              (setq state 'key))
1535             ((eq arg '&allow-other-keys) (setq allow-other-keys t))
1536             ((memq arg lambda-list-keywords))
1537             (t
1538              (ecase state
1539                (required (push arg required))
1540                (optional (push arg optional))
1541                (key      (push arg key))
1542                (rest     (setq rest arg))))))
1543     (values (nreverse required)
1544             (nreverse optional)
1545             rest
1546             (nreverse key)
1547             allow-other-keys)))
1548