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