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