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